问:
editing a JSON file
First of all yes I did check other options, questions and answers but sadly those didn't work for me.

So I'm currently working on a small project including a shopping cart system.
The shopping cart system is created by a PHP session and everything works fine. Products can be added, rows can be deleted and the cart can be cleared completely.

Now I would like to add some functions like counting the items in the cart, calculating the total price and VAT prices. Since the session is stored as a JSON object I'm able to use angularjs and $http.get() to read the JSON cart object and redefine the data so it's usable in an ng-repeat for the view.

So when the visitor clicks on the "add to cart" button the following code is creating the session:

```<code>session_start();

$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);
// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price,
    "total_items" => 0
);

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($product_id and $product_size, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
    echo "<script> alert('Dit product staat al in de winkelwagen')</script>])";
}

// else, add the item to the array
else{
    $_SESSION['cart']["cartItems"][$product_id]=$cartProduct;
}
</code>```

So my first attempt was to add the following to the section "add the item to the array"

```<code>    $arr = json_decode($_SESSION['cart']['cartItems'][$product_id], true);
    $total_items['total_items'] = count($_SESSION['cart']);
    array_push($arr['cartItems'], $total_items);
</code>```

But sadly this didn't work. I also tried adding this to the getCart section.

```<code>session_start();

$json = json_encode($_SESSION['cart']["cartItems"]);
echo($json);
</code>```

Sadly also without any result.

So my question is how am I able to add the total_items calculation to the array. And how am I able to calculate the total price, VAT prices etc?

PS: the JSON outcome of one product:

```<code>{"16":{"id":"16","name":"TestDatumProduct","price":1000,"size":"M","quantity":"4","total_product_price":4000,"total_items":0}}
</code>```

UPDATE

So an update to combine the progress of the last few days:

So currently my code is based on the answer of @devionNL since i like the action method and the answer of @FranciscoRodríguez was barely an answer since he only adviced me about the counting method, (didn't work)

So using the action examples from @devionNL i've made some small changes and came up with the following code.

```<code><?php
session_start();
$cartItemID = $_REQUEST['cartItem_id'];
$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// Add to cart
if ($_REQUEST['action'] == 'addToCart')
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
    }
    else
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
        array_push($_SESSION['cart']['cartItems'], $cartProduct );
    }
}

// RemoveRow
else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        if ($_SESSION['cart']['cartItems']['totalItems'] > 1)
        {
            foreach ($cartDecode as $key => $cartItem)
            {
                // IF THE TITLE MATCHES THE SIGNAL STRING
                if ($cartItem->{"id"} == $cartItemID)
                {
                    // REMOVE THIS OBJECT
                    unset($cartDecode[$key]);
                }

            }
            $_SESSION['cart']['cartItems']['totalItems']--; // Deduct by 1.
        }
    else
        {
            $_SESSION['cart']['cartItems'] = $cartProduct;
        }
    }

    $_SESSION['cart']['cartItems']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['totalItems'];
    },
        $_SESSION['cart']['cartItems']));

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);
</code>```

So adding to the cart, and calculating the cartItems is working as expected. But i still can't find the way of removing a row. inside the cart. Next to that i'm still struggling with getting the total price of the cart. The JSON outcome is as following:

```<code>{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}
</code>```

The full cart in JSON would then be:

```<code>{"cartItems":{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}}
</code>```

So my questions are?
1. How am i able to delete a single row (ID == "", Then delete)
2. How am i able to calculate the full price of the cart?
3. For placing the order inside the dabatase, how would i be able to select each row? (id, name, etc). I was thinking in the way of using a foreach() statement?

If there are any questions please ask them in the comments.

As always, Thanks in advance!

答:
The best approach is to have your product information stored in a database and not let the client send all that info to the server, since you cannot initially verify that the client is telling the truth (read: Never trust client input).

Basically what the client should send is only Add/Remove and the productId it wants to add, you can ofcourse then return the full object with price and such but the client shouldn't be able to 'update' that price.

This assumes $product_id contains the product to be add or removed.

```<code>session_start();

// If the cart or cartItems isn't set, create empty
if (empty($_SESSION['cart']) || empty($_SESSION['cart']['cartItems']))
{
   $_SESSION['cart'] = array();
   $_SESSION['cart']['cartItems'] = array();
   $_SESSION['cart']['totalPrice'] = 0;
   $_SESSION['cart']['totalItems'] = 0;
}

// Search the cartItems for the column named productId that matches the $product_id. This can return null, so always verify with !empty.

$arrayKeyId = array_search($product_id, array_column($_SESSION['cart']['cartItems'], 'productId'));

if ($_REQUEST['action'] == 'add')
{
  if (!empty($arrayKeyId)) // If it isn't empty, append to  the quantity
     $_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems']++;
  else // It's new: Add it to the array
     $_SESSION['cart']['cartItems'][] = $cartProduct;
}
else if ($_REQUEST['action'] == 'delete') // If you want a delete action
{
  if (!empty($arrayKeyId))
  {
   // If more than 1 quantity, lower by 1
   if ($_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems'] > 1)
       $_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems']--;
   else // Or if there was only 1, remove the item fully.
      unset($_SESSION['cart']['cartItems'][$arrayKeyId]);
  }
}

// Total price based on item count times their price.
$_SESSION['cart']['totalPrice'] = array_sum(array_map(function($item) {
    return $item['price'] * $item['totalItems'];
}, $_SESSION['cart']['cartItems']));

// Total items based on the total amount of cartItems (without their quantity)
$_SESSION['cart']['totalItems'] = count($_SESSION['cart']['cartItems']);

echo json_encode($_SESSION['cart']['cartItems']);
</code>```

Title: editing a JSON file

Body:
First of all yes I did check other options, questions and answers but sadly those didn't work for me.

So I'm currently working on a small project including a shopping cart system.
The shopping cart system is created by a PHP session and everything works fine. Products can be added, rows can be deleted and the cart can be cleared completely.

Now I would like to add some functions like counting the items in the cart, calculating the total price and VAT prices. Since the session is stored as a JSON object I'm able to use angularjs and $http.get() to read the JSON cart object and redefine the data so it's usable in an ng-repeat for the view.

So when the visitor clicks on the "add to cart" button the following code is creating the session:

session_start();

$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);
// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price,
    "total_items" => 0
);

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($product_id and $product_size, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
    echo "])";
}

// else, add the item to the array
else{
    $_SESSION['cart']["cartItems"][$product_id]=$cartProduct;
}

So my first attempt was to add the following to the section "add the item to the array"

    $arr = json_decode($_SESSION['cart']['cartItems'][$product_id], true);
    $total_items['total_items'] = count($_SESSION['cart']);
    array_push($arr['cartItems'], $total_items);

But sadly this didn't work. I also tried adding this to the getCart section.

session_start();

$json = json_encode($_SESSION['cart']["cartItems"]);
echo($json);

Sadly also without any result.

So my question is how am I able to add the total_items calculation to the array. And how am I able to calculate the total price, VAT prices etc?

PS: the JSON outcome of one product:

{"16":{"id":"16","name":"TestDatumProduct","price":1000,"size":"M","quantity":"4","total_product_price":4000,"total_items":0}}

UPDATE

So an update to combine the progress of the last few days:

So currently my code is based on the answer of @devionNL since i like the action method and the answer of @FranciscoRodríguez was barely an answer since he only adviced me about the counting method, (didn't work)

So using the action examples from @devionNL i've made some small changes and came up with the following code.

<?php
session_start();
$cartItemID = $_REQUEST['cartItem_id'];
$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// Add to cart
if ($_REQUEST['action'] == 'addToCart')
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
    }
    else
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
        array_push($_SESSION['cart']['cartItems'], $cartProduct );
    }
}

// RemoveRow
else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        if ($_SESSION['cart']['cartItems']['totalItems'] > 1)
        {
            foreach ($cartDecode as $key => $cartItem)
            {
                // IF THE TITLE MATCHES THE SIGNAL STRING
                if ($cartItem->{"id"} == $cartItemID)
                {
                    // REMOVE THIS OBJECT
                    unset($cartDecode[$key]);
                }

            }
            $_SESSION['cart']['cartItems']['totalItems']--; // Deduct by 1.
        }
    else
        {
            $_SESSION['cart']['cartItems'] = $cartProduct;
        }
    }

    $_SESSION['cart']['cartItems']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['totalItems'];
    },
        $_SESSION['cart']['cartItems']));

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);

So adding to the cart, and calculating the cartItems is working as expected. But i still can't find the way of removing a row. inside the cart. Next to that i'm still struggling with getting the total price of the cart. The JSON outcome is as following:

{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}

The full cart in JSON would then be:

{"cartItems":{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}}

So my questions are?
1. How am i able to delete a single row (ID == "", Then delete)
2. How am i able to calculate the full price of the cart?
3. For placing the order inside the dabatase, how would i be able to select each row? (id, name, etc). I was thinking in the way of using a foreach() statement?

If there are any questions please ask them in the comments.

As always, Thanks in advance!

Body:
The best approach is to have your product information stored in a database and not let the client send all that info to the server, since you cannot initially verify that the client is telling the truth (read: Never trust client input).

Basically what the client should send is only Add/Remove and the productId it wants to add, you can ofcourse then return the full object with price and such but the client shouldn't be able to 'update' that price.

This assumes $product_id contains the product to be add or removed.

session_start();

// If the cart or cartItems isn't set, create empty
if (empty($_SESSION['cart']) || empty($_SESSION['cart']['cartItems']))
{
   $_SESSION['cart'] = array();
   $_SESSION['cart']['cartItems'] = array();
   $_SESSION['cart']['totalPrice'] = 0;
   $_SESSION['cart']['totalItems'] = 0;
}

// Search the cartItems for the column named productId that matches the $product_id. This can return null, so always verify with !empty.

$arrayKeyId = array_search($product_id, array_column($_SESSION['cart']['cartItems'], 'productId'));

if ($_REQUEST['action'] == 'add')
{
  if (!empty($arrayKeyId)) // If it isn't empty, append to  the quantity
     $_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems']++;
  else // It's new: Add it to the array
     $_SESSION['cart']['cartItems'][] = $cartProduct;
}
else if ($_REQUEST['action'] == 'delete') // If you want a delete action
{
  if (!empty($arrayKeyId))
  {
   // If more than 1 quantity, lower by 1
   if ($_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems'] > 1)
       $_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems']--;
   else // Or if there was only 1, remove the item fully.
      unset($_SESSION['cart']['cartItems'][$arrayKeyId]);
  }
}

// Total price based on item count times their price.
$_SESSION['cart']['totalPrice'] = array_sum(array_map(function($item) {
    return $item['price'] * $item['totalItems'];
}, $_SESSION['cart']['cartItems']));

// Total items based on the total amount of cartItems (without their quantity)
$_SESSION['cart']['totalItems'] = count($_SESSION['cart']['cartItems']);

echo json_encode($_SESSION['cart']['cartItems']);


来源: stackexchange

问:
How can I load Child entities dynamically in Entity Framework 6
I have a Provider class and an Article one. Article has a int ProviderId{get;set} and a public virtual Provider Provider {get;set;} properties.

I know about Lazy loading and why I can't access the Provider property in Article outside the context but I have a generic method that returns the next T like this:

```<code>public static T Next<T>(T currentElement) where T : class, IModel {
    T data;

    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities()) {
        data = context.Set<T>().Single(el => el.Id == currentElement.Id + 1);
    }

    return data;
}
</code>```

But I can't retrieve Child entities like Provider in Articles Class. How can I include all entities? Should I update the method and make one per entity?

I read about Eager loading and Explicit loading but I don't know how can I implement these in my method.

Note:

Not all my entities have entity children and I have more methods like Previous<T>(), First<T>() or Last<T>() that do the work you expect.

答:
You could create an overload of your Next method that accepts an Expression<Func<T, object>>:

```<code>public static T Next<T>(T currentElement, Expression<Func<T, object>> navigationProperty) where T : class, IModel
{
    T data;

    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities())
    {
        IQueryable<T> dbQuery = context.Set<T>();
        if (navigationProperty != null)
            dbQuery = dbQuery.Include<T, object>(navigationProperty);

        data = dbQuery.AsNoTracking().Single(el => el.Id == currentElement.Id + 1);
    }
    return data;
}
</code>```

Usage:

```<code>var entity = Next(instance, x => x.Provider);
</code>```

Please refer to the following blog post for more information and a complete example.

Implementing a generic data access layer using Entity Framework: https://blog.magnusmontin.net/2013/05/30/generic-dal-using-entity-framework/

ContentLicense: CC BY-SA 3.0

Body:
I have a Provider class and an Article one. Article has a int ProviderId{get;set} and a public virtual Provider Provider {get;set;} properties.

I know about Lazy loading and why I can't access the Provider property in Article outside the context but I have a generic method that returns the next T like this:

public static T Next<T>(T currentElement) where T : class, IModel {
    T data;

    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities()) {
        data = context.Set<T>().Single(el => el.Id == currentElement.Id + 1);
    }

    return data;
}

But I can't retrieve Child entities like Provider in Articles Class. How can I include all entities? Should I update the method and make one per entity?

I read about Eager loading and Explicit loading but I don't know how can I implement these in my method.

Note:

Not all my entities have entity children and I have more methods like Previous<T>(), First<T>() or Last<T>() that do the work you expect.

Body:
You could create an overload of your Next method that accepts an Expression<Func<T, object>>:

public static T Next<T>(T currentElement, Expression<Func<T, object>> navigationProperty) where T : class, IModel
{
    T data;

    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities())
    {
        IQueryable<T> dbQuery = context.Set<T>();
        if (navigationProperty != null)
            dbQuery = dbQuery.Include<T, object>(navigationProperty);

        data = dbQuery.AsNoTracking().Single(el => el.Id == currentElement.Id + 1);
    }
    return data;
}

Usage:

var entity = Next(instance, x => x.Provider);

Please refer to the following blog post for more information and a complete example.

Implementing a generic data access layer using Entity Framework: https://blog.magnusmontin.net/2013/05/30/generic-dal-using-entity-framework/


问:
RadUpload From Telerik doesn't work inside sharepoint 2010 sites?
I have RadUpload from telerik inside Sharepoint 2010 Site Page , but DeleteSelected and Select Buttons Don't work

Is There any idea or workaround???

答: Do you receive any JavaScript errors when clicking on the 'Delete' button? The same functionality works fine in a simple ASP.NET page.</p>

ContentLicense: CC BY-SA 2.5


问:
Place .net control on the sheet
I am using spreadsheetgear, and I want to place the combobox (ComponentOne) into 1 cell. I want that when the user go to this cell, this combobox will activate and show the list to user. After user chose item on the list, it will place this item into the cell value and hide the combobox.
How to do it in Spreadsheetgear.

Thanks,

Doit

答:
I am not familiar with ComponentOne controls, so cannot really speak for that portion of your question.  However, regarding a more general approach to embedding custom controls onto a SpreadsheetGear WorkbookView UI control, this is possible by sub-classing the UIManager class, which would allow you to intercept the creation of existing shapes on a worksheet and replace them with your own custom controls.

Below is a simple example that demonstrates this with the Windows Forms WorkbookView control and a sub-class of SpreadsheetGear.Windows.Forms.UIManager.  This example just replaces a rectangle AutoShape with a button.  You could modify it to show a ComponentOne CheckBox instead.

Note that the UIManager.CreateCustomControl(...) method gets called anytime a shape is scrolled into view / made visible on the WorkbookView.  Also note that that your custom control will be disposed of every time it is scrolled out of view or otherwise made invisible.  Please see the documentation for more details on this API.

Another important point about shapes and worksheets in general--shapes are not embedded inside a cell.  Instead they hover over cells.  So there will be no explicit "link" between a given shape and a given cell.  The closest you could come to making such an association is with the IShape.TopLeftCell or BottomRightCell properties, which will provide the ranges for which this shape's respective edges reside over.  The IShape interface contains a number of other API that you might find useful in your use-case.  For instance, you can hide a shape by setting the IShape.Visible property to false.

```<code>using System;
using System.Windows.Forms;
using SpreadsheetGear;
using SpreadsheetGear.Shapes;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Create the UIManager replacement.
        new MyUIManager(workbookView1.ActiveWorkbookSet);
    }

    private void buttonRunSample_Click(object sender, EventArgs e)
    {
        // NOTE: Must acquire a workbook set lock.
        workbookView1.GetLock();
        try
        {
            // Get a reference to the active worksheet and window information.
            IWorksheetWindowInfo windowInfo = workbookView1.ActiveWorksheetWindowInfo;
            IWorksheet worksheet = workbookView1.ActiveWorksheet;

            // Get a reference to a cell.
            IRange cell = workbookView1.ActiveWorksheet.Cells["B2"];

            // Add a placeholder shape to the worksheet's shape collection.
            // This shape will be replaced with a custom control.
            double left = windowInfo.ColumnToPoints(cell.Column) + 5;
            double top = windowInfo.RowToPoints(cell.Row) + 5;
            double width = 100;
            double height = 30;
            IShape shape = worksheet.Shapes.AddShape(AutoShapeType.Rectangle, left, top, width, height);

            // Set the name of the shape for identification purposes.
            shape.Name = "MyCustomControl";
        }
        finally
        {
            // NOTE: Must release the workbook set lock.
            workbookView1.ReleaseLock();
        }
        buttonRunSample.Enabled = false;
    }

    // UIManager replacement class.
    private class MyUIManager : SpreadsheetGear.Windows.Forms.UIManager
    {
        private Button _customControl;

        public MyUIManager(IWorkbookSet workbookSet)
            : base(workbookSet)
        {
            _customControl = null;
        }

        // Override to substitute a custom control for any existing shape in the worksheet.
        // This method is called when a control is first displayed within the WorkbookView.
        public override System.Windows.Forms.Control CreateCustomControl(IShape shape)
        {
            // If the shape name matches...
            if (String.Equals(shape.Name, "MyCustomControl"))
            {
                // Verify that a control does not already exist.
                System.Diagnostics.Debug.Assert(_customControl == null);

                // Create a custom control and set various properties.
                _customControl = new Button();
                _customControl.Text = "My Custom Button";

                // Add a Click event handler.
                _customControl.Click += new EventHandler(CustomControl_Click);

                // Add an event handler so that we know when the control
                // has been disposed.  The control will be disposed when
                // it is no longer in the viewable area of the WorkbookView.
                _customControl.Disposed += new EventHandler(CustomControl_Disposed);

                return _customControl;
            }
            return base.CreateCustomControl(shape);
        }

        private void CustomControl_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Custom Control was Clicked!");
        }

        private void CustomControl_Disposed(object sender, EventArgs e)
        {
            // Add any cleanup code here...

            // Set the custom control reference to null.
            _customControl = null;
        }
    }
}
</code>```

Title: Place .net control on the sheet

Body:
I am not familiar with ComponentOne controls, so cannot really speak for that portion of your question.  However, regarding a more general approach to embedding custom controls onto a SpreadsheetGear WorkbookView UI control, this is possible by sub-classing the UIManager class, which would allow you to intercept the creation of existing shapes on a worksheet and replace them with your own custom controls.

Below is a simple example that demonstrates this with the Windows Forms WorkbookView control and a sub-class of SpreadsheetGear.Windows.Forms.UIManager.  This example just replaces a rectangle AutoShape with a button.  You could modify it to show a ComponentOne CheckBox instead.

Note that the UIManager.CreateCustomControl(...) method gets called anytime a shape is scrolled into view / made visible on the WorkbookView.  Also note that that your custom control will be disposed of every time it is scrolled out of view or otherwise made invisible.  Please see the documentation for more details on this API.

Another important point about shapes and worksheets in general--shapes are not embedded inside a cell.  Instead they hover over cells.  So there will be no explicit "link" between a given shape and a given cell.  The closest you could come to making such an association is with the IShape.TopLeftCell or BottomRightCell properties, which will provide the ranges for which this shape's respective edges reside over.  The IShape interface contains a number of other API that you might find useful in your use-case.  For instance, you can hide a shape by setting the IShape.Visible property to false.

using System;
using System.Windows.Forms;
using SpreadsheetGear;
using SpreadsheetGear.Shapes;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Create the UIManager replacement.
        new MyUIManager(workbookView1.ActiveWorkbookSet);
    }

    private void buttonRunSample_Click(object sender, EventArgs e)
    {
        // NOTE: Must acquire a workbook set lock.
        workbookView1.GetLock();
        try
        {
            // Get a reference to the active worksheet and window information.
            IWorksheetWindowInfo windowInfo = workbookView1.ActiveWorksheetWindowInfo;
            IWorksheet worksheet = workbookView1.ActiveWorksheet;

            // Get a reference to a cell.
            IRange cell = workbookView1.ActiveWorksheet.Cells["B2"];

            // Add a placeholder shape to the worksheet's shape collection.
            // This shape will be replaced with a custom control.
            double left = windowInfo.ColumnToPoints(cell.Column) + 5;
            double top = windowInfo.RowToPoints(cell.Row) + 5;
            double width = 100;
            double height = 30;
            IShape shape = worksheet.Shapes.AddShape(AutoShapeType.Rectangle, left, top, width, height);

            // Set the name of the shape for identification purposes.
            shape.Name = "MyCustomControl";
        }
        finally
        {
            // NOTE: Must release the workbook set lock.
            workbookView1.ReleaseLock();
        }
        buttonRunSample.Enabled = false;
    }

    // UIManager replacement class.
    private class MyUIManager : SpreadsheetGear.Windows.Forms.UIManager
    {
        private Button _customControl;

        public MyUIManager(IWorkbookSet workbookSet)
            : base(workbookSet)
        {
            _customControl = null;
        }

        // Override to substitute a custom control for any existing shape in the worksheet.
        // This method is called when a control is first displayed within the WorkbookView.
        public override System.Windows.Forms.Control CreateCustomControl(IShape shape)
        {
            // If the shape name matches...
            if (String.Equals(shape.Name, "MyCustomControl"))
            {
                // Verify that a control does not already exist.
                System.Diagnostics.Debug.Assert(_customControl == null);

                // Create a custom control and set various properties.
                _customControl = new Button();
                _customControl.Text = "My Custom Button";

                // Add a Click event handler.
                _customControl.Click += new EventHandler(CustomControl_Click);

                // Add an event handler so that we know when the control
                // has been disposed.  The control will be disposed when
                // it is no longer in the viewable area of the WorkbookView.
                _customControl.Disposed += new EventHandler(CustomControl_Disposed);

                return _customControl;
            }
            return base.CreateCustomControl(shape);
        }

        private void CustomControl_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Custom Control was Clicked!");
        }

        private void CustomControl_Disposed(object sender, EventArgs e)
        {
            // Add any cleanup code here...

            // Set the custom control reference to null.
            _customControl = null;
        }
    }
}


问:
Return Code on failure. Positive or negative?
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;
</code>```

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;
</code>```

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

答:
errno is a global variable you would set with the error number.  The convention is to set errno and then return a negative number (usually negative one).  The negative return value indicates errno should be checked.  Using your example (and putting it into a function), it might look like this:

```<code>int allocate_buffer(char *buffer) {
    buffer = malloc(1024);
    if (buffer == NULL) {
        errno = ENOMEM;
        return -1;
    }
    return 0;
}
</code>```

The caller would then know if there was an error based on the return value, and check errno to see what the error was and decide how to proceed from there.

Body:
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

Body:
errno is a global variable you would set with the error number.  The convention is to set errno and then return a negative number (usually negative one).  The negative return value indicates errno should be checked.  Using your example (and putting it into a function), it might look like this:

int allocate_buffer(char *buffer) {
    buffer = malloc(1024);
    if (buffer == NULL) {
        errno = ENOMEM;
        return -1;
    }
    return 0;
}

The caller would then know if there was an error based on the return value, and check errno to see what the error was and decide how to proceed from there.


问:
Disposing object in async event C# WPF
Im usign Kinect SDK in a WPF application and im listenting the DepthFrameReady event to make some operations. In order to avoid UI blocks i made the event async and im "awaiting" the function that made the data operations.

Rigth now in the output window in visual studio im getting the message:

WARNING: An imageFrame instance was not disposed

I tried many things to dispose the DepthImageFrame (put logic inside usingblock, callback when async function ends, etc...) but after first call it is sending null, so...

Which is the rigth way to dispose the object in async/await events?.

MyWindow.xaml.cs

```<code>private async void KinectSensorFound_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
{

   // as suggested in Zoran Answer
   await Task.Run(() =>
            {
                using (DepthImageFrame DataDepthImageFrame = e.OpenDepthImageFrame())
                {
                    UpdateUserDepthInfo(DataDepthImageFrame);
                }

            });
}

 public void UpdateUserDepthInfo(DepthImageFrame DataDepthImage)
        {
            var TimeNow = DateTime.Now;
            if ((DateTime.Now - PreviusTime).Milliseconds <= 50)
                return;

            syncronizationContext.Post(new SendOrPostCallback(o =>
            {
                if (chckbxDepthImage.IsChecked == true)
                {
                   chckbxColorImage.IsChecked = false;
                   // This method is called in my bussines logic to do a transformation with the frame
                   BitmapSource DepthBitMapSource = Controller.getInfoOfDepthUser(DataDepthImage);
                   DepthCanvas.Background = new ImageBrush(DepthBitMapSource);
                }
                else
                {
                    DepthCanvas.Children.Clear();
                    DepthCanvas.Background = new SolidColorBrush(Colors.Transparent);
                }

                DepthUserInfo = Controller.DoGetInfoDepthUser(DataDepthImage);
                lblDepthUser.Content = string.Format("{0:0.00} mts", DepthUserInfo / 1000);

            }), DataDepthImage);
            PreviusTime = TimeNow;
        }
</code>```

KinectHelper.cs

```<code>public BitmapSource getBitmapOfDepth(DepthImageFrame DataImageFrame)
{
    DepthImagePixel[] ImageDepth = new DepthImagePixel[0];
    int DepthDistance;
    depthReturnStruct DepthReturn = new depthReturnStruct();

    if (DataImageFrame != null)
    {
        ImageDepth = new DepthImagePixel[DataImageFrame.PixelDataLength];
        DataImageFrame.CopyDepthImagePixelDataTo(ImageDepth); // exception here

        //... other code
    }
    return bitmapDepth;
}
</code>```

答:
My impression here is that you are mixing responsibilities. To make things clear, every object should have an owner - the one who instantiates it and disposes it. In your solution, those are two entities - the event handler which constructs the DataDepthImageFrame, and the task which does the work.

In my opinion, the function which starts the task shouldn't construct the image frame, but instead prepare a factory function for it. That would allow the task to both instantiate and dispose the object. In that way, the task would be entirely responsible for that object.

Of course, if you plan to capture the factory in the closure, then you don't even need it - you can capture event arguments e and use them in the task directly.

```<code>private async void KinectSensorFound_DepthFrameReady(
    object sender, DepthImageFrameReadyEventArgs e)
{
   await Task.Run(
     () =>
     {
       using (DepthImageFrame DataDepthImageFrame = e.OpenDepthImageFrame())
       {
           UpdateUserDepthInfo(DataDepthImageFrame)
       }
   });
}
</code>```

I cannot reproduce your scenario, but I believe that the image frame from the event arguments will survive to be opened in another thread when the task starts running.

Title: Disposing object in async event C# WPF

Body:
Im usign Kinect SDK in a WPF application and im listenting the DepthFrameReady event to make some operations. In order to avoid UI blocks i made the event async and im "awaiting" the function that made the data operations.

Rigth now in the output window in visual studio im getting the message:

WARNING: An imageFrame instance was not disposed

I tried many things to dispose the DepthImageFrame (put logic inside usingblock, callback when async function ends, etc...) but after first call it is sending null, so...

Which is the rigth way to dispose the object in async/await events?.

MyWindow.xaml.cs

private async void KinectSensorFound_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
{

   // as suggested in Zoran Answer
   await Task.Run(() =>
            {
                using (DepthImageFrame DataDepthImageFrame = e.OpenDepthImageFrame())
                {
                    UpdateUserDepthInfo(DataDepthImageFrame);
                }

            });
}

 public void UpdateUserDepthInfo(DepthImageFrame DataDepthImage)
        {
            var TimeNow = DateTime.Now;
            if ((DateTime.Now - PreviusTime).Milliseconds <= 50)
                return;

            syncronizationContext.Post(new SendOrPostCallback(o =>
            {
                if (chckbxDepthImage.IsChecked == true)
                {
                   chckbxColorImage.IsChecked = false;
                   // This method is called in my bussines logic to do a transformation with the frame
                   BitmapSource DepthBitMapSource = Controller.getInfoOfDepthUser(DataDepthImage);
                   DepthCanvas.Background = new ImageBrush(DepthBitMapSource);
                }
                else
                {
                    DepthCanvas.Children.Clear();
                    DepthCanvas.Background = new SolidColorBrush(Colors.Transparent);
                }

                DepthUserInfo = Controller.DoGetInfoDepthUser(DataDepthImage);
                lblDepthUser.Content = string.Format("{0:0.00} mts", DepthUserInfo / 1000);

            }), DataDepthImage);
            PreviusTime = TimeNow;
        }

KinectHelper.cs

public BitmapSource getBitmapOfDepth(DepthImageFrame DataImageFrame)
{
    DepthImagePixel[] ImageDepth = new DepthImagePixel[0];
    int DepthDistance;
    depthReturnStruct DepthReturn = new depthReturnStruct();

    if (DataImageFrame != null)
    {
        ImageDepth = new DepthImagePixel[DataImageFrame.PixelDataLength];
        DataImageFrame.CopyDepthImagePixelDataTo(ImageDepth); // exception here

        //... other code
    }
    return bitmapDepth;
}

Body:
My impression here is that you are mixing responsibilities. To make things clear, every object should have an owner - the one who instantiates it and disposes it. In your solution, those are two entities - the event handler which constructs the DataDepthImageFrame, and the task which does the work.

In my opinion, the function which starts the task shouldn't construct the image frame, but instead prepare a factory function for it. That would allow the task to both instantiate and dispose the object. In that way, the task would be entirely responsible for that object.

Of course, if you plan to capture the factory in the closure, then you don't even need it - you can capture event arguments e and use them in the task directly.

private async void KinectSensorFound_DepthFrameReady(
    object sender, DepthImageFrameReadyEventArgs e)
{
   await Task.Run(
     () =>
     {
       using (DepthImageFrame DataDepthImageFrame = e.OpenDepthImageFrame())
       {
           UpdateUserDepthInfo(DataDepthImageFrame)
       }
   });
}

I cannot reproduce your scenario, but I believe that the image frame from the event arguments will survive to be opened in another thread when the task starts running.


问:
Deprecation of the static keyword... no more?
In C++ it is possible to use the static keyword within a translation unit to affect the visibility of a symbol (either variable or function declaration).

In n3092, this was deprecated:

Annex D.2 [depr.static]

  The use of the static keyword is deprecated when declaring objects in namespace scope (see 3.3.6).

In n3225, this has been removed.

The only article I could find is somewhat informal.

It does underline though, that for compatibility with C (and the ability to compile C-programs as C++) the deprecation is annoying. However, compiling a C program directly as C++ can be a frustrating experience already, so I am unsure if it warrants consideration.

Does anyone know why it was changed ?

答:
Deprecated or not, removing this language feature would break existing codes and annoy people.

The whole static deprecation thing was just wishful thinking along the lines of "anonymous namespaces are better than static" and "references are better pointers". Lol.

ContentLicense: CC BY-SA 4.0


问:
Cannot Post CSV file in Python
I'm having problems with a CSV file upload with requests.post method in python 3.

```<code>from requests.auth import HTTPBasicAuth
import csv
import requests

user='myuser'
pw='mypass'
advertiserid='10550'
campaignid='12394'
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
csv="myfile.csv"

with open(csv, 'r') as f:
    r = requests.post(url, files={csv: f})
    print(r)
</code>```

The output is 'Response [502]'

Any idea of what could be the problem?

Many thanks!

答:
```<code>csv="myfile.csv"

url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'

files = {'upload_file': open(csv,'rb')}

r = requests.post(url, files=files)
</code>```

Title: Cannot Post CSV file in Python

Body:
I'm having problems with a CSV file upload with requests.post method in python 3.

from requests.auth import HTTPBasicAuth
import csv
import requests

user='myuser'
pw='mypass'
advertiserid='10550'
campaignid='12394'
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
csv="myfile.csv"

with open(csv, 'r') as f:
    r = requests.post(url, files={csv: f})
    print(r)

The output is 'Response [502]'

Any idea of what could be the problem?

Many thanks!


问:
Command Prompt cannot find or run my Java File
New programmer here, in terms of actually using an editor and running it. I have created a simple program that states this.

```<code>public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }
}
</code>```

I have already set the path to "C:\Program Files\Java\jdk1.8.0_151\bin\".(current version"1.8.0_151"). In the cmd input, "java" and "javac" work until I attempt to find a file name either "HelloWorld.java" or "HelloWorld". How do I get cmd to find and run my java file? Thank you!

答:
you compile with javac
eg:

```<code>javac HelloWorld.java
</code>```

you run the compiled byte code using java. You need to place yourself in the directory containing the compiled bytecode
eg

```<code>C:\introcs\hello\>java HelloWorld
Hello, World
</code>```

Body:
New programmer here, in terms of actually using an editor and running it. I have created a simple program that states this.

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }
}

I have already set the path to "C:\Program Files\Java\jdk1.8.0_151\bin\".(current version"1.8.0_151"). In the cmd input, "java" and "javac" work until I attempt to find a file name either "HelloWorld.java" or "HelloWorld". How do I get cmd to find and run my java file? Thank you!

Body:
you compile with javac
eg:

javac HelloWorld.java

you run the compiled byte code using java. You need to place yourself in the directory containing the compiled bytecode
eg

C:\introcs\hello\>java HelloWorld
Hello, World


问:
Iterating through an arraylist in a hashmap based on key in JSTL
I have a hashmap as Map<String, List<String>> coverageDataMap.
I need to iterate through the list returned by it based on a key.

I'm doing it the following way:

```<code>    <c:forEach items="${bean.coverageDataMap['my_key']}"
            var="entry" varStatus="loop">
        <tr>
            <td><h:outputText value="#{loop.index+1}"/></td>
            <td><h:outputText value="#{entry}"/></td>
        </tr>
    </c:forEach>
</code>```

Unfortunately it doesn't work. I've looked around but couldn't find anything. Please let me know what did I get wrong here! Thanks.

答:
Run a test with following code, working as required.
Check if the "my_key" is set.

test.xhtml

```<code><html xmlns="http://www.w3.org/1999/xhtml" lang="en"
  xmlns:h="http://xmlns.jcp.org/jsf/html"
  xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
    <title>Test</title>
</h:head>
<h:body>
   Key is set:<h:outputText value="${bean.coverageDataMap['my_key'] ne null}"/>
   <br/>
   <br/>
    <c:forEach items="${bean.coverageDataMap['my_key']}"
               var="entry" varStatus="loop">
        <tr>
            <td><h:outputText value="#{loop.index+1}"/></td>
            <td><h:outputText value="#{entry}"/></td>
        </tr>
    </c:forEach>
</h:body>
</code>```

TestBean.java

```<code>@ManagedBean(name = "bean")
@RequestScoped
public class TestBean implements Serializable{

private static final long serialVersionUID = 1L;

Map<String, List<String>> coverageDataMap;

public TestBean() {
    coverageDataMap = new HashMap<>();
    ArrayList<String> list = new ArrayList<>();
    for (int i = 1; i <= 10; i++) {
        list.add("hello" + i);
    }
    coverageDataMap.put("my_key", list);
}

public Map<String, List<String>> getCoverageDataMap() {
    return coverageDataMap;
}

public void setCoverageDataMap(Map<String, List<String>> coverageDataMap) {
    this.coverageDataMap = coverageDataMap;
}
}
</code>```

Body:
I have a hashmap as Map<String, List<String>> coverageDataMap.
I need to iterate through the list returned by it based on a key.

I'm doing it the following way:

    <c:forEach items="${bean.coverageDataMap['my_key']}"
            var="entry" varStatus="loop">

            <h:outputText value="#{loop.index+1}"/>
            <h:outputText value="#{entry}"/>

    </c:forEach>

Unfortunately it doesn't work. I've looked around but couldn't find anything. Please let me know what did I get wrong here! Thanks.

Body:
Run a test with following code, working as required.
Check if the "my_key" is set.

test.xhtml

<html xmlns="http://www.w3.org/1999/xhtml" lang="en"
  xmlns:h="http://xmlns.jcp.org/jsf/html"
  xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
    <title>Test</title>
</h:head>
<h:body>
   Key is set:<h:outputText value="${bean.coverageDataMap['my_key'] ne null}"/>
   <br/>
   <br/>
    <c:forEach items="${bean.coverageDataMap['my_key']}"
               var="entry" varStatus="loop">
        <tr>
            <td><h:outputText value="#{loop.index+1}"/></td>
            <td><h:outputText value="#{entry}"/></td>
        </tr>
    </c:forEach>
</h:body>

TestBean.java

@ManagedBean(name = "bean")
@RequestScoped
public class TestBean implements Serializable{

private static final long serialVersionUID = 1L;

Map<String, List<String>> coverageDataMap;

public TestBean() {
    coverageDataMap = new HashMap<>();
    ArrayList<String> list = new ArrayList<>();
    for (int i = 1; i <= 10; i++) {
        list.add("hello" + i);
    }
    coverageDataMap.put("my_key", list);
}

public Map<String, List<String>> getCoverageDataMap() {
    return coverageDataMap;
}

public void setCoverageDataMap(Map<String, List<String>> coverageDataMap) {
    this.coverageDataMap = coverageDataMap;
}
}


问:
ItemSource in Tree View MVVM Style... I can't get it to bind properly
I can't seem to use the ItemSource Tag for my treeview.  I don't unerstand the problem..
I am trying a simple tree view before i actually bind to my database.. I a looking for an MVVM Style solution

Here is My view Model

```<code>    public class TreeViewVM : ViewModelBase
    {

        public class Topic
        {
            public string Title { get; set; }
            public int Rating { get; set; }
            private ObservableCollection<Topic> childTopicsValue = new ObservableCollection<Topic>();
            public ObservableCollection<Topic> ChildTopics {
                get
                {
                    return childTopicsValue;
                }
                set
                {
                    childTopicsValue = value;
                }
            }
            public Topic() {}
            public Topic(string title, int rating)
            {
               Title = title;
               Rating = rating;
            }
        }

        static public ObservableCollection<Topic> Users = new ObservableCollection<Topic>();

        public TreeViewVM()
        {

            Users.Add(new Topic("Using Controls and Dialog Boxes", -1));
            Users.Add(new Topic("Getting Started with Controls", 1));
            Topic DataGridTopic = new Topic("DataGrid", 4);
            DataGridTopic.ChildTopics.Add(
                new Topic("Default Keyboard and Mouse Behavior in the DataGrid Control", -1));
            DataGridTopic.ChildTopics.Add(
                new Topic("How to: Add a DataGrid Control to a Page", -1));
            DataGridTopic.ChildTopics.Add(
                new Topic("How to: Display and Configure Row Details in the DataGrid Control", 1));
            Users.Add(DataGridTopic);
            Topics = Users;
        }

        private ObservableCollection<Topic> _Topics { get; set; }
        public ObservableCollection<Topic> Topics
        {
            get
            {
                return _Topics;
            }
            set
            {
                if (_Topics != value)
                {
                    _Topics = value;
                    OnNotifyPropertyChanged("Topics");
                }
            }
        }

    }
}
</code>```

Here is my Xaml

```<code>xmlns:converter="clr-namespace:TestTree"
xmlns:viewModel="clr-namespace:TestTree.ViewModel"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<UserControl.Resources>
    <viewModel:TreeViewVM x:Key="ViewModel" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource Topics}}">
    <StackPanel x:Name="LayoutRoot2" Background="White">
        <StackPanel.Resources>
            <sdk:HierarchicalDataTemplate x:Key="ChildTemplate"  >
                <TextBlock FontStyle="Italic" Text="{Binding Path=Title}" />
            </sdk:HierarchicalDataTemplate>
            <sdk:HierarchicalDataTemplate x:Key="NameTemplate"
        ItemsSource="{Binding Path=ChildTopics}"
        ItemTemplate="{StaticResource ChildTemplate}">
                <TextBlock Text="{Binding Path=Title}" FontWeight="Bold" />
            </sdk:HierarchicalDataTemplate>
        </StackPanel.Resources>
        <sdk:TreeView Width="400"  Height="300" DataContext="{Binding Path=Topics}" ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" />
    </StackPanel>
</code>```

答:
First of all you set DataContext of the "LayourRoot" grid to a resource with key "Topics" which does not exist. That probably should be the "ViewModel" resource. Second of all, why can't you use the ItemsSource property on the TreeView? Setting DataContext property on the TreeView alone will not work. Here is the correct XAML:</p>

```<code><UserControl x:Class="MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
    <UserControl.Resources>
        <viewModel:TreeViewVM x:Key="ViewModel" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource ViewModel}}">
        <StackPanel x:Name="LayoutRoot2" Background="White">
            <StackPanel.Resources>
                <sdk:HierarchicalDataTemplate x:Key="ChildTemplate"  >
                    <TextBlock FontStyle="Italic" Text="{Binding Path=Title}" />
                </sdk:HierarchicalDataTemplate>
                <sdk:HierarchicalDataTemplate x:Key="NameTemplate"
        ItemsSource="{Binding Path=ChildTopics}"
        ItemTemplate="{StaticResource ChildTemplate}">
                    <TextBlock Text="{Binding Path=Title}" FontWeight="Bold" />
                </sdk:HierarchicalDataTemplate>
            </StackPanel.Resources>
            <sdk:TreeView Width="400"  Height="300" ItemsSource="{Binding Path=Topics}" ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" />
        </StackPanel>
    </Grid>
</UserControl>
</code>```

Body:
I can't seem to use the ItemSource Tag for my treeview.  I don't unerstand the problem..
I am trying a simple tree view before i actually bind to my database.. I a looking for an MVVM Style solution

Here is My view Model

    public class TreeViewVM : ViewModelBase
    {

        public class Topic
        {
            public string Title { get; set; }
            public int Rating { get; set; }
            private ObservableCollection<Topic> childTopicsValue = new ObservableCollection<Topic>();
            public ObservableCollection<Topic> ChildTopics {
                get
                {
                    return childTopicsValue;
                }
                set
                {
                    childTopicsValue = value;
                }
            }
            public Topic() {}
            public Topic(string title, int rating)
            {
               Title = title;
               Rating = rating;
            }
        }

        static public ObservableCollection<Topic> Users = new ObservableCollection<Topic>();

        public TreeViewVM()
        {

            Users.Add(new Topic("Using Controls and Dialog Boxes", -1));
            Users.Add(new Topic("Getting Started with Controls", 1));
            Topic DataGridTopic = new Topic("DataGrid", 4);
            DataGridTopic.ChildTopics.Add(
                new Topic("Default Keyboard and Mouse Behavior in the DataGrid Control", -1));
            DataGridTopic.ChildTopics.Add(
                new Topic("How to: Add a DataGrid Control to a Page", -1));
            DataGridTopic.ChildTopics.Add(
                new Topic("How to: Display and Configure Row Details in the DataGrid Control", 1));
            Users.Add(DataGridTopic);
            Topics = Users;
        }

        private ObservableCollection<Topic> _Topics { get; set; }
        public ObservableCollection<Topic> Topics
        {
            get
            {
                return _Topics;
            }
            set
            {
                if (_Topics != value)
                {
                    _Topics = value;
                    OnNotifyPropertyChanged("Topics");
                }
            }
        }

    }
}

Here is my Xaml

xmlns:converter="clr-namespace:TestTree"
xmlns:viewModel="clr-namespace:TestTree.ViewModel"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<UserControl.Resources>
    <viewModel:TreeViewVM x:Key="ViewModel" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource Topics}}">
    <StackPanel x:Name="LayoutRoot2" Background="White">
        <StackPanel.Resources>
            <sdk:HierarchicalDataTemplate x:Key="ChildTemplate"  >
                <TextBlock FontStyle="Italic" Text="{Binding Path=Title}" />
            </sdk:HierarchicalDataTemplate>
            <sdk:HierarchicalDataTemplate x:Key="NameTemplate"
        ItemsSource="{Binding Path=ChildTopics}"
        ItemTemplate="{StaticResource ChildTemplate}">
                <TextBlock Text="{Binding Path=Title}" FontWeight="Bold" />
            </sdk:HierarchicalDataTemplate>
        </StackPanel.Resources>
        <sdk:TreeView Width="400"  Height="300" DataContext="{Binding Path=Topics}" ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" />
    </StackPanel>

Body:
First of all you set DataContext of the "LayourRoot" grid to a resource with key "Topics" which does not exist. That probably should be the "ViewModel" resource. Second of all, why can't you use the ItemsSource property on the TreeView? Setting DataContext property on the TreeView alone will not work. Here is the correct XAML:

<UserControl x:Class="MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
    <UserControl.Resources>
        <viewModel:TreeViewVM x:Key="ViewModel" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource ViewModel}}">
        <StackPanel x:Name="LayoutRoot2" Background="White">
            <StackPanel.Resources>
                <sdk:HierarchicalDataTemplate x:Key="ChildTemplate"  >
                    <TextBlock FontStyle="Italic" Text="{Binding Path=Title}" />
                </sdk:HierarchicalDataTemplate>
                <sdk:HierarchicalDataTemplate x:Key="NameTemplate"
        ItemsSource="{Binding Path=ChildTopics}"
        ItemTemplate="{StaticResource ChildTemplate}">
                    <TextBlock Text="{Binding Path=Title}" FontWeight="Bold" />
                </sdk:HierarchicalDataTemplate>
            </StackPanel.Resources>
            <sdk:TreeView Width="400"  Height="300" ItemsSource="{Binding Path=Topics}" ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" />
        </StackPanel>
    </Grid>
</UserControl>


问:
FileName -FilePath comparison
I'm trying to compare the 2 file names.

I build a file name and then compare it to the one in the directory. My code is not able to compare the strings. Please let me know, what am I doing wrong? There are no errors, but the the strings is never equal.

```<code>DateTime dt = DateTime.Now;
Filename = "Account Daily " + dt.ToString("yyyy-MM-dd") + " .xslx";

FileInfo[] folderFiles = null;
folderFiles = dir1.GetFiles();
foreach (FileInfo aFile in folderFiles)
{
    if (String.Compare(aFile.ToString(),Filename) == 1)
    {
        // Send email with this attachment
    }
}
</code>```

答:
FileInfo.ToString() returns the whole access path (e.g. c:/temp/ file.xml)

Source : https://msdn.microsoft.com/library/system.io.fileinfo.tostring(v=vs.110).aspx

Unfortunately, the value you assigned to the Filename variable is a plain file name without the access path. Therefore it cannot be equal to anything FileInfo.ToString() gives you.

Suggestion : You could use aFile.Name instead of aFile.ToString()

Title: FileName -FilePath comparison

Body:
I'm trying to compare the 2 file names.

I build a file name and then compare it to the one in the directory. My code is not able to compare the strings. Please let me know, what am I doing wrong? There are no errors, but the the strings is never equal.

DateTime dt = DateTime.Now;
Filename = "Account Daily " + dt.ToString("yyyy-MM-dd") + " .xslx";

FileInfo[] folderFiles = null;
folderFiles = dir1.GetFiles();
foreach (FileInfo aFile in folderFiles)
{
    if (String.Compare(aFile.ToString(),Filename) == 1)
    {
        // Send email with this attachment
    }
}


答:
String.Compare returns 0 if the two arguments match. So if you want to enter the if, the comparison should check against that value.

Here's a reference:

```
|           Value           | Condition
|-------------------------- |---------------------------------------------------------------------------------
| Less than zero            | The first substring precedes the second substring in the sort order.
| Zero                      | The substrings occur in the same position in the sort order, or length is zero.
| GreaterGreater than zero  | The first substring follows the second substring in the sort order.
```

Title: FileName -FilePath comparison

Body:
String.Compare returns 0 if the two arguments match. So if you want to enter the if, the comparison should check against that value.

Here's a reference:

|           Value           | Condition
|-------------------------- |---------------------------------------------------------------------------------
| Less than zero            | The first substring precedes the second substring in the sort order.
| Zero                      | The substrings occur in the same position in the sort order, or length is zero.
| GreaterGreater than zero  | The first substring follows the second substring in the sort order.


问:
Converting a CM Synergy archive to free source control
Because of downsizing and cost-saving our organisation is moving from CM/Telogic/Rational Synergy to free tools (most probably SVN). Is there anyway to transfer history and branch information from Synergy to a free tool? </p>

答:
I don't know of a native way to dump/import a CM Synergy source base into another SCM, which means the usual "generic import" tactic applies:

select some important baselines/labels/branches and load them one by one on the hard drive.

for each baseline, use that image as source to copy the files over the working directory of the target SCM (SVN or Git, Git can handle that kind of scenario very easily).

commit, then repeat for the next baseline/label/branch

But that means you loose some history and some metadata along the way.


问:
Unable to cast a object of type 'SZArrayEnumerator' to type 'System.Collections.Generic.IEnumerator' 1[System.String]'
I am writing a hash table using given interfaces, but I get the error says as the title at

```<code>return (IEnumerator<Key>)items.GetEnumerator();
</code>```

and

```<code> foreach (String first in ht);
</code>```

The entire code shown as below:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RIT_CS
{

public class NonExistentKey<Key> : Exception
{

    public Key BadKey { get; private set; }

    public NonExistentKey(Key k) :
        base("Non existent key in HashTable: " + k)
    {
        BadKey = k;
    }

}

interface Table<Key, Value> : IEnumerable<Key>
{

    void Put(Key k, Value v);

    bool Contains(Key k);

    Value Get(Key k);
}

public struct KeyValue<Key, Value>
{
    public Key K { get; set;}
    public Value V { get; set; }
}

class MyTable<Key, Value>:Table<Key, Value>
{
    private int size;
    private int count=0;
    private  LinkedList<KeyValue<Key, Value>>[] items;

    public MyTable(int size)
    {
        ...
    }

    public void SetSize(int size)
    {
        ...
    }
    public LinkedList<KeyValue<Key, Value>>[] GetItems()
    {
        return items;
    }
    protected int Getposition(Key k)
    {
       ...
    }
    protected LinkedList<KeyValue<Key, Value>> GetLinkedList(int position)
    {

        return items[position];
    }
  public  void Put(Key k, Value v)
    {
    }

 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  {
      return (System.Collections.IEnumerator)GetEnumerator();
  }

public  IEnumerator<Key> GetEnumerator()
  {

      return (IEnumerator<Key>)items.GetEnumerator();
  }

  public  bool Contains(Key k)
    {
    }
   public Value Get(Key k)
    {
    }

}

class TableFactory
{

    public static MyTable<Key, Value> Make<Key, Value>(int size = 100, double loadThreshold = 0.75)
    {
        MyTable<Key, Value> mytable = new MyTable<Key, Value>(size);
        return mytable;
    }

}

class MainClass
{
    public static void Main(string[] args)
    {
        MyTable<String, String> ht = TableFactory.Make<String, String>(10, 0.75);
        ht.Put("Joe", "Doe");
        ht.Put("Jane", "Brain");
        ht.Put("Chris", "Swiss");
        try
        {
            foreach (String first in ht)
            {
                Console.WriteLine(first + " -> " + ht.Get(first));
            }
            Console.WriteLine("=========================");

            ht.Put("Wavy", "Gravy");
            ht.Put("Chris", "Bliss");
           foreach (String first in ht)
            {
                Console.WriteLine(first + " -> " + ht.Get(first));
            }
            Console.WriteLine("=========================");

            Console.Write("Jane -> ");
            Console.WriteLine(ht.Get("Jane"));
            Console.Write("John -> ");
            Console.WriteLine(ht.Get("John"));
        }
        catch (NonExistentKey<String> nek)
        {
            Console.WriteLine(nek.Message);
            Console.WriteLine(nek.StackTrace);
        }

        Console.ReadLine();
    }
  }
}
</code>```

To look better, I deleted some irrelevant codes.

答:
Just use the first option from https://stackoverflow.com/a/1272677/3162415 and write:</p>

```<code>return ((IEnumerable<Key>)items).GetEnumerator();
</code>```

Body:
I am writing a hash table using given interfaces, but I get the error says as the title at

return (IEnumerator<Key>)items.GetEnumerator();

and

 foreach (String first in ht);

The entire code shown as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RIT_CS
{

public class NonExistentKey<Key> : Exception
{

    public Key BadKey { get; private set; }

    public NonExistentKey(Key k) :
        base("Non existent key in HashTable: " + k)
    {
        BadKey = k;
    }

}

interface Table<Key, Value> : IEnumerable<Key>
{

    void Put(Key k, Value v);

    bool Contains(Key k);

    Value Get(Key k);
}

public struct KeyValue<Key, Value>
{
    public Key K { get; set;}
    public Value V { get; set; }
}

class MyTable<Key, Value>:Table<Key, Value>
{
    private int size;
    private int count=0;
    private  LinkedList<KeyValue<Key, Value>>[] items;

    public MyTable(int size)
    {
        ...
    }

    public void SetSize(int size)
    {
        ...
    }
    public LinkedList<KeyValue<Key, Value>>[] GetItems()
    {
        return items;
    }
    protected int Getposition(Key k)
    {
       ...
    }
    protected LinkedList<KeyValue<Key, Value>> GetLinkedList(int position)
    {

        return items[position];
    }
  public  void Put(Key k, Value v)
    {
    }

 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  {
      return (System.Collections.IEnumerator)GetEnumerator();
  }

public  IEnumerator<Key> GetEnumerator()
  {

      return (IEnumerator<Key>)items.GetEnumerator();
  }

  public  bool Contains(Key k)
    {
    }
   public Value Get(Key k)
    {
    }

}

class TableFactory
{

    public static MyTable<Key, Value> Make<Key, Value>(int size = 100, double loadThreshold = 0.75)
    {
        MyTable<Key, Value> mytable = new MyTable<Key, Value>(size);
        return mytable;
    }

}

class MainClass
{
    public static void Main(string[] args)
    {
        MyTable<String, String> ht = TableFactory.Make<String, String>(10, 0.75);
        ht.Put("Joe", "Doe");
        ht.Put("Jane", "Brain");
        ht.Put("Chris", "Swiss");
        try
        {
            foreach (String first in ht)
            {
                Console.WriteLine(first + " -> " + ht.Get(first));
            }
            Console.WriteLine("=========================");

            ht.Put("Wavy", "Gravy");
            ht.Put("Chris", "Bliss");
           foreach (String first in ht)
            {
                Console.WriteLine(first + " -> " + ht.Get(first));
            }
            Console.WriteLine("=========================");

            Console.Write("Jane -> ");
            Console.WriteLine(ht.Get("Jane"));
            Console.Write("John -> ");
            Console.WriteLine(ht.Get("John"));
        }
        catch (NonExistentKey<String> nek)
        {
            Console.WriteLine(nek.Message);
            Console.WriteLine(nek.StackTrace);
        }

        Console.ReadLine();
    }
  }
}

To look better, I deleted some irrelevant codes.

Body:
Just use the first option from https://stackoverflow.com/a/1272677/3162415 and write:

return ((IEnumerable<Key>)items).GetEnumerator();


问:
different casting double type to unsigned long long type result in c++ from windows and linux
I want to get a result from casting double type to usigned long long type in c++. But that code have different result from Windows and Linux.
Here's my code. </p>

```<code>#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << (unsigned long long) pow(10, 18) << endl;
    return 0;
}
</code>```

<p>I just used 'pow' function to get 10 to the 18, and cast it to unsigned long long type. In Windows, It has result of 99999999999999999 (10^18-1), but It has result of 1000000000000000000 (10 ^18) in Linux.
I used MinGW g++ for C++11 compilation in Windows and use g++ in Linux.
What's the reason of this result? Thanks.  </p>

答:
The reason is that pow operates on floating-point values, and different implementations can produce values that differ slightly in their low bits. If you need exact integer results, do integer arithmetic.

Contrary to one of the comments in response to the question, converting the result of this call to unsigned long long is perfectly safe (for some sensible meaning of “safe”): unsigned long long can hold the value that this call to pow returns, and the resulting value will be the floating-point result with its fraction discarded.

Body:
I want to get a result from casting double type to usigned long long type in c++. But that code have different result from Windows and Linux.
Here's my code.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << (unsigned long long) pow(10, 18) << endl;
    return 0;
}

I just used 'pow' function to get 10 to the 18, and cast it to unsigned long long type. In Windows, It has result of 99999999999999999 (10^18-1), but It has result of 1000000000000000000 (10 ^18) in Linux.
I used MinGW g++ for C++11 compilation in Windows and use g++ in Linux.
What's the reason of this result? Thanks.