问:
wordpress text domain issue
so i testing my them from errs with theme check plugin
and go the text domain issue but it returns a blank value ! is this make any since !!

REQUIRED: This theme text domain does not match the theme's slug. The text domain used: This theme's correct slug and text-domain is osiris-rathemes.

/*
Theme Name: osiris rathemes
Theme URI: https://themeforest.net/user/ra-themes/portfolioa
Author: Mohamed Said
Author URI: https://themeforest.net/user/ra-themes
Description: some dec
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: osiris-rathemes

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/
```

theme folder name as the text domain
and the style.css have the text domain and its not an empty string

do i miss any thing !

答:
Maybe you need to load the theme textdomain in the functions.php file.  Your style.css file looks correct but I don't know what your theme plugin checker is doing.. </p>

```<code>function osiris_rathemes_setup() {
    load_theme_textdomain( 'osiris-rathemes', get_template_directory() . '/languages' );
}

add_action( 'after_setup_theme', 'osiris_rathemes_setup' );
</code>```

Title: wordpress text domain issue

Body:
so i testing my them from errs with theme check plugin
and go the text domain issue but it returns a blank value ! is this make any since !!

REQUIRED: This theme text domain does not match the theme's slug. The text domain used: This theme's correct slug and text-domain is osiris-rathemes.

/*
Theme Name: osiris rathemes
Theme URI: https://themeforest.net/user/ra-themes/portfolioa
Author: Mohamed Said
Author URI: https://themeforest.net/user/ra-themes
Description: some dec
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: osiris-rathemes

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/

theme folder name as the text domain
and the style.css have the text domain and its not an empty string

do i miss any thing !

Body:
Maybe you need to load the theme textdomain in the functions.php file.  Your style.css file looks correct but I don't know what your theme plugin checker is doing..

function osiris_rathemes_setup() {
    load_theme_textdomain( 'osiris-rathemes', get_template_directory() . '/languages' );
}

add_action( 'after_setup_theme', 'osiris_rathemes_setup' );


来源: stackexchange

问:
Prevent background image from stretching the view
Whenever I assign background to a view that is laid out with wrap_content, if the background image is larger than a view, the view is stretched so that it can hold the entire background. Why is it so and how to prevent it? It occurs even if the image is 9-patch and has stretchable areas marked - why isn't the image shrunk to the size of the view?</p>

答: Rather than using a background, you can use a FrameLayout with an ImageView as the first element.  Then use android:scaleType="center" so the image won't scale.  It will always be it's original size, and centered.  Then you can put whatever views you like on top of it in the FrameLayout.</p>

ContentLicense: CC BY-SA 2.5


问:
JS iterate over an object and remove the enabled false
I have a dynamic object with the following structure:

```<code>{
 a: {
  someKey: {
    propOne: '',
    enabled: true
  }
 },
 b: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
c: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
   someKey: {
      ab: {
        propOne: '',
        enabled: true
      }
     }
    }
</code>```

I need to remove the tree with the enabled false. So in the above example the result should be:

```<code> const result = {
     a: {
      someKey: {
        propOne: '',
        enabled: true
      }
     },

   d: {
      someKey: {
        propOne: '',
        enabled: true
      }
     }
    }
</code>```

How can I do this?

答:
With lodash:</p>

```<code>result = _.filter(test, o => o.ab.enabled)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dynamic object with the following structure:

{
 a: {
  someKey: {
    propOne: '',
    enabled: true
  }
 },
 b: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
c: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
   someKey: {
      ab: {
        propOne: '',
        enabled: true
      }
     }
    }

I need to remove the tree with the enabled false. So in the above example the result should be:

 const result = {
     a: {
      someKey: {
        propOne: '',
        enabled: true
      }
     },

   d: {
      someKey: {
        propOne: '',
        enabled: true
      }
     }
    }

How can I do this?

Body:
With lodash:

result = _.filter(test, o => o.ab.enabled)


问:
How to generate multiple orders from cart in Hybris storefront?
I'm working with Hybris 6.3 we generated a module for a B2B implementation  and I have the requirement of splitting the cart contents into different orders depending on the products in the cart, the billing address, payment, delivery, etc must share the same parameters.

From the requirements we've gathered from our client, we concluded applying consignments strategies aren't what we requiere here, since that handles one order and splits it for shipping and delivery purposes, instead our client's needs are that the different products in the cart to be grouped by a set of shared attributes and generate an order for each group of products.

So far I have identified the class in charge of placing the order in the storefront extension, DefaultCheckoutFacade, which contains the following method:

```<code> @Override
 public OrderData placeOrder() throws InvalidCartException
 {
     final CartModel cartModel = getCart();
     if (cartModel != null)
     {
         if (cartModel.getUser().equals(getCurrentUserForCheckout()) || getCheckoutCustomerStrategy().isAnonymousCheckout())
         {
             beforePlaceOrder(cartModel);
             final OrderModel orderModel = placeOrder(cartModel);
             afterPlaceOrder(cartModel, orderModel);
             if (orderModel != null)
             {
                 return getOrderConverter().convert(orderModel);
             }
         }
     }
     return null;
 }
</code>```

From what I understand, I should override this method to generate a different CartModel accordingly to the criteria set in my requirements and place an order for each CartModel. I revised the CartModel class, and it's superclass AbstractOrderModel, I'm guessing after the getCart() call in the method above, I just need to modify the entries in the CartModel and make a call to the method placeOrder() for each order I need to place, but is it allowed to modify the CartModel object in this way?

Or if I need to split my cart into different orders, should I approach this in a different way? Is something like having multiple carts but showing them as one something that should be done? Does this kind of modification should be done on the OOTB commercefacades extension? Is there a way to extend it somewhere in our module?

EDIT

I started to read about Multiple Carts and it seems to be what I need, but I haven't found how to save entries to a saved cart. In this link I can see how to save the cart, the method saveCart returns a CommerceSaveCartResultData object, both saveCart and the method getCartForCodeAndCurrentUser receive a CommerceSaveCartParameter which must contain a CartModel, how can I generate an instance of this object to set in a CommerceSaveCartParameter?

答: I think you need to use multiple cart. When user click checkout button with his wants, you can create new cart with out of list, then remove them from cart and go to process it. Because there is alot of calculation over cart, if you don't split as two cart, coupon and rules can be give to customer extra fees because of whole products.</p>

Body:
I'm working with Hybris 6.3 we generated a module for a B2B implementation  and I have the requirement of splitting the cart contents into different orders depending on the products in the cart, the billing address, payment, delivery, etc must share the same parameters.

From the requirements we've gathered from our client, we concluded applying consignments strategies aren't what we requiere here, since that handles one order and splits it for shipping and delivery purposes, instead our client's needs are that the different products in the cart to be grouped by a set of shared attributes and generate an order for each group of products.

So far I have identified the class in charge of placing the order in the storefront extension, DefaultCheckoutFacade, which contains the following method:

 @Override
 public OrderData placeOrder() throws InvalidCartException
 {
     final CartModel cartModel = getCart();
     if (cartModel != null)
     {
         if (cartModel.getUser().equals(getCurrentUserForCheckout()) || getCheckoutCustomerStrategy().isAnonymousCheckout())
         {
             beforePlaceOrder(cartModel);
             final OrderModel orderModel = placeOrder(cartModel);
             afterPlaceOrder(cartModel, orderModel);
             if (orderModel != null)
             {
                 return getOrderConverter().convert(orderModel);
             }
         }
     }
     return null;
 }

From what I understand, I should override this method to generate a different CartModel accordingly to the criteria set in my requirements and place an order for each CartModel. I revised the CartModel class, and it's superclass AbstractOrderModel, I'm guessing after the getCart() call in the method above, I just need to modify the entries in the CartModel and make a call to the method placeOrder() for each order I need to place, but is it allowed to modify the CartModel object in this way?

Or if I need to split my cart into different orders, should I approach this in a different way? Is something like having multiple carts but showing them as one something that should be done? Does this kind of modification should be done on the OOTB commercefacades extension? Is there a way to extend it somewhere in our module?

EDIT

I started to read about Multiple Carts and it seems to be what I need, but I haven't found how to save entries to a saved cart. In this link I can see how to save the cart, the method saveCart returns a CommerceSaveCartResultData object, both saveCart and the method getCartForCodeAndCurrentUser receive a CommerceSaveCartParameter which must contain a CartModel, how can I generate an instance of this object to set in a CommerceSaveCartParameter?


问:
Can I convert these data into json and send it with form POST instead of ajax
I have a 7 steps form and this is the last step which shows all the info the user typed in former pages. All the data is dynamically appended to each  using jQuery.

I need to wrap up these data into json format like below and send it to backend:

```<code>{
  "personal": {
    "gender": "F",
    "firstName": "Heeeeey",
    "lastName": "Beauty",
    "localName": "Girl",
    "birthday": "1992/10/28"
  },
  "interests": {
    "destinations": [
      "UK",
      "USA",
      "CA"
    ],
   }
 }
</code>```

Any method to do this??
The table structure looks like:

```<code><form action='/student-registration/process'>
    <hr>
    <div class="blue_font_title">ABOUT YOU
       <div class="link_page link_page_1" data-hook="form_step1"><span class="page_back_arrow"></span></div>
    </div>

    <table class="info_table" id="personal">
       <tbody>
          <tr>
            <td class="table_info_title">Gender:</td>
            <td class="table_info_ans student_gender" name="gender"></td>
          </tr>
          <tr>
            <td class="table_info_title">Local name:</td>
            <td class="table_info_ans student_local_name" name="localName"></td>
          </tr>
          <tr>
            <td class="table_info_title">First name:</td>
            <td class="table_info_ans student_eng_firstname" name="firstName"></td>
          </tr>
          <tr>
             <td class="table_info_title">Last name:</td>
             <td class="table_info_ans student_eng_lastname" name="lastName"></td>
          </tr>
          <tr>
             <td class="table_info_title">Birthday:</td>
             <td class="table_info_ans student_birthday" name="birthday"></td>
          </tr>
      </tbody>
  </table>
  <hr>
  <div class="blue_font_title">COUNTRY AND TIME YOU WANT TO GO
     <div class="link_page link_page_2" data-hook="form_step2"><span class="page_back_arrow"></span></div>
  </div>
  <table class="info_table" id="interest">
     <tbody>
        <tr>
           <td class="table_info_title">Destination:</td>
           <td class="table_info_ans student_study_destination"></td>
        </tr>
               ...
      </tbody>
   </table>
   <button type="submit" id="submit_button" class="submit_button">SUBMIT YOUR PROFILE</button>
</code>```

Now, I'm trying to wrap up these data into the format I want manually....

```<code>var personal_title_arr = [];
var personal_ans_arr = [];
var obj_per = {};
$('#personal tr').each(function() {
  var personal_title = $(this).find('.table_info_ans').attr('name');
  var personal_ans = $(this).find('.table_info_ans').text();

  personal_title_arr.push(personal_title);
  personal_ans_arr.push(personal_ans);
});

for (var i = 0; i < personal_title_arr.length; i++) {
    obj_per[personal_title_arr[i]] = personal_ans_arr[i];
}
var asJSON_per = JSON.stringify(obj_per);
</code>```

Because there are four tables in this form, so I have to wrap them up manually four times. I think the way I'm doing is really ridiculous..... Are there any tips that I can for loop just ONE time?

答:
Following will work in javascript. Try this:

Change the table as :

```<code><table class="info_table" id="personal" data-id="personal">
   <tbody>
      <tr>
        <td class="table_info_title">Gender:</td>
        <td class="table_info_ans student_gender" name="gender">F</td>
      </tr>
      <tr>
        <td class="table_info_title">Local name:</td>
        <td class="table_info_ans student_local_name" name="localName">Heeey</td>
      </tr>
      <tr>
        <td class="table_info_title">First name:</td>
        <td class="table_info_ans student_eng_firstname" name="firstName">Beauty</td>
      </tr>
      <tr>
         <td class="table_info_title">Last name:</td>
         <td class="table_info_ans student_eng_lastname" name="lastName">Girl</td>
      </tr>
      <tr>
         <td class="table_info_title">Birthday:</td>
         <td class="table_info_ans student_birthday" name="birthday">1992/10/28</td>
      </tr>
  </tbody>
</table>
<table class="info_table" id="interests" data-id="interests">
   <tbody>
      <tr>
        <td class="table_info_title">Destination:</td>
          <td class="table_info_ans student_gender" name="Destination" data-multi="true">US<br/>UK<br/>Canada</td>
      </tr>
      <tr>
        <td class="table_info_title">Year:</td>
        <td class="table_info_ans student_local_name" name="Year">2020</td>
      </tr>
      <tr>
        <td class="table_info_title">Month:</td>
        <td class="table_info_ans student_eng_firstname" name="Month">AUgust</td>
      </tr>
      <tr>
         <td class="table_info_title">Level of educaiton    :</td>
         <td class="table_info_ans student_eng_lastname" name="Level of educaiton" data-multi="true">Certificate<br/>Diploma<br/>masters</td>
      </tr>

  </tbody>
</table>
</code>```

Then use,

```<code><script>
var tables = $(".info_table");
    var finalObj = {};
    for(var i=0;i<tables.length;i++){
        var tempObj = {};
        $(tables[i]).find("tr").each(function(){
           var key = $(this).find(".table_info_ans").attr("name");
            if($(this).find(".table_info_ans").attr("data-multi")=="true"){
                tempObj[key] = $(this).find(".table_info_ans").html().split("<br>");
            }else{
                 tempObj[key] = $(this).find(".table_info_ans").html();
            }

        });
        var objId = $(tables[i]).attr("data-id");
        finalObj[objId] = tempObj;
    }
</script>
</code>```

the variable finalObj will have the data in the format you wanted.

Body:
I have a 7 steps form and this is the last step which shows all the info the user typed in former pages. All the data is dynamically appended to each  using jQuery.

I need to wrap up these data into json format like below and send it to backend:

{
  "personal": {
    "gender": "F",
    "firstName": "Heeeeey",
    "lastName": "Beauty",
    "localName": "Girl",
    "birthday": "1992/10/28"
  },
  "interests": {
    "destinations": [
      "UK",
      "USA",
      "CA"
    ],
   }
 }

Any method to do this??
The table structure looks like:

<form action='/student-registration/process'>

ABOUT YOU

            Gender:

            Local name:

            First name:

             Last name:

             Birthday:

COUNTRY AND TIME YOU WANT TO GO

           Destination:

               ...

   <button type="submit" id="submit_button" class="submit_button">SUBMIT YOUR PROFILE</button>

Now, I'm trying to wrap up these data into the format I want manually....

var personal_title_arr = [];
var personal_ans_arr = [];
var obj_per = {};
$('#personal tr').each(function() {
  var personal_title = $(this).find('.table_info_ans').attr('name');
  var personal_ans = $(this).find('.table_info_ans').text();

  personal_title_arr.push(personal_title);
  personal_ans_arr.push(personal_ans);
});

for (var i = 0; i < personal_title_arr.length; i++) {
    obj_per[personal_title_arr[i]] = personal_ans_arr[i];
}
var asJSON_per = JSON.stringify(obj_per);

Because there are four tables in this form, so I have to wrap them up manually four times. I think the way I'm doing is really ridiculous..... Are there any tips that I can for loop just ONE time?

Body:
Following will work in javascript. Try this:

Change the table as :

<table class="info_table" id="personal" data-id="personal">
   <tbody>
      <tr>
        <td class="table_info_title">Gender:</td>
        <td class="table_info_ans student_gender" name="gender">F</td>
      </tr>
      <tr>
        <td class="table_info_title">Local name:</td>
        <td class="table_info_ans student_local_name" name="localName">Heeey</td>
      </tr>
      <tr>
        <td class="table_info_title">First name:</td>
        <td class="table_info_ans student_eng_firstname" name="firstName">Beauty</td>
      </tr>
      <tr>
         <td class="table_info_title">Last name:</td>
         <td class="table_info_ans student_eng_lastname" name="lastName">Girl</td>
      </tr>
      <tr>
         <td class="table_info_title">Birthday:</td>
         <td class="table_info_ans student_birthday" name="birthday">1992/10/28</td>
      </tr>
  </tbody>
</table>
<table class="info_table" id="interests" data-id="interests">
   <tbody>
      <tr>
        <td class="table_info_title">Destination:</td>
          <td class="table_info_ans student_gender" name="Destination" data-multi="true">US<br/>UK<br/>Canada</td>
      </tr>
      <tr>
        <td class="table_info_title">Year:</td>
        <td class="table_info_ans student_local_name" name="Year">2020</td>
      </tr>
      <tr>
        <td class="table_info_title">Month:</td>
        <td class="table_info_ans student_eng_firstname" name="Month">AUgust</td>
      </tr>
      <tr>
         <td class="table_info_title">Level of educaiton    :</td>
         <td class="table_info_ans student_eng_lastname" name="Level of educaiton" data-multi="true">Certificate<br/>Diploma<br/>masters</td>
      </tr>

  </tbody>
</table>

Then use,

<script>
var tables = $(".info_table");
    var finalObj = {};
    for(var i=0;i<tables.length;i++){
        var tempObj = {};
        $(tables[i]).find("tr").each(function(){
           var key = $(this).find(".table_info_ans").attr("name");
            if($(this).find(".table_info_ans").attr("data-multi")=="true"){
                tempObj[key] = $(this).find(".table_info_ans").html().split("<br>");
            }else{
                 tempObj[key] = $(this).find(".table_info_ans").html();
            }

        });
        var objId = $(tables[i]).attr("data-id");
        finalObj[objId] = tempObj;
    }
</script>

the variable finalObj will have the data in the format you wanted.


问:
Access VBA: using `do while` loop to update a recordset
I would like to get a result using a do while loop.
However, my result gives only one record...

What I'm trying to do is:

Move through rs (record-set) records

Check if a value in rs is equal to rs2

If so, copy the username from rs to rs2

Move to the next record

```<code>Do While Not rs.BOF                                  ' No of records in rs
    Do While Not rs2.EOF                             ' No of records in rs2
        If Trim(rs2![pic_no]) = Trim(rs![pic]) Then
            rs![UserID] = rs2![NEW_USER]
            rs2.MoveNext
            rs.Update
        Else
            rs2.MoveNext
            rs.Update
        End If
    Loop

    rs.MovePrevious
    rs.Update
Loop
</code>```

答:
```<code>Do While Not rs.EOF                                  ' No of records in rs
    Do While Not rs2.EOF                             ' No of records in rs2
        If Trim(rs2![pic_no]) = Trim(rs![pic]) Then
            MsgBox rs!UserID
            rs.Edit
            rs.Fields("UserID") = rs2![NEW_USER]
            rs.Update
        End If
    rs2.MoveNext
    Loop
rs2.MoveFirst
rs.MoveNext
Loop

rs.Close
rs2.Close
Set rs = Nothing
Set rs2 = Nothing

End Sub
</code>```

But why don't you simply use an update statement?
Say you have two tables called TableUser (table you tefer to in rs) and TableNewUser (table you refer to in rs2).
Your update statement would like like:

```<code>UPDATE TableUser, TableNewUser
SET TableUser.UserID = TableNewUser.NEW_USER
WHERE TableUser.pic = TableNewUser.pic_no;
</code>```

Much easier. You can put this update statement in VBA code too (if there's a need/reason to do so).

Body:
I would like to get a result using a do while loop.
However, my result gives only one record...

What I'm trying to do is:

Move through rs (record-set) records

Check if a value in rs is equal to rs2

If so, copy the username from rs to rs2

Move to the next record

Do While Not rs.BOF                                  ' No of records in rs
    Do While Not rs2.EOF                             ' No of records in rs2
        If Trim(rs2![pic_no]) = Trim(rs![pic]) Then
            rs![UserID] = rs2![NEW_USER]
            rs2.MoveNext
            rs.Update
        Else
            rs2.MoveNext
            rs.Update
        End If
    Loop

    rs.MovePrevious
    rs.Update
Loop

Body:
Do While Not rs.EOF                                  ' No of records in rs
    Do While Not rs2.EOF                             ' No of records in rs2
        If Trim(rs2![pic_no]) = Trim(rs![pic]) Then
            MsgBox rs!UserID
            rs.Edit
            rs.Fields("UserID") = rs2![NEW_USER]
            rs.Update
        End If
    rs2.MoveNext
    Loop
rs2.MoveFirst
rs.MoveNext
Loop

rs.Close
rs2.Close
Set rs = Nothing
Set rs2 = Nothing

End Sub

But why don't you simply use an update statement?
Say you have two tables called TableUser (table you tefer to in rs) and TableNewUser (table you refer to in rs2).
Your update statement would like like:

UPDATE TableUser, TableNewUser
SET TableUser.UserID = TableNewUser.NEW_USER
WHERE TableUser.pic = TableNewUser.pic_no;

Much easier. You can put this update statement in VBA code too (if there's a need/reason to do so).


问:
Split RNN Memory Consumption Evenly Between GPUs in TensorFlow
I'm trying to figure out the most strategic way to evenly split the memory load of a seq2seq network between two GPUs.

With convolutional networks, the task is much easier. However, I'm trying to figure out how to maximize the memory usage of 2 Titan X's. The goal is to build the largest network that the combined 24GB of memory will allow.

One idea was to place each RNN layer in a separate GPU.

```<code>GPU1 --> RNN Layer 1 & Backward Pass
GPU2 --> RNN Layer 2,3,4
</code>```

However, the backprop computations require a significant amount of memory. Therefore, another idea is to do the entire forward pass on one GPU and the backward pass on the separate GPU.

```<code>GPU1 --> Forward Pass
GPU2 --> Backward Pass
</code>```

(However, GPU2 still takes most of the memory load)

Is there any way to measure how much of the GPU memory is being used? This would allow us to figure out how to maximize each GPU before it's "filled up".

Once 2 GPUs are used, I would eventually want to use four. However, I think maximizing 2 GPUs is the first step.

答:
Setting "colocate_gradients_with_ops" as TRUE maybe work. It allows GPU memory to allocated evenly.</p>

```<code>optimizer = tf.train.AdamOptimizer(learning_rate)
gvs = optimizer.compute_gradients(loss, colocate_gradients_with_ops=True)
train_op = optimizer.apply_gradients(gvs, global_step=self.global_step)
</code>```

Body:
I'm trying to figure out the most strategic way to evenly split the memory load of a seq2seq network between two GPUs.

With convolutional networks, the task is much easier. However, I'm trying to figure out how to maximize the memory usage of 2 Titan X's. The goal is to build the largest network that the combined 24GB of memory will allow.

One idea was to place each RNN layer in a separate GPU.

GPU1 --> RNN Layer 1 & Backward Pass
GPU2 --> RNN Layer 2,3,4

However, the backprop computations require a significant amount of memory. Therefore, another idea is to do the entire forward pass on one GPU and the backward pass on the separate GPU.

GPU1 --> Forward Pass
GPU2 --> Backward Pass

(However, GPU2 still takes most of the memory load)

Is there any way to measure how much of the GPU memory is being used? This would allow us to figure out how to maximize each GPU before it's "filled up".

Once 2 GPUs are used, I would eventually want to use four. However, I think maximizing 2 GPUs is the first step.

Body:
Setting "colocate_gradients_with_ops" as TRUE maybe work. It allows GPU memory to allocated evenly.

optimizer = tf.train.AdamOptimizer(learning_rate)
gvs = optimizer.compute_gradients(loss, colocate_gradients_with_ops=True)
train_op = optimizer.apply_gradients(gvs, global_step=self.global_step)


问:
magento import product tags via spreadsheet
Is there a way of importing product tags via a spreadsheet?

if not through a module, can this be done through a script?

答:
Tags to be imported format should be like this

And place the about spreadsheet in root/tagimport/tagsheet.csv

and paste the following code in root/tagimport/importtag.php

```<code><?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();

$fileName = 'importtag.csv';

getAttributeCsv($fileName);

function getAttributeCsv($fileName){
    $file = fopen($fileName,"r");
    $RemoveLine = 0;
    while(!feof($file)){
        $data = fgetcsv($file);
        if($RemoveLine != 0){
            $labelText[] = $data[1];
        }$RemoveLine++;
    }createAttribute($labelText);
    fclose($file);
}

function createAttribute($labelText)
{
    foreach($labelText as $tag){
        if($tag){
            $quote = Mage::getModel('tag/tag');
            $quote->loadByName($tag);
            if(!$quote->getId()){
                $quote->setName($tag);
                $quote->setStatus(1);
                $quote->setFirstStoreId(0);
                $quote->setPopularity(0);
                $quote->save();

                ##### Save product tags in "tag_properties"
                $connectionresource = Mage::getSingleton('core/resource');
                $connectionWrite = $connectionresource->getConnection('core_write');
                $table = 'tag_properties';
                $query = "insert into ".$table." "."(tag_id,store_id,base_popularity) values "."(:tag_id, :store_id, :base_popularity)";

                $binds = array(
                    'tag_id'    => $quote->getTagId(),
                    'store_id'   => '1',
                    'base_popularity' => '0',
                    );
                $connectionWrite->query($query, $binds);
                echo 'Tags Imported Successfully';
            }
        }
    }
}
</code>```

run the above php file using

```<code>www.yourdomain.com/tagimport/importtag.php
</code>```

Body:
Tags to be imported format should be like this

And place the about spreadsheet in root/tagimport/tagsheet.csv

and paste the following code in root/tagimport/importtag.php

<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();

$fileName = 'importtag.csv';

getAttributeCsv($fileName);

function getAttributeCsv($fileName){
    $file = fopen($fileName,"r");
    $RemoveLine = 0;
    while(!feof($file)){
        $data = fgetcsv($file);
        if($RemoveLine != 0){
            $labelText[] = $data[1];
        }$RemoveLine++;
    }createAttribute($labelText);
    fclose($file);
}

function createAttribute($labelText)
{
    foreach($labelText as $tag){
        if($tag){
            $quote = Mage::getModel('tag/tag');
            $quote->loadByName($tag);
            if(!$quote->getId()){
                $quote->setName($tag);
                $quote->setStatus(1);
                $quote->setFirstStoreId(0);
                $quote->setPopularity(0);
                $quote->save();

                ##### Save product tags in "tag_properties"
                $connectionresource = Mage::getSingleton('core/resource');
                $connectionWrite = $connectionresource->getConnection('core_write');
                $table = 'tag_properties';
                $query = "insert into ".$table." "."(tag_id,store_id,base_popularity) values "."(:tag_id, :store_id, :base_popularity)";

                $binds = array(
                    'tag_id'    => $quote->getTagId(),
                    'store_id'   => '1',
                    'base_popularity' => '0',
                    );
                $connectionWrite->query($query, $binds);
                echo 'Tags Imported Successfully';
            }
        }
    }
}

run the above php file using

www.yourdomain.com/tagimport/importtag.php


问:
implement financial microservice using node.js | python | R
I'm developing a tourist web app with node.js and microservics.

I need to develop a pricing service which will do all the calculation for the guest (price for night, taxes, VAT, discounts etc).

Moreover, I need those calculation will be easy to dynamically change and control.

From my past experience, doing those calcs in common web programming languages and/or storing math formulas in the db end with a mess.

Are there any alternative solutions for this? From what I read so far language like python, R or Java can fit to the job. However, is there any specific library within those which aimed for pricing?

答:
On can do calulations in (datamodel / class) in javascript

1 : you can create a javascript class

```<code>   function sales(){
    let self = this
    this.address = '';
    this.personname = '';
    this.totalVat = 0
    this.items = [];
    this.calculateTax = function(){
       let tax = ...compute items array and set
       self.totalVat = tax
     }
   }
</code>```

Note :

you can use this data model if you are going to use it only on ui

else if

you want to use it on server then you can use same datamodel on server

esle if

you want to use on both server and ui then

(you can maintain only 1 copy of this model shared by server and ui , here you can use require.js bundling to take help of sharing one datamodel , also there are nice articles that show how to share js datamodels)

in Case Of (you want to use on both server and ui then)

You mentioned database , you create mechanism to store formula in database and you can generate sales_datamodel.js on server whenever any changes are done in datamodel in db

Body:
On can do calulations in (datamodel / class) in javascript

1 : you can create a javascript class

   function sales(){
    let self = this
    this.address = '';
    this.personname = '';
    this.totalVat = 0
    this.items = [];
    this.calculateTax = function(){
       let tax = ...compute items array and set
       self.totalVat = tax
     }
   }

Note :

you can use this data model if you are going to use it only on ui

else if

you want to use it on server then you can use same datamodel on server

esle if

you want to use on both server and ui then

(you can maintain only 1 copy of this model shared by server and ui , here you can use require.js bundling to take help of sharing one datamodel , also there are nice articles that show how to share js datamodels)

in Case Of (you want to use on both server and ui then)

You mentioned database , you create mechanism to store formula in database and you can generate sales_datamodel.js on server whenever any changes are done in datamodel in db


问:
Python :My generator is returning the passed list instead of a filtered output
The code filters the list in such a way that it only returns me the first three values of the list. I tried another generator as well to print only the even numbers but i'm getting the same problem i.e. the whole list is being printed.

```<code>def take(count, iterable):

    counter = 0
    for item in iterable:
        if counter==count:
            return
        count+=1
        yield item

def run_take():
    items = [2,6,5,23,1,4,6,7]

    for item in take(3,items):
        print(item)

if __name__ == '__main__':
    run_take()
</code>```

This should print 2,6,5 but rather prints the  full list. Why???

EDIT : Sorry, i made a very silly error. The counter variable was to be incremented.

答:
That's because there's a logical error in your code. In your take function, you want to increment counter instead of count.

```<code>def take(count, iterable):
    counter = 0
    for item in iterable:
        if counter == count:
            return
        counter += 1
        yield item
</code>```

Body:
The code filters the list in such a way that it only returns me the first three values of the list. I tried another generator as well to print only the even numbers but i'm getting the same problem i.e. the whole list is being printed.

def take(count, iterable):

    counter = 0
    for item in iterable:
        if counter==count:
            return
        count+=1
        yield item

def run_take():
    items = [2,6,5,23,1,4,6,7]

    for item in take(3,items):
        print(item)

if __name__ == '__main__':
    run_take()

This should print 2,6,5 but rather prints the  full list. Why???

EDIT : Sorry, i made a very silly error. The counter variable was to be incremented.

Body:
That's because there's a logical error in your code. In your take function, you want to increment counter instead of count.

def take(count, iterable):
    counter = 0
    for item in iterable:
        if counter == count:
            return
        counter += 1
        yield item


问:
C: why does pointer address set to null in function, have a non-null address in main?
I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.

I have noticed, if I set top to NULL from within main, then it sticks.

My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?

```<code>//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t;

        CreateTree(&t);
        printf("%p\n", t.top) **here returns a memory location

        t.top = NULL **if I add this, then if below works.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
         }
         ...
</code>```

答:
I would like to add a simple test case to demonstrate what others say.

```<code>#include <stdio.h>

void foo(int *p) {
  printf("pointer: %ld\n", (long)&p);
  printf("address: %ld\n", (long)p);
}

int main() {
  int i = 0;
  int* p = &i;
  printf("pointer: %ld\n", (long)&p);
  printf("address: %ld\n", (long)p);
  foo(p);
  return 0;
}
</code>```

Results:

```<code>pointer: 140736715097888
address: 140736715097884
pointer: 140736715097848
address: 140736715097884
</code>```

Above code prints the address of a pointer (where it is allocated) and contents of that pointer (the address where it points to) as you can see the content is the same but the addresses are different. That's why if you change p inside f that will have no effect on the outsider p. The pointer has been copied into f's stack.

Body:
I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.

I have noticed, if I set top to NULL from within main, then it sticks.

My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?

//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t;

        CreateTree(&t);
        printf("%p\n", t.top) **here returns a memory location

        t.top = NULL **if I add this, then if below works.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
         }
         ...

Body:
I would like to add a simple test case to demonstrate what others say.

#include <stdio.h>

void foo(int *p) {
  printf("pointer: %ld\n", (long)&p);
  printf("address: %ld\n", (long)p);
}

int main() {
  int i = 0;
  int* p = &i;
  printf("pointer: %ld\n", (long)&p);
  printf("address: %ld\n", (long)p);
  foo(p);
  return 0;
}

Results:

pointer: 140736715097888
address: 140736715097884
pointer: 140736715097848
address: 140736715097884

Above code prints the address of a pointer (where it is allocated) and contents of that pointer (the address where it points to) as you can see the content is the same but the addresses are different. That's why if you change p inside f that will have no effect on the outsider p. The pointer has been copied into f's stack.


问:
jQuery - some beginner questions
I'm a very beginner to jQuery, and I'm having some basic questions:

Is it advisable to use jQuery whenever it is possible to replace something by using it? For example, is it prudent to bind all events to elements using it, instead of through HTML?

Is it better to host the jQuery .js file and all other relevant files (like JQuery UI) myself, or is it perhaps a better choice to use Google's link (they seem to host it for others too)?

When it comes to executing a script when the page is done loading, what way is preferred?

$(document).ready(function() {})

$(function() {})

$().ready(function() {})

They seem to all do the same thing, but what is the preferred way of scripting?

答:
For the 3d point, none of them. it is generally recommended, for performance reasons, to place your scripts just before the closing  tag. Thus you will not need to wait for the ready event: at this stage, the page is already loaded.

Check Jquery Cookbox (O'Reilly), Chapter 1.2: Executing jQuery/JavaScript Coded Ater DOM Has Loaded but Before Complete Page Load (that book is a must read all in all)

To have a quick idea about this technique, check Move jQuery to the end of body tag? (there are many other posts on SO about this subject)

Title: jQuery - some beginner questions

Body:
For the 3d point, none of them. it is generally recommended, for performance reasons, to place your scripts just before the closing </body> tag. Thus you will not need to wait for the ready event: at this stage, the page is already loaded.

Check Jquery Cookbox (O'Reilly), Chapter 1.2: Executing jQuery/JavaScript Coded Ater DOM Has Loaded but Before Complete Page Load (that book is a must read all in all)

To have a quick idea about this technique, check Move jQuery to the end of body tag? (there are many other posts on SO about this subject)


问:
Getting documents having minimum value for a given field
My document structure is as below:

```<code>{'_id': 1, '_type': '2017-01-01',...}  --- (1)
{'_id': 1, '_type': '2017-01-02',...}  --- (2)
{'_id': 2, '_type': '2017-01-01',...}  --- (3)
{'_id': 2, '_type': '2017-01-02',...}  --- (4)
</code>```

Each id can belong to different types (which are dates here). The aim is to get documents matching given id list having minimum value of _type.

So for an input of id=[1,2], documents 1 & 3 should be returned as they have minimum value of _type (2017-01-01).

This can easily be done on per id basis (by querying for min available type for a given id), but that'd be too expensive as the given id list is in range of thousands.

答:
The following query would do what i need:

```<code>{
 "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "OpID": [id_list]
          }
        }
      ]
    }
  },
  "aggs": {
    "distinct_id": {
      "terms": {
        "field": "OpID",
        "size": 100
      },
      "aggs": {
        "least_type": {
          "top_hits": {
            "sort": [{
              "as_of": {
                "order": "asc"
              }
            }
              ],
              "_source": {
                "includes": ["as_of", "OpID"]
              },
              "size": 1
          }
        }
      }
    }
  },
  "size": 0
}
</code>```

Explanation: The bool filter filters out the documents with the given ID list. The aggregation part gives top 1 document found after arranging documents in order of the given field (as_of in this case). The meaning of _source remains the same here.

The above solution worked for me as i had a field as_of which is of date type and had the copy of the value stored in _type. The above aggregation isn't possible on the field _type

Body:
My document structure is as below:

{'_id': 1, '_type': '2017-01-01',...}  --- (1)
{'_id': 1, '_type': '2017-01-02',...}  --- (2)
{'_id': 2, '_type': '2017-01-01',...}  --- (3)
{'_id': 2, '_type': '2017-01-02',...}  --- (4)

Each id can belong to different types (which are dates here). The aim is to get documents matching given id list having minimum value of _type.

So for an input of id=[1,2], documents 1 & 3 should be returned as they have minimum value of _type (2017-01-01).

This can easily be done on per id basis (by querying for min available type for a given id), but that'd be too expensive as the given id list is in range of thousands.

Body:
The following query would do what i need:

{
 "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "OpID": [id_list]
          }
        }
      ]
    }
  },
  "aggs": {
    "distinct_id": {
      "terms": {
        "field": "OpID",
        "size": 100
      },
      "aggs": {
        "least_type": {
          "top_hits": {
            "sort": [{
              "as_of": {
                "order": "asc"
              }
            }
              ],
              "_source": {
                "includes": ["as_of", "OpID"]
              },
              "size": 1
          }
        }
      }
    }
  },
  "size": 0
}

Explanation: The bool filter filters out the documents with the given ID list. The aggregation part gives top 1 document found after arranging documents in order of the given field (as_of in this case). The meaning of _source remains the same here.

The above solution worked for me as i had a field as_of which is of date type and had the copy of the value stored in _type. The above aggregation isn't possible on the field _type


问:
Get row which matched in each group
I am trying to make a sql query. I got some results from 2 tables below. Below results are good for me. Now I want those values which is present in each group. for example, A and B is present in each group(in each ID). so i want only A and B in result. and also i want make my query dynamic. Could anyone help?</p>

```<code>| ID | Value |
|----|-------|
|  1 |     A |
|  1 |     B |
|  1 |     C |
|  1 |     D |
|  2 |     A |
|  2 |     B |
|  2 |     C |
|  3 |     A |
|  3 |     B |
</code>```

答:
The solution is simple - you can do this in two ways at least. Group by letters (Value), aggregate IDs with SUM or COUNT (distinct values in ID). Having that, choose those letters that have the value for SUM(ID) or COUNT(ID).

```<code>select Value from MyTable group by Value
having SUM(ID) = (SELECT SUM(DISTINCT ID) from MyTable)

select Value from MyTable group by Value
having COUNT(ID) = (SELECT COUNT(DISTINCT ID) from MyTable)
</code>```

Title: Get row which matched in each group

Body:
I am trying to make a sql query. I got some results from 2 tables below. Below results are good for me. Now I want those values which is present in each group. for example, A and B is present in each group(in each ID). so i want only A and B in result. and also i want make my query dynamic. Could anyone help?

| ID | Value |
|----|-------|
|  1 |     A |
|  1 |     B |
|  1 |     C |
|  1 |     D |
|  2 |     A |
|  2 |     B |
|  2 |     C |
|  3 |     A |
|  3 |     B |

Body:
The solution is simple - you can do this in two ways at least. Group by letters (Value), aggregate IDs with SUM or COUNT (distinct values in ID). Having that, choose those letters that have the value for SUM(ID) or COUNT(ID).

select Value from MyTable group by Value
having SUM(ID) = (SELECT SUM(DISTINCT ID) from MyTable)

select Value from MyTable group by Value
having COUNT(ID) = (SELECT COUNT(DISTINCT ID) from MyTable)


问:
Access the php value on the same page using jquery and ajax
i am trying to echo the value entered by the user in the input tag using jquery and ajax .
the following is my code

< script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>     <
  script type = "text/JavaScript" >
  function showMessage() {
    var message = document.getElementById("message").value;
    $.ajax({
      url: 'value_pass.php',
      type: 'GET',
      data: {
        var_PHP_data: message
      },
      success: function(data) {
        alert("success");
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        //case error
      }
    });

  } <
  /script>```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
</head>

<body>
  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
  <?php echo "hi".$_GET['var_PHP_data'];?>
</body>

</html></code>```

My php script is:

```<code><?php
echo "hi".$_GET['var_PHP_data'];
?>
</code>```

the code alert the success prompt , but i am not able to access the value using GET , any pointers on what i am doing wrong.

答:
If you are doing this on same page add your php script at the top of the page that handle your ajax request

Like this

```<code><?php if(isset($_GET['var_PHP_data'])){
  echo "hi".$_GET['var_PHP_data'];
  die;
}?>

<!-- rest of your html code start from here -->
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
</body>

</html>
</code>```

Body:
i am trying to echo the value entered by the user in the input tag using jquery and ajax .
the following is my code

< script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>     <
  script type = "text/JavaScript" >
  function showMessage() {
    var message = document.getElementById("message").value;
    $.ajax({
      url: 'value_pass.php',
      type: 'GET',
      data: {
        var_PHP_data: message
      },
      success: function(data) {
        alert("success");
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        //case error
      }
    });

  } <
  /script>

<!DOCTYPE html>

  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
  <?php echo "hi".$_GET['var_PHP_data'];?>

My php script is:

<?php
echo "hi".$_GET['var_PHP_data'];
?>

the code alert the success prompt , but i am not able to access the value using GET , any pointers on what i am doing wrong.

Body:
If you are doing this on same page add your php script at the top of the page that handle your ajax request

Like this

<?php if(isset($_GET['var_PHP_data'])){
  echo "hi".$_GET['var_PHP_data'];
  die;
}?>

<!-- rest of your html code start from here -->
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
</body>

</html>


问:
'NSInvalidArgumentException', reason: 'Receiver has no segue with identifier 'unwind''
when user clicked button

```<code>let uvc: UINavigationController =
            self.storyboard?.instantiateViewController(withIdentifier: "nationSelect") as! UINavigationController

uvc.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(uvc, animated: true, completion: nil)
</code>```

run this code.

identifier:nationSelect storyboard img

cell, closebutton, VC segue unwind  img

and
button vc have this function

```<code>@IBAction func unwindFromPostCodeSelectionView(_ sender: UIStoryboardSegue) {
    print("unwindFromPostCodeSelectionView")
}
</code>```

and nationSelect VC

when collectionview's cell clicked
run this code

```<code>performSegue(withIdentifier: unwind, sender: nil)
</code>```

and prepare function

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    guard let identifier = segue.identifier, identifier == unwind else{
        return
    }
    guard let vc = segue.destination as? CurationRequestViewController else {
        return
    }

    vc.getAddress.setTitle( (continent.text ?? " ") + " " + nation , for: .normal)
}
</code>```

but i got this error

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier 'unwind''

help me plz!!!

答:
Looks like you are trying to implement unwind segue and you missed to specify the identifier for unwind segue.

Here are the steps to properly implement unwind segue:

Step 1: If you are trying to implement unwind segue from Vc2 to Vc1 (Coming back to VC1 from VC2) then in VC1 add the IBAction as

```<code>@IBAction func unwindToViewController1(segue : UIStoryboardSegue) {
     //you will get control back here when you unwind
}
</code>```

Step 2:
Open storyboard, select VC2 and control drag from ViewController to Exit option in storyboard as shown below

This should show a popover and the method you just declared select it.

Step 3: (Step I think you missed)
Select the unwind segue you just added and provide a identifier to it.

Step 4:
Now whenever you wanna return back to VC1 you can simply call

```<code>self.performSegue(withIdentifier: "unwindSegueToViewController1", sender: nil)
</code>```

Hope it helps :) Happy coding

Body:
when user clicked button

let uvc: UINavigationController =
            self.storyboard?.instantiateViewController(withIdentifier: "nationSelect") as! UINavigationController

uvc.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(uvc, animated: true, completion: nil)

run this code.

identifier:nationSelect storyboard img

cell, closebutton, VC segue unwind  img

and
button vc have this function

@IBAction func unwindFromPostCodeSelectionView(_ sender: UIStoryboardSegue) {
    print("unwindFromPostCodeSelectionView")
}

and nationSelect VC

when collectionview's cell clicked
run this code

performSegue(withIdentifier: unwind, sender: nil)

and prepare function

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    guard let identifier = segue.identifier, identifier == unwind else{
        return
    }
    guard let vc = segue.destination as? CurationRequestViewController else {
        return
    }

    vc.getAddress.setTitle( (continent.text ?? " ") + " " + nation , for: .normal)
}

but i got this error

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier 'unwind''

help me plz!!!

Body:
Looks like you are trying to implement unwind segue and you missed to specify the identifier for unwind segue.

Here are the steps to properly implement unwind segue:

Step 1: If you are trying to implement unwind segue from Vc2 to Vc1 (Coming back to VC1 from VC2) then in VC1 add the IBAction as

@IBAction func unwindToViewController1(segue : UIStoryboardSegue) {
     //you will get control back here when you unwind
}

Step 2:
Open storyboard, select VC2 and control drag from ViewController to Exit option in storyboard as shown below

This should show a popover and the method you just declared select it.

Step 3: (Step I think you missed)
Select the unwind segue you just added and provide a identifier to it.

Step 4:
Now whenever you wanna return back to VC1 you can simply call

self.performSegue(withIdentifier: "unwindSegueToViewController1", sender: nil)

Hope it helps :) Happy coding


问:
vsts pack .net standard 2 into nuget
I have been trying to pack this nuget package for an entire day in the VSTS build process.  it is .net standard 2.0 project

This is one of the errors i keep getting

```<code>Unable to cast object of type 'System.String' to type 'NuGet.Frameworks.NuGetFramework'.
</code>```

This the print out from the console when it attempts to pack.

```<code>******************************************************************************
Starting: NuGet pack
******************************************************************************
==============================================================================
Task         : NuGet
Description  : Restore, pack, or push NuGet packages, or run a NuGet command. Supports NuGet.org and authenticated feeds like Package Management and MyGet. Uses NuGet.exe and works with .NET Framework apps. For .NET Core and .NET Standard apps, use the .NET Core task.
Version      : 2.0.15
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613747)
==============================================================================
C:\Windows\system32\chcp.com 65001
Active code page: 65001
Attempting to pack file: d:\a\1\s\MyProject.Core.Framework.Logging\MyProject.Core.Framework.Logging.csproj
d:\a\_tool\NuGet\4.1.0\x64\nuget.exe pack d:\a\1\s\MyProject.Core.Framework.Logging\MyProject.Core.Framework.Logging.csproj -NonInteractive -OutputDirectory d:\a\1\a -Properties Configuration=release -Verbosity Detailed
NuGet Version: 4.1.0.2450
Attempting to build package from 'MyProject.Core.Framework.Logging.csproj'.
MSBuild auto-detection: using msbuild version '15.4.8.50001' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin'. Use option -MSBuildVersion to force nuget to use a specific version of MSBuild.
Packing files from 'd:\a\1\s\MyProject.Core.Framework.Logging\bin\release\netstandard2.0'.
Using 'MyProject.Core.Framework.Logging.1.0.0.nuspec' for metadata.
Add file 'd:\a\1\s\MyProject.Core.Framework.Logging\bin\release\netstandard2.0\MyProject.Core.Framework.Logging.dll' to package as 'lib\netstandard2.0\MyProject.Core.Framework.Logging.dll'
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'NuGet.Frameworks.NuGetFramework'.
   at NuGet.ProjectManagement.NuGetProject.GetMetadata[T](String key)
   at NuGet.ProjectManagement.PackagesConfigNuGetProject..ctor(String folderPath, Dictionary`2 metadata)
   at CallSite.Target(Closure , CallSite , Type , Object , Dictionary`2 )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at NuGet.CommandLine.ProjectFactory.AddDependencies(Dictionary`2 packagesAndDependencies)
   at NuGet.CommandLine.ProjectFactory.ProcessDependencies(PackageBuilder builder)
   at NuGet.CommandLine.ProjectFactory.CreateBuilder(String basePath, NuGetVersion version, String suffix, Boolean buildIfNeeded, PackageBuilder builder)
   at NuGet.Commands.PackCommandRunner.BuildFromProjectFile(String path)
   at NuGet.CommandLine.PackCommand.ExecuteCommand()
   at NuGet.CommandLine.Command.ExecuteCommandAsync()
   at NuGet.CommandLine.Command.Execute()
   at NuGet.CommandLine.Program.MainCore(String workingDirectory, String[] args)
Error: d:\a\_tool\NuGet\4.1.0\x64\nuget.exe failed with return code: 1
An error ocurred while trying to pack the files.
</code>```

here is nuspec file

```<code><?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>MyrProject.Core.Framework.Logging</id>
    <version>1.0.0</version>
    <authors>Christian Green</authors>
    <owners>Christian Green</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <projectUrl>https://MyrProject.visualstudio.com/MyrProject Core Frameworks/_wiki?pagePath=/MyrProject-Core-Frameworks</projectUrl>
    <iconUrl>http://MyrProject.com/application/files/cache/c169905894409716427e11acc3bdc2df.png</iconUrl>
    <description>Package Description</description>
    <dependencies>
      <group targetFramework=".NETStandard2.0">
        <dependency id="log4net" version="2.0.8" exclude="Build,Analyzers" />
        <dependency id="Microsoft.EntityFrameworkCore.SqlServer" version="2.0.0" exclude="Build,Analyzers" />
      </group>
    </dependencies>
  </metadata>
</package>
</code>```

I have tried $version$ in the nuspec file also.

I have selected all the Automatic package versioning options and I always get the some error.

I can provide more details if needed.

答: Need to use dotnet pack command.</p>

Title: vsts pack .net standard 2 into nuget

Body:
I have been trying to pack this nuget package for an entire day in the VSTS build process.  it is .net standard 2.0 project

This is one of the errors i keep getting

Unable to cast object of type 'System.String' to type 'NuGet.Frameworks.NuGetFramework'.

This the print out from the console when it attempts to pack.

******************************************************************************
Starting: NuGet pack
******************************************************************************
==============================================================================
Task         : NuGet
Description  : Restore, pack, or push NuGet packages, or run a NuGet command. Supports NuGet.org and authenticated feeds like Package Management and MyGet. Uses NuGet.exe and works with .NET Framework apps. For .NET Core and .NET Standard apps, use the .NET Core task.
Version      : 2.0.15
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613747)
==============================================================================
C:\Windows\system32\chcp.com 65001
Active code page: 65001
Attempting to pack file: d:\a\1\s\MyProject.Core.Framework.Logging\MyProject.Core.Framework.Logging.csproj
d:\a\_tool\NuGet\4.1.0\x64\nuget.exe pack d:\a\1\s\MyProject.Core.Framework.Logging\MyProject.Core.Framework.Logging.csproj -NonInteractive -OutputDirectory d:\a\1\a -Properties Configuration=release -Verbosity Detailed
NuGet Version: 4.1.0.2450
Attempting to build package from 'MyProject.Core.Framework.Logging.csproj'.
MSBuild auto-detection: using msbuild version '15.4.8.50001' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin'. Use option -MSBuildVersion to force nuget to use a specific version of MSBuild.
Packing files from 'd:\a\1\s\MyProject.Core.Framework.Logging\bin\release\netstandard2.0'.
Using 'MyProject.Core.Framework.Logging.1.0.0.nuspec' for metadata.
Add file 'd:\a\1\s\MyProject.Core.Framework.Logging\bin\release\netstandard2.0\MyProject.Core.Framework.Logging.dll' to package as 'lib\netstandard2.0\MyProject.Core.Framework.Logging.dll'
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'NuGet.Frameworks.NuGetFramework'.
   at NuGet.ProjectManagement.NuGetProject.GetMetadata[T](String key)
   at NuGet.ProjectManagement.PackagesConfigNuGetProject..ctor(String folderPath, Dictionary`2 metadata)
   at CallSite.Target(Closure , CallSite , Type , Object , Dictionary`2 )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at NuGet.CommandLine.ProjectFactory.AddDependencies(Dictionary`2 packagesAndDependencies)
   at NuGet.CommandLine.ProjectFactory.ProcessDependencies(PackageBuilder builder)
   at NuGet.CommandLine.ProjectFactory.CreateBuilder(String basePath, NuGetVersion version, String suffix, Boolean buildIfNeeded, PackageBuilder builder)
   at NuGet.Commands.PackCommandRunner.BuildFromProjectFile(String path)
   at NuGet.CommandLine.PackCommand.ExecuteCommand()
   at NuGet.CommandLine.Command.ExecuteCommandAsync()
   at NuGet.CommandLine.Command.Execute()
   at NuGet.CommandLine.Program.MainCore(String workingDirectory, String[] args)
Error: d:\a\_tool\NuGet\4.1.0\x64\nuget.exe failed with return code: 1
An error ocurred while trying to pack the files.

here is nuspec file

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>MyrProject.Core.Framework.Logging</id>
    <version>1.0.0</version>
    <authors>Christian Green</authors>
    <owners>Christian Green</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <projectUrl>https://MyrProject.visualstudio.com/MyrProject Core Frameworks/_wiki?pagePath=/MyrProject-Core-Frameworks</projectUrl>
    <iconUrl>http://MyrProject.com/application/files/cache/c169905894409716427e11acc3bdc2df.png</iconUrl>
    <description>Package Description</description>
    <dependencies>
      <group targetFramework=".NETStandard2.0">
        <dependency id="log4net" version="2.0.8" exclude="Build,Analyzers" />
        <dependency id="Microsoft.EntityFrameworkCore.SqlServer" version="2.0.0" exclude="Build,Analyzers" />
      </group>
    </dependencies>
  </metadata>
</package>

I have tried $version$ in the nuspec file also.

I have selected all the Automatic package versioning options and I always get the some error.

I can provide more details if needed.

Body: Need to use dotnet pack command.


问:
SkiaSharp keeps installing in Xamarin.Droid project but installation does not get complete. It just keeps installing.?
I have a xamarin.Forms App in VS for Mac in which I am using a Telerik UI control. When i build my .Droid project, it gives me an exception : FileNotFoundException -> SkiaSharp 1.59.0 is missing perhaps it is not installed for mono for android.

I am trying to install SkiaSharp from Nuget but it just keeps installing but never gets completed. I waited for 10 minutes but did not happen and it just kept installing it.
Any solutions please?
Thanks

答:
I have try to install the SkiaSharp from nuget package in Mac and there is no problem. When you install other nuget package is the same problem? If it did, maybe your VS network configuration has some problem, so it cannot download this package. You could restart your VS and Mac and try again.

As an alternative choice, you could directly download the nuget package from this link, then you could local feed this nuget package to your project reference.


问:
Is it possible to catch the response of search feature available in url
I am trying to write automated screenshotter using puppeteer in node.js which will navigate to particular url.url have one faeture for search box which will give the information for desired query.If we get desired output screenshot is taken and saved to "success" folder but we didnt get any result (like no result found), i want screenshot in "failure" folder. Is It possible to record the response and segregate the screenshots.</p>

答:
Here is your question broken down to bits,

You are trying to,

write automated screenshotter using puppeteer in node.js

which will navigate to particular url.

url have one feature for search box.

which will give the information for desired query.

If we get desired output

screenshot is taken and saved to "success" folder

but we didnt get any result (like no result found),

i want screenshot in "failure" folder.

Is It possible to record the response and segregate the screenshots?
The answer is, Yes.

For example, it can be a simple google/yahoo/duckduckgo results scraper . Save screenshot depending on the result count.

You can use .goto to go to the page, .$$ to check the results, .screenshot to take screenshot depending on the results.

Here is an example code to check if there is any result or not,

```<code>let results = !!await page.$("div > div > h3 > a");
// returns if there is any result in google search

let path;
if (results) {
   path = "success/mysuccessimage.png";
} else {
   path = "failed/myfailimage.png";
}

await page.screenshot({ path });
</code>```

Since you did not share any code, no one will be able to help you. But I guess I answered your question. Now, you can implement it in a thousand ways, peace.

Body:
Here is your question broken down to bits,

You are trying to,

write automated screenshotter using puppeteer in node.js

which will navigate to particular url.

url have one feature for search box.

which will give the information for desired query.

If we get desired output

screenshot is taken and saved to "success" folder

but we didnt get any result (like no result found),

i want screenshot in "failure" folder.

Is It possible to record the response and segregate the screenshots?
The answer is, Yes.

For example, it can be a simple google/yahoo/duckduckgo results scraper . Save screenshot depending on the result count.

You can use .goto to go to the page, .$$ to check the results, .screenshot to take screenshot depending on the results.

Here is an example code to check if there is any result or not,

let results = !!await page.$("div > div > h3 > a");
// returns if there is any result in google search

let path;
if (results) {
   path = "success/mysuccessimage.png";
} else {
   path = "failed/myfailimage.png";
}

await page.screenshot({ path });

Since you did not share any code, no one will be able to help you. But I guess I answered your question. Now, you can implement it in a thousand ways, peace.

ContentLicense: CC BY-SA 4.0


问:
Deploy .json file with UserControl WinForms
I have built a custom User Control in Visual Studio (Win Forms).

This User Control requires a .json file to be deployed along with it.

Short Version: How is this possible?

Long Version:
When I am testing the User Control from with the Control designer itself, it works no problem.
This would be because I have set the following:

Build Action to Content and;
Copy To Output Directory - Copy if Newer

So when I'm debugging it, everything is there, as I expect it to be.

The problem occurs when I create a separate Win Forms application, and add this newly designed control to the Palette by:

Right click Toolbox->Choose Items->Browse->Browse to the Project Directory of the Control->Select the DLL->OK

It show up on my Palette, but the problem is of course when I drop the User Control onto the form itself. It has no means of getting "MyFile.json" from User Control Application/Dll to the Current Project.

How do I make this work?

Chud

答:
One easy way is to build your json file as a EmbeddedResource instead of Content. That way it will be embedded into the UserControl's binary (the dll file itself). You can then use ResourceManager class to read it in your code.

If you're going to change the content of json file at runtime, you can instead create an application setting of string type that stores the actual json content. This setting can then be read/written easily using ProjectName.Properties.Settings.Default.YourSettingName.

Also note that if you have set your json file's Build Action to Content and Copy to Output Directory to Always Copy, and you add a reference to this project from another project that also exists in that solution, the content file (json file) should get copied to the bin folder correctly. But if your UserControl project does not exist in the current solution, or you're referencing your control through Browse button, you'll not get your content files. This may not seem obvious, but once you think about it, you'll understand that VS cannot figure out what dependencies does a DLL file has if you simply add a file reference.

In the latter case, a setting is the cheapest solution (described above) that you can use.


问:
use foreach loop dynamically in php
i want use foreach loop dynamically in php, i have task to print AAA to 999 and i'm using this code and it's work perfect,

Reference :: http://www.onlinecode.org/generate-string-aaaa-9999-using-php-code/

```<code>$addalphabeth = array_merge(range('A', 'Z'), range(0,9));
$setcharacter = [];
foreach ($addalphabeth as $setcharacter[0]) {
  foreach ($addalphabeth as $setcharacter[1]) {
    foreach ($addalphabeth as $setcharacter[2]) {
        //$setcatalog[] = vsprintf('%s%s%s', $setcharacter);
        echo "<b>".vsprintf('%s%s%s', $setcharacter)."</b>";
        echo "<br>";
    }
  }
}
</code>```

now my issue is have to print that AAAAA to 99999 (need loop 5 time) or AAAAAAAA to 99999999 (need loop 8 time) ,
so for this i use loop n time. I have no idea how to do it, any help or suggestion will be appreciated.

答:
Evening, here is my solution, using recursion.
To setup a recursion, you have to think of two things.  What is your stop condition, and what do to with non-stopping conditions.

Stopping condition:  when you ask for only 1 char width, simply loop through each member of $addalphabeth.  And since that width == 1 scenario will happen when the final width you want is >1, add the prefix to it.

Non-stopping condition: lets start with width 2.  You want the every first char to be followed by all possible second chars.  So call the function with width = 1 and prefix = the first char.

for 3, you want the first char followed by every char in the second position, followed by every char in the third position.

and so on...

So the general case is: from left to right, with n chars width, loop on every char, and print every possible combination of n-1 chars after it.

So here is the code:

```<code>function printAto9($width,$prefix = '')
{
    $chars = array_merge(range('A', 'Z'), range(0,9));
    if ($width == 1)
    {
        foreach ($chars as $char)
        {
            echo "$prefix$char\n";
        }
    }
    else
    {
        $width--;
        foreach ($chars as $char)
        {
            echo printAto9($width,$prefix . $char);
        }
    }
}

printAto9(5);
</code>```

I put printAto9(5); as a test, you can use whatever.
But careful, the output is monstrous pretty quick, and you can kill your php (memory or time limit).

Title: use foreach loop dynamically in php

Body:
i want use foreach loop dynamically in php, i have task to print AAA to 999 and i'm using this code and it's work perfect,

Reference :: http://www.onlinecode.org/generate-string-aaaa-9999-using-php-code/

$addalphabeth = array_merge(range('A', 'Z'), range(0,9));
$setcharacter = [];
foreach ($addalphabeth as $setcharacter[0]) {
  foreach ($addalphabeth as $setcharacter[1]) {
    foreach ($addalphabeth as $setcharacter[2]) {
        //$setcatalog[] = vsprintf('%s%s%s', $setcharacter);
        echo "".vsprintf('%s%s%s', $setcharacter)."";
        echo "
";
    }
  }
}

now my issue is have to print that AAAAA to 99999 (need loop 5 time) or AAAAAAAA to 99999999 (need loop 8 time) ,
so for this i use loop n time. I have no idea how to do it, any help or suggestion will be appreciated.

Body:
Evening, here is my solution, using recursion.
To setup a recursion, you have to think of two things.  What is your stop condition, and what do to with non-stopping conditions.

Stopping condition:  when you ask for only 1 char width, simply loop through each member of $addalphabeth.  And since that width == 1 scenario will happen when the final width you want is >1, add the prefix to it.

Non-stopping condition: lets start with width 2.  You want the every first char to be followed by all possible second chars.  So call the function with width = 1 and prefix = the first char.

for 3, you want the first char followed by every char in the second position, followed by every char in the third position.

and so on...

So the general case is: from left to right, with n chars width, loop on every char, and print every possible combination of n-1 chars after it.

So here is the code:

function printAto9($width,$prefix = '')
{
    $chars = array_merge(range('A', 'Z'), range(0,9));
    if ($width == 1)
    {
        foreach ($chars as $char)
        {
            echo "$prefix$char\n";
        }
    }
    else
    {
        $width--;
        foreach ($chars as $char)
        {
            echo printAto9($width,$prefix . $char);
        }
    }
}

printAto9(5);

I put printAto9(5); as a test, you can use whatever.
But careful, the output is monstrous pretty quick, and you can kill your php (memory or time limit).


问:
Padding on block element

I cant don this .The problem is in second li I could not give left padding on li
I cant don this .The problem is in second li I could not give left padding on li
I cant don this .The problem is in second li I could not give left padding on li
I cant don this .The problem is in second li I could not give left padding on li

```<code><div class="service-box">
   <div class="header-with-text">
      <div class="img-holder">
      </div>
      <div class="h-text">
         <h3>Unlimited 24/7 Roadside Assistance*</h3>
      </div>
   </div>
   <div class="s-list">
      <ul>
         <li> <i class="fa fa-check-circle" aria-hidden="true"></i>
            Unlimited ernergenry towing.
         </li>
         <li><i class="fa fa-check-circle" aria-hidden="true"></i>
            Tire change, fuel delivery,
            mechaniial adjustment,Jump start,Lockout service & more!
         </li>
         <li> <i class="fa fa-check-circle" aria-hidden="true"></i>
            Emergency travel & living
            expenses
         </li>
      </ul>
   </div>
</div>
</code>```

CSS---------

```<code>.service-box{
    background: #f0f0ee;
    border-radius: 4px;
    max-width: 310px;
    padding: 19px 19px 16px 16px;
    float: left;
 }
 .header-with-text{
    float: left;
 }
 .header-with-text .img-holder{
    background: url(../images/road-side.png) no-repeat 0 0;
    float: left;
    width: 45px;
    height: 32px;
    display: block;
    margin-right: 10px;
 }
 .h-text{
    float: right;
    max-width: 212px;
 }
 .h-text h3{
    font-size: 20px;
    color: #272b68;
 }
 .s-list ul{
    padding: 0px;
 }
 .s-list ul li{
    list-style: none;
 }
</code>```

答:
```<code> .s-list ul li{
    list-style: none;
    padding-left: 10px;
 }
</code>```

https://jsfiddle.net/ctmeaqg2/1/

Padding on li works fine. Check!

Title: Padding on block element

Body:
I cant don this .The problem is in second li I could not give left padding on li
I cant don this .The problem is in second li I could not give left padding on li
I cant don this .The problem is in second li I could not give left padding on li
I cant don this .The problem is in second li I could not give left padding on li

Unlimited 24/7 Roadside Assistance*

            Unlimited ernergenry towing.

            Tire change, fuel delivery,
            mechaniial adjustment,Jump start,Lockout service & more!

            Emergency travel & living
            expenses

CSS---------

.service-box{
    background: #f0f0ee;
    border-radius: 4px;
    max-width: 310px;
    padding: 19px 19px 16px 16px;
    float: left;
 }
 .header-with-text{
    float: left;
 }
 .header-with-text .img-holder{
    background: url(../images/road-side.png) no-repeat 0 0;
    float: left;
    width: 45px;
    height: 32px;
    display: block;
    margin-right: 10px;
 }
 .h-text{
    float: right;
    max-width: 212px;
 }
 .h-text h3{
    font-size: 20px;
    color: #272b68;
 }
 .s-list ul{
    padding: 0px;
 }
 .s-list ul li{
    list-style: none;
 }

Body:
 .s-list ul li{
    list-style: none;
    padding-left: 10px;
 }

https://jsfiddle.net/ctmeaqg2/1/

Padding on li works fine. Check!


问:
Error just on host, not on my computer; String was not recognized as a valid DateTime
I am in bad situation. I have a program that it works very well in my computer but when I upload it on the host it gives me this error "String was not recognized as a valid DateTime." my program is on ASP.net C# visual studio 2015

Edit:
  both date's format on my computer and on the host are the same. like
  this:"mm/dd/yyyy"

would you please help me?
here is my code:
HTML:

<%@ Page Title="" Language="C#" MasterPageFile="~/mainMembers/frameMembers.Master" AutoEventWireup="true" CodeBehind="GMList.aspx.cs" Inherits="Federation.mainMembers.GMList" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainFrame" runat="server">
    <form id="gml" runat="server" method="post">
        <asp:Label ID="titr" runat="server" CssClass="shekaste" Text="title"></asp:Label>

        <asp:GridView ID="fedList" runat="server" AutoGenerateColumns="false" CssClass="parastoo" OnRowDataBound="MatchList_RowDataBound" >
            <Columns>

                <asp:BoundField HeaderText="a" DataField="birthday" />

                <asp:BoundField HeaderText="b" DataField="start_sport" />

                <asp:BoundField HeaderText="c" DataField="ToDate" />

            </Columns>
        </asp:GridView>

        </form>
</asp:Content>```
</div>
</div>
</p>

<ol start="2">
<li><p>C# code:</p>

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Globalization;
using System.Drawing;
using System.Text.RegularExpressions;
using System.IO;

namespace Federation.mainMembers
{

    public partial class GMList : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSG"].ConnectionString);
        //SqlConnection con = new SqlConnection(conStr);
        DataSet ds = new DataSet();
        //private string strSQL;
        private SqlCommand com;
        SqlDataAdapter sda;
        // DateTime dtime;
        DataTable dt = new DataTable();
        //DataTable dt1 = new DataTable();
        PersianCalendar pc = new PersianCalendar();
        //string memberID = "1111111112";
        string matchID = "";
        Boolean[] age2 = new Boolean[6];
        Boolean[] weight = new Boolean[9];
        //Int16 morshedi = 0;
        byte[] img1 = new byte[0];

        Int16 level;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["FID"] != null)
            {
                matchID = this.Session["FID"].ToString();
                //memberID = this.Session["VID"].ToString();
                //morshedi = Convert.ToInt16(this.Session["VMID"].ToString());

                //string s;

                if (!Page.IsPostBack)
                {

                    //********************************************************
                    dt.Rows.Clear();
                    con.Close();
                    sda = new SqlDataAdapter("select birthday,start_sport,ToDate   from general_members ", con);
                    con.Close();

                    con.Open();
                    dt.Rows.Clear();
                    sda.Fill(dt);

                    con.Close();
                    //string dds=dt.Rows[0]["ToDate"].ToString();
                    DataView dv1 = new DataView(dt);

                    fedList.DataSource = dv1;

                    fedList.DataBind();

                }
            }
            else
            {
                Response.Redirect("~/a.aspx");
            }

        }

        protected void MatchList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // Find the value in the c04_oprogrs column. You'll have to use
                // some trial and error here to find the right control. The line
                // below may provide the desired value but I'm not entirely sure.

                TableCell statusCell1 = e.Row.Cells[0];
                TableCell statusCell2 = e.Row.Cells[1];
                TableCell statusCell3 = e.Row.Cells[2];

                string dstr = "";
                int year, month, day;
                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell1.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell1.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell1.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell1.Text = dstr;

                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell2.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell2.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell2.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell2.Text = dstr;

                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell3.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell3.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell3.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell3.Text = dstr;

            }
        }
    }
}
```

答:
The problem is very likely different regional settings on your host.

To address this ensure you pass the expected CultureInfo to your conversion method:

https://msdn.microsoft.com/en-us/library/9xk1h71t(v=vs.110).aspx

See below, applied to your code. You will need to substitute the relevant culture string in the CultureInfo constructor:

```<code>System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");

year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell1.Text,culture)));
month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell1.Text,culture)));
day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell1.Text,culture)));
</code>```

Body:
I am in bad situation. I have a program that it works very well in my computer but when I upload it on the host it gives me this error "String was not recognized as a valid DateTime." my program is on ASP.net C# visual studio 2015

Edit:
  both date's format on my computer and on the host are the same. like
  this:"mm/dd/yyyy"

would you please help me?
here is my code:
HTML:

<%@ Page Title="" Language="C#" MasterPageFile="~/mainMembers/frameMembers.Master" AutoEventWireup="true" CodeBehind="GMList.aspx.cs" Inherits="Federation.mainMembers.GMList" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainFrame" runat="server">
    <form id="gml" runat="server" method="post">
        <asp:Label ID="titr" runat="server" CssClass="shekaste" Text="title"></asp:Label>

        <asp:GridView ID="fedList" runat="server" AutoGenerateColumns="false" CssClass="parastoo" OnRowDataBound="MatchList_RowDataBound" >
            <Columns>

                <asp:BoundField HeaderText="a" DataField="birthday" />

                <asp:BoundField HeaderText="b" DataField="start_sport" />

                <asp:BoundField HeaderText="c" DataField="ToDate" />

            </Columns>
        </asp:GridView>

        </form>
</asp:Content>

C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Globalization;
using System.Drawing;
using System.Text.RegularExpressions;
using System.IO;

namespace Federation.mainMembers
{

    public partial class GMList : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSG"].ConnectionString);
        //SqlConnection con = new SqlConnection(conStr);
        DataSet ds = new DataSet();
        //private string strSQL;
        private SqlCommand com;
        SqlDataAdapter sda;
        // DateTime dtime;
        DataTable dt = new DataTable();
        //DataTable dt1 = new DataTable();
        PersianCalendar pc = new PersianCalendar();
        //string memberID = "1111111112";
        string matchID = "";
        Boolean[] age2 = new Boolean[6];
        Boolean[] weight = new Boolean[9];
        //Int16 morshedi = 0;
        byte[] img1 = new byte[0];

        Int16 level;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["FID"] != null)
            {
                matchID = this.Session["FID"].ToString();
                //memberID = this.Session["VID"].ToString();
                //morshedi = Convert.ToInt16(this.Session["VMID"].ToString());

                //string s;

                if (!Page.IsPostBack)
                {

                    //********************************************************
                    dt.Rows.Clear();
                    con.Close();
                    sda = new SqlDataAdapter("select birthday,start_sport,ToDate   from general_members ", con);
                    con.Close();

                    con.Open();
                    dt.Rows.Clear();
                    sda.Fill(dt);

                    con.Close();
                    //string dds=dt.Rows[0]["ToDate"].ToString();
                    DataView dv1 = new DataView(dt);

                    fedList.DataSource = dv1;

                    fedList.DataBind();

                }
            }
            else
            {
                Response.Redirect("~/a.aspx");
            }

        }

        protected void MatchList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // Find the value in the c04_oprogrs column. You'll have to use
                // some trial and error here to find the right control. The line
                // below may provide the desired value but I'm not entirely sure.

                TableCell statusCell1 = e.Row.Cells[0];
                TableCell statusCell2 = e.Row.Cells[1];
                TableCell statusCell3 = e.Row.Cells[2];

                string dstr = "";
                int year, month, day;
                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell1.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell1.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell1.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell1.Text = dstr;

                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell2.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell2.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell2.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell2.Text = dstr;

                year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell3.Text)));
                month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell3.Text)));
                day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell3.Text)));
                dstr = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
                statusCell3.Text = dstr;

            }
        }
    }
}

Body:
The problem is very likely different regional settings on your host.

To address this ensure you pass the expected CultureInfo to your conversion method:

https://msdn.microsoft.com/en-us/library/9xk1h71t(v=vs.110).aspx

See below, applied to your code. You will need to substitute the relevant culture string in the CultureInfo constructor:

System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");

year = Convert.ToInt32(pc.GetYear(Convert.ToDateTime(statusCell1.Text,culture)));
month = Convert.ToInt32(pc.GetMonth(Convert.ToDateTime(statusCell1.Text,culture)));
day = Convert.ToInt32(pc.GetDayOfMonth(Convert.ToDateTime(statusCell1.Text,culture)));


问:
Dynamically change header string in angular 2
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a

```<code><h1>{{title}}</h1>
</code>```

and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page

below is an image of what im trying to change

Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..

Not sure how I can go about this and everything ive researched has been to change the title in the  tags

答:
Use the title service in @angular/platform-browser  and add router component with data property.

```<code>const appRoutes: Routes = [
  { path: 'home',component:HomeComponent , data:{title:'Home'}}

  ];
</code>```

Call this function in the root component

```<code>ngOnInit() {
    this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .map(() => this.activatedRoute)
      .map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      })
      .filter((route) => route.outlet === 'primary')
      .mergeMap((route) => route.data)
      .subscribe((event) => this.titleService.setTitle(event['title']));
  }
}
</code>```

Body:
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a

{{title}}

and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page

below is an image of what im trying to change

Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..

Not sure how I can go about this and everything ive researched has been to change the title in the  tags

Body:
Use the title service in @angular/platform-browser  and add router component with data property.

const appRoutes: Routes = [
  { path: 'home',component:HomeComponent , data:{title:'Home'}}

  ];

Call this function in the root component

ngOnInit() {
    this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .map(() => this.activatedRoute)
      .map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      })
      .filter((route) => route.outlet === 'primary')
      .mergeMap((route) => route.data)
      .subscribe((event) => this.titleService.setTitle(event['title']));
  }
}


问:
How to use WriteProcessMemory in Delphi
I cannot compile this code. Could I have a help? Thanks.

```<code>procedure ChangeOutsideDateTime(h: HWND; dt: TDateTime);
var
  st: TSystemTime;
  pst: Pointer;
  hDTP: Cardinal;
  hProc: THandle;
  dwWrote: DWORD;
begin
  DateTimeToSystemTime(dt, st);
  pst:= VirtualAllocEx(h, nil, SizeOf(st), MEM_COMMIT, 0);
  if pst <> nil then begin
    if GetWindowThreadProcessId(h, hDTP) > 0 then begin
      hProc:= OpenProcess(PROCESS_VM_OPERATION, false, hDTP);
      if WriteProcessMemory(hProc, pst, @st, SizeOf(st), dwWrote) > 0 then begin
        SendMessage(h, DTM_SETSYSTEMTIME, GDT_VALID, hDTP);
        CloseHandle(hProc);
      end;
    end;
    VirtualFreeEx(h, pst, 0, MEM_RELEASE);
  end;
end;
</code>```

It shows "Types of actual and formal var parameters must be identical" at line where is using "WriteProcessMemory".

答:
Types of actual and formal var parameters must be identical

This is compiler error E2003. If you encounter a compiler error that you don't understand, the first thing to do is read the documentation. It says:

For a variable parameter, the actual argument must be of the exact type of the formal parameter.

The function call which leads to this error is WriteProcessMemory. Let's look at its declaration:

```<code>function WriteProcessMemory(hProcess: THandle; const lpBaseAddress: Pointer;
  lpBuffer: Pointer; nSize: SIZE_T; var lpNumberOfBytesWritten: SIZE_T): BOOL; stdcall;
</code>```

There is only one var parameter here, the final parameter. The variable that you pass must be of type SIZE_T, but you passed a variable of type DWORD. That is the mismatch.

Some other comments:

The call to VirtualAllocEx is bound to fail because you pass a window handle rather than a process handle.

Semantically it makes no sense to test for positive thread ID. Test not equal to zero for success or otherwise.

You don't check the OpenProcess return value. That could readily fail.

You don't open the process with the PROCESS_VM_WRITE access right which is necessary for WriteProcessMemory.

You leak the handle if the call to WriteProcessMemory fails.

The return type of WriteProcessMemory is BOOL.

hDTP is a strange name for a process ID. That name suggests you think it is the handle of the date time picker control. It's not. It's the process ID.

You pass that process ID in the SendMessage call rather than the address of the system time that you just wrote.

Title: How to use WriteProcessMemory in Delphi

Body:
I cannot compile this code. Could I have a help? Thanks.

procedure ChangeOutsideDateTime(h: HWND; dt: TDateTime);
var
  st: TSystemTime;
  pst: Pointer;
  hDTP: Cardinal;
  hProc: THandle;
  dwWrote: DWORD;
begin
  DateTimeToSystemTime(dt, st);
  pst:= VirtualAllocEx(h, nil, SizeOf(st), MEM_COMMIT, 0);
  if pst <> nil then begin
    if GetWindowThreadProcessId(h, hDTP) > 0 then begin
      hProc:= OpenProcess(PROCESS_VM_OPERATION, false, hDTP);
      if WriteProcessMemory(hProc, pst, @st, SizeOf(st), dwWrote) > 0 then begin
        SendMessage(h, DTM_SETSYSTEMTIME, GDT_VALID, hDTP);
        CloseHandle(hProc);
      end;
    end;
    VirtualFreeEx(h, pst, 0, MEM_RELEASE);
  end;
end;

It shows "Types of actual and formal var parameters must be identical" at line where is using "WriteProcessMemory".

Body:
Types of actual and formal var parameters must be identical

This is compiler error E2003. If you encounter a compiler error that you don't understand, the first thing to do is read the documentation. It says:

For a variable parameter, the actual argument must be of the exact type of the formal parameter.

The function call which leads to this error is WriteProcessMemory. Let's look at its declaration:

function WriteProcessMemory(hProcess: THandle; const lpBaseAddress: Pointer;
  lpBuffer: Pointer; nSize: SIZE_T; var lpNumberOfBytesWritten: SIZE_T): BOOL; stdcall;

There is only one var parameter here, the final parameter. The variable that you pass must be of type SIZE_T, but you passed a variable of type DWORD. That is the mismatch.

Some other comments:

The call to VirtualAllocEx is bound to fail because you pass a window handle rather than a process handle.

Semantically it makes no sense to test for positive thread ID. Test not equal to zero for success or otherwise.

You don't check the OpenProcess return value. That could readily fail.

You don't open the process with the PROCESS_VM_WRITE access right which is necessary for WriteProcessMemory.

You leak the handle if the call to WriteProcessMemory fails.

The return type of WriteProcessMemory is BOOL.

hDTP is a strange name for a process ID. That name suggests you think it is the handle of the date time picker control. It's not. It's the process ID.

You pass that process ID in the SendMessage call rather than the address of the system time that you just wrote.


问:
PHP 7.0 get_magic_quotes_runtime error
I have code like that:

```<code>    if (function_exists('get_magic_quotes_runtime')) {
        $mqr = @get_magic_quotes_runtime();
        @set_magic_quotes_runtime(0);
    }
</code>```

And when it is executed It returns error message: Uncaught Error: Call to undefined function set_magic_quotes_runtime()

But why function_exists('get_magic_quotes_runtime') returns true?
Is it normal for PHP 7.0?

答:
Change all

set_XXXX functions like set_magic_quotes_runtime

to

ini_set('magic_quotes_runtime', 0);

Title: PHP 7.0 get_magic_quotes_runtime error

Body:
I have code like that:

    if (function_exists('get_magic_quotes_runtime')) {
        $mqr = @get_magic_quotes_runtime();
        @set_magic_quotes_runtime(0);
    }

And when it is executed It returns error message: Uncaught Error: Call to undefined function set_magic_quotes_runtime()

But why function_exists('get_magic_quotes_runtime') returns true?
Is it normal for PHP 7.0?