问:
Filtered HTML list: making li elements initially invisible
This is the HTML:

```<code><input type="text" id="myInput" onkeyup="myFunction()" placeholder="orasul tau..">

<ul id="myUL">
    <li>Bucuresti</li>
    <li>Cluj</li>
    <li>Timisoara</li>
</ul>
</code>```

And this is my scipt:

```<code>var value = $('#myInput').val();
if(value.length == 0) {
    $("#myUL li").style.display = "none";
}

$('#myInput').bind('keyup', function() {
    var searchString = $(this).val();
    $("ul li").each(function(index, value) {
        currentName = $(value).text()
        if( currentName.toUpperCase().indexOf(searchString.toUpperCase()) > -1) {
           $(value).show();
        } else {
            $(value).hide();
        }
    });
});
</code>```

I want to filter the elements of the ul based on the text in the input.

Everything is working perfectly without that initial if statement, but I want all the li elements to initially have diplay:none. Adding that if deactivates the whole filtering. Any possible solution for how I could do that?

Any help would be appreciated.

答:
The problem is that $("#myUL li").style.display = "none" doesn't make sense. $("#myUL li") is jQuery instance object, not HTMLElement. So it doesn't have property style.

Use $("#myUL li").hide() to hide all elements.

However, the better approach is to use CSS to hide LI initially and trigger one search on page load if myInput has value:

var $input = $('#myInput').on('input', function() {
  var searchString = $(this).val();
  $("ul li").each(function(index, value) {
    var currentName = $(value).text()
    var shouldShow = searchString.length && currentName.toUpperCase().indexOf(searchString.toUpperCase()) > -1;

    if (shouldShow) {
      $(value).show();
    } else {
      $(value).hide();
    }
  });
});

var value = $input.val();

if (value.length !== 0) {
 $input.trigger('keyup');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myUL li {
  display: none;
}</code>```

<input type="text" id="myInput" placeholder="orasul tau..">

Bucuresti

Cluj

Timisoara

```

Body:
This is the HTML:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="orasul tau..">

Bucuresti

Cluj

Timisoara

And this is my scipt:

var value = $('#myInput').val();
if(value.length == 0) {
    $("#myUL li").style.display = "none";
}

$('#myInput').bind('keyup', function() {
    var searchString = $(this).val();
    $("ul li").each(function(index, value) {
        currentName = $(value).text()
        if( currentName.toUpperCase().indexOf(searchString.toUpperCase()) > -1) {
           $(value).show();
        } else {
            $(value).hide();
        }
    });
});

I want to filter the elements of the ul based on the text in the input.

Everything is working perfectly without that initial if statement, but I want all the li elements to initially have diplay:none. Adding that if deactivates the whole filtering. Any possible solution for how I could do that?

Any help would be appreciated.

Body:
The problem is that $("#myUL li").style.display = "none" doesn't make sense. $("#myUL li") is jQuery instance object, not HTMLElement. So it doesn't have property style.

Use $("#myUL li").hide() to hide all elements.

However, the better approach is to use CSS to hide LI initially and trigger one search on page load if myInput has value:

var $input = $('#myInput').on('input', function() {
  var searchString = $(this).val();
  $("ul li").each(function(index, value) {
    var currentName = $(value).text()
    var shouldShow = searchString.length && currentName.toUpperCase().indexOf(searchString.toUpperCase()) > -1;

    if (shouldShow) {
      $(value).show();
    } else {
      $(value).hide();
    }
  });
});

var value = $input.val();

if (value.length !== 0) {
 $input.trigger('keyup');
}

#myUL li {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" placeholder="orasul tau..">

<ul id="myUL">
  <li>Bucuresti</li>
  <li>Cluj</li>
  <li>Timisoara</li>
</ul>


来源: stackexchange

问:
Finding max value using reduce
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

```<code>{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])
</code>```

This is what I have so far:

```<code>(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)
</code>```

This produces the outcome:

```<code>{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}
</code>```

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

答:
Here is a pretty fast version that avoids intermediate data structures:</p>

```<code>(let [parse #(Double/parseDouble (clojure.string/replace % "," ""))]
  (reduce (fn [m {:keys [product sales city] :as cand}]
            (let [sales-d (parse sales)]
              (update m product (fn [prev]
                                  (if (or (nil? prev) (< (:sales prev) sales-d))
                                    (assoc cand :sales sales-d)
                                    prev)))))
          {} products))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Finding max value using reduce

Body:
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])

This is what I have so far:

(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)

This produces the outcome:

{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

Body:
Here is a pretty fast version that avoids intermediate data structures:

(let [parse #(Double/parseDouble (clojure.string/replace % "," ""))]
  (reduce (fn [m {:keys [product sales city] :as cand}]
            (let [sales-d (parse sales)]
              (update m product (fn [prev]
                                  (if (or (nil? prev) (< (:sales prev) sales-d))
                                    (assoc cand :sales sales-d)
                                    prev)))))
          {} products))


问:
Getting "-nan(ind)" when trying to generate random variates
I am trying generate random variates by trying to generate two standard normal variates r1, r2, by using polar coordinates along with a mean and sigma value. However when I run my code, I keep getting a "-nan(ind)" as my output.

What am I doing wrong here? The code is as follows:

```<code>static double saveNormal;
static int NumNormals = 0;
static double PI = 3.1415927;

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

static double normal(double r, double mean, double sigma) {
    double returnNormal;
    if (NumNormals == 0) {
        //to get next double value
        double r1 = fRand(0, 20);
        double r2 = fRand(0, 20);
        returnNormal = sqrt(-2 * log(r1)) * cos(2 * PI*r2);
        saveNormal = sqrt(-2 * log(r1)) * sin(2 * PI*r2);
    }
    else {
        NumNormals = 0;
        returnNormal = saveNormal;
    }
    return returnNormal*sigma + mean;
}
</code>```

答:
So, you're using the Box–Muller method to pseudo randomly sample a normal random variate. For this transform to work, r1 and r2 must be uniformly distributed independent variates in [0,1].

Instead, your r1/r2 are [0,20] supported, resulting in a negative sqrt argument when >1, this will give you nans. Replace with

```<code>double r1 = fRand(0, 1);
double r2 = fRand(0, 1);
</code>```

Moreover, you should use C++11 <random> for better pseudorandom number generation; as of now, your fRand has poor quality due to rand()-to-double conversion and possible spurious correlations between adjacent calls. Moreover, your function lacks some basic error checking and badly depends on global variables and is inherently thread unsafe.

FYI, this is what a C++11 version might look like

```<code>#include <random>
#include <iostream>

int main()
{
  auto engine = std::default_random_engine{ std::random_device{}() };
  auto variate = std::normal_distribution<>{ /*mean*/0., /*stddev*/ 1. };

  while(true) // a lot of normal samples ...
    std::cout << variate(engine) << std::endl;
}
</code>```

Body:
I am trying generate random variates by trying to generate two standard normal variates r1, r2, by using polar coordinates along with a mean and sigma value. However when I run my code, I keep getting a "-nan(ind)" as my output.

What am I doing wrong here? The code is as follows:

static double saveNormal;
static int NumNormals = 0;
static double PI = 3.1415927;

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

static double normal(double r, double mean, double sigma) {
    double returnNormal;
    if (NumNormals == 0) {
        //to get next double value
        double r1 = fRand(0, 20);
        double r2 = fRand(0, 20);
        returnNormal = sqrt(-2 * log(r1)) * cos(2 * PI*r2);
        saveNormal = sqrt(-2 * log(r1)) * sin(2 * PI*r2);
    }
    else {
        NumNormals = 0;
        returnNormal = saveNormal;
    }
    return returnNormal*sigma + mean;
}

Body:
So, you're using the Box–Muller method to pseudo randomly sample a normal random variate. For this transform to work, r1 and r2 must be uniformly distributed independent variates in [0,1].

Instead, your r1/r2 are [0,20] supported, resulting in a negative sqrt argument when >1, this will give you nans. Replace with

double r1 = fRand(0, 1);
double r2 = fRand(0, 1);

Moreover, you should use C++11 <random> for better pseudorandom number generation; as of now, your fRand has poor quality due to rand()-to-double conversion and possible spurious correlations between adjacent calls. Moreover, your function lacks some basic error checking and badly depends on global variables and is inherently thread unsafe.

FYI, this is what a C++11 version might look like

#include <random>
#include <iostream>

int main()
{
  auto engine = std::default_random_engine{ std::random_device{}() };
  auto variate = std::normal_distribution<>{ /*mean*/0., /*stddev*/ 1. };

  while(true) // a lot of normal samples ...
    std::cout << variate(engine) << std::endl;
}


问:
Multiple index properties on a type?
Is it possible to have something like this in C#? I am not very sure:

```<code>class Library
{
    public string Books[string title]
    {
        get{return this.GetBookByName(string title);}
    }

    public DateTime PublishingDates[string title]
    {
        get{return this.GetBookByName(string title).PublishingDate;}
    }
}
</code>```

So it could be used as such:

```<code>myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...
</code>```

So my complete member methods that I need to implement in my framework (by calling them) are:

```<code>GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)
</code>```

I want to implement them cleaner in my own type.

答:
The only way you could do this would be to have Books be a property that returns a type that has its own suitable indexer.  Here's one possible approach:

```<code>public class Indexer<TKey, TValue>
{
    private Func<TKey, TValue> func;

    public Indexer(Func<TKey, TValue> func)
    {
        if (func == null)
            throw new ArgumentNullException("func");

        this.func = func;
    }

    public TValue this[TKey key]
    {
        get { return func(key); }
    }
}

class Library
{
    public Indexer<string, Book> Books { get; private set; }
    public Indexer<string, DateTime> PublishingDates { get; private set; }

    public Library()
    {
        Books = new Indexer<string, Book>(GetBookByName);
        PublishingDates = new Indexer<string, DateTime>(GetPublishingDate);
    }

    private Book GetBookByName(string bookName)
    {
        // ...
    }

    private DateTime GetPublishingDate(string bookName)
    {
        return GetBookByName(bookName).PublishingDate;
    }
}
</code>```

But you should seriously consider providing an implementation of IDictionary<,> instead of using this approach, as it will allow other nifty stuff, like enumeration of key-value pairs, etc.

ContentLicense: CC BY-SA 2.5

Title: Multiple index properties on a type?

Body:
Is it possible to have something like this in C#? I am not very sure:

class Library
{
    public string Books[string title]
    {
        get{return this.GetBookByName(string title);}
    }

    public DateTime PublishingDates[string title]
    {
        get{return this.GetBookByName(string title).PublishingDate;}
    }
}

So it could be used as such:

myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...

So my complete member methods that I need to implement in my framework (by calling them) are:

GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)

I want to implement them cleaner in my own type.

Body:
The only way you could do this would be to have Books be a property that returns a type that has its own suitable indexer.  Here's one possible approach:

public class Indexer<TKey, TValue>
{
    private Func<TKey, TValue> func;

    public Indexer(Func<TKey, TValue> func)
    {
        if (func == null)
            throw new ArgumentNullException("func");

        this.func = func;
    }

    public TValue this[TKey key]
    {
        get { return func(key); }
    }
}

class Library
{
    public Indexer<string, Book> Books { get; private set; }
    public Indexer<string, DateTime> PublishingDates { get; private set; }

    public Library()
    {
        Books = new Indexer<string, Book>(GetBookByName);
        PublishingDates = new Indexer<string, DateTime>(GetPublishingDate);
    }

    private Book GetBookByName(string bookName)
    {
        // ...
    }

    private DateTime GetPublishingDate(string bookName)
    {
        return GetBookByName(bookName).PublishingDate;
    }
}

But you should seriously consider providing an implementation of IDictionary<,> instead of using this approach, as it will allow other nifty stuff, like enumeration of key-value pairs, etc.


问:
array combine three or more arrays with php
ok, assuming I have 5 arrays, all just indexed arrays, and I would like to combine them, this is the best way I can figure, is there a better way to handle this?

```<code>function mymap_arrays(){
    $args=func_get_args();
    $key=array_shift($args);
    return array_combine($key,$args);
}
$keys=array('u1','u2','u3');
$names=array('Bob','Fred','Joe');
$emails=array('bob@mail.com','fred@mail.com','joe@mail.com');
$ids=array(1,2,3);
$u_keys=array_fill(0,count($names),array('name','email','id'));
$users=array_combine($keys,array_map('mymap_arrays',$u_keys,$names,$emails,$ids));
</code>```

this returns:

```<code>Array
(
    [u1] => Array
        (
            [name] => Bob
            [email] => bob@mail.com
            [id] => 1
        )

    [u2] => Array
        (
            [name] => Fred
            [email] => fred@mail.com
            [id] => 2
        )

    [u3] => Array
        (
            [name] => Joe
            [email] => joe@mail.com
            [id] => 3
        )

)
</code>```

EDIT: After lots of benchmarking I wend with a version of Glass Robots answer to handle a variable number of arrays, it's slower than his obviously, but faster than my original:

```<code>function test_my_new(){
    $args=func_get_args();
    $keys=array_shift($args);
    $vkeys=array_shift($args);
    $results=array();
    foreach($args as $key=>$array){
        $vkey=array_shift($vkeys);
        foreach($array as $akey=>$val){
            $result[$keys[$akey]][$vkey]=$val;
        }
    }
    return $result;
}
$keys=array('u1','u2','u3');
$names=array('Bob','Fred','Joe');
$emails=array('bob@mail.com','fred@mail.com','joe@mail.com');
$ids=array(1,2,3);
$vkeys=array('name','email','id');
test_my_new($keys,$vkeys,$names,$emails,$ids);
</code>```

答:
Simply try this for multiples array combine (if you have length of arrays)</p>

```<code>$array_id = array ('1', '2', '3');
$array1 = array ('arr1_value1', 'arr1_value2', 'arr1_value3');
$array2 = array ('arr2_value1', 'arr2_value2', 'arr2_value3');
$array3 = array ('arr3_value1', 'arr3_value2', 'arr3_value3');

  $lenght = count($array_id);
  $i = 0;

  while ($i < $lenght) {
    $result[] = array(
        $array_id[$i]
        , $array1[$i]
        , $array2[$i]
        , $array3[$i]
    );
    $i++;
  }

echo '```';
print_r($result);
</code>```

Body:
ok, assuming I have 5 arrays, all just indexed arrays, and I would like to combine them, this is the best way I can figure, is there a better way to handle this?

function mymap_arrays(){
    $args=func_get_args();
    $key=array_shift($args);
    return array_combine($key,$args);
}
$keys=array('u1','u2','u3');
$names=array('Bob','Fred','Joe');
$emails=array('bob@mail.com','fred@mail.com','joe@mail.com');
$ids=array(1,2,3);
$u_keys=array_fill(0,count($names),array('name','email','id'));
$users=array_combine($keys,array_map('mymap_arrays',$u_keys,$names,$emails,$ids));

this returns:

Array
(
    [u1] => Array
        (
            [name] => Bob
            [email] => bob@mail.com
            [id] => 1
        )

    [u2] => Array
        (
            [name] => Fred
            [email] => fred@mail.com
            [id] => 2
        )

    [u3] => Array
        (
            [name] => Joe
            [email] => joe@mail.com
            [id] => 3
        )

)

EDIT: After lots of benchmarking I wend with a version of Glass Robots answer to handle a variable number of arrays, it's slower than his obviously, but faster than my original:

function test_my_new(){
    $args=func_get_args();
    $keys=array_shift($args);
    $vkeys=array_shift($args);
    $results=array();
    foreach($args as $key=>$array){
        $vkey=array_shift($vkeys);
        foreach($array as $akey=>$val){
            $result[$keys[$akey]][$vkey]=$val;
        }
    }
    return $result;
}
$keys=array('u1','u2','u3');
$names=array('Bob','Fred','Joe');
$emails=array('bob@mail.com','fred@mail.com','joe@mail.com');
$ids=array(1,2,3);
$vkeys=array('name','email','id');
test_my_new($keys,$vkeys,$names,$emails,$ids);

Body:
Simply try this for multiples array combine (if you have length of arrays)

$array_id = array ('1', '2', '3');
$array1 = array ('arr1_value1', 'arr1_value2', 'arr1_value3');
$array2 = array ('arr2_value1', 'arr2_value2', 'arr2_value3');
$array3 = array ('arr3_value1', 'arr3_value2', 'arr3_value3');

  $lenght = count($array_id);
  $i = 0;

  while ($i < $lenght) {
    $result[] = array(
        $array_id[$i]
        , $array1[$i]
        , $array2[$i]
        , $array3[$i]
    );
    $i++;
  }

echo '<pre>';
print_r($result);


答:
r1 can be zero, making log(r1) undefined.

furthermore, don't use rand() except when you need your numbers to look random to a human in a hurry. Use <random> instead

Title: Getting "-nan(ind)" when trying to generate random variates


问:
Bot Framework Emulator VS Web Chat
I have this code :

```<code> if (activity.Type == ActivityTypes.Message)
        {
            var audioAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Equals("audio/wav") || a.ContentType.Equals("application/octet-stream"));
            if (audioAttachment != null)
            {
                var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                var stream = await GetAudioStream(connector, audioAttachment);
                var text = await this.speechService.GetTextFromAudioAsync(stream);
                Activity reply = activity.CreateReply(text);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
            }
        }
        else
        {
            HandleSystemMessage(activity);
        }
        var response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
</code>```

When i input something it check if is audio file or text and if is audio it sent to Bing Speech in order to get text out of audio file.

I tested it on Bot Framework emulator and is working but when i try to upload a file from web chat it say couldn't sent also i got this error
-- There was an error sending this message to your bot: HTTP status code GatewayTimeout

I want to deploy this bot on skype and to upload audio file or to use microfon and to get text form this.

答:
Seems like the error was because i was trying to upload a file bigger than 15 seconds.
I cut the respective file in to a 10 seconds sequence and now i working as intended.

-- I still don't know why bot framework accept larger files, it seems like at the half way sending the file stops and then after few seconds it retake the sending from where it stops --

Title: Bot Framework Emulator VS Web Chat

Body:
I have this code :

 if (activity.Type == ActivityTypes.Message)
        {
            var audioAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Equals("audio/wav") || a.ContentType.Equals("application/octet-stream"));
            if (audioAttachment != null)
            {
                var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                var stream = await GetAudioStream(connector, audioAttachment);
                var text = await this.speechService.GetTextFromAudioAsync(stream);
                Activity reply = activity.CreateReply(text);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
            }
        }
        else
        {
            HandleSystemMessage(activity);
        }
        var response = Request.CreateResponse(HttpStatusCode.OK);
        return response;

When i input something it check if is audio file or text and if is audio it sent to Bing Speech in order to get text out of audio file.

I tested it on Bot Framework emulator and is working but when i try to upload a file from web chat it say couldn't sent also i got this error
-- There was an error sending this message to your bot: HTTP status code GatewayTimeout

I want to deploy this bot on skype and to upload audio file or to use microfon and to get text form this.


问:
Java Application script to display the number of rows in a column, of a SQL table. Error in SQL query. The output should be in a label
Hello there. I am trying to get the result of my SQL query into a label on my java application. Any advice on what I am doing wrong? (The label is "lblTest", the table is "transactions" and the column in "TRANS_ID"). Thank you in advance.

```<code>    try
    {
        conMySQLConnectionString =
        DriverManager.getConnection
        (strDBConnectionString,strDBUser,strDBPassword);
        stStatement = conMySQLConnectionString.createStatement();
        String strQuery = "SELECT COUNT(TRANS_ID)"+"FROM transactions";
        stStatement.execute(strQuery);
        rs = stStatement.getResultSet();
        lblTest.setText(rs.getString(1));

    }
    catch (Exception e)
    {
        JOptionPane.showMessageDialog(null,e);
    }
</code>```

}

答:
You have to check if the resultSet contains at least one record :  </p>

```<code>if(rs.first()){
    lblTest.setText(rs.getString(1));
 }
</code>```

Body:
Hello there. I am trying to get the result of my SQL query into a label on my java application. Any advice on what I am doing wrong? (The label is "lblTest", the table is "transactions" and the column in "TRANS_ID"). Thank you in advance.

    try
    {
        conMySQLConnectionString =
        DriverManager.getConnection
        (strDBConnectionString,strDBUser,strDBPassword);
        stStatement = conMySQLConnectionString.createStatement();
        String strQuery = "SELECT COUNT(TRANS_ID)"+"FROM transactions";
        stStatement.execute(strQuery);
        rs = stStatement.getResultSet();
        lblTest.setText(rs.getString(1));

    }
    catch (Exception e)
    {
        JOptionPane.showMessageDialog(null,e);
    }

}

Body:
You have to check if the resultSet contains at least one record :

if(rs.first()){
    lblTest.setText(rs.getString(1));
 }


问:
"Cannot change DataType of a column once it has data" error in Visual Studio 2005 DataSet Designer
I've got a DataSet in VisualStudio 2005.  I need to change the datatype of a column in one of the datatables from System.Int32 to System.Decimal.  When I try to change the datatype in the DataSet Designer I receive the following error:

Property value is not valid.  Cannot change DataType of a column once
  it has data.

From my understanding, this should be changing the datatype in the schema for the DataSet.  I don't see how there can be any data to cause this error.

Does any one have any ideas?

答: I have found a work around.  If I delete the data column and add it back with the different data type, then it will work.</p>

OwnerDisplayName: firedfly


问:
Why does the VBA Editor open on its own sometimes?
I created a script in Outlook 2003 VBA that watches for new appointments, and sets them to tentative and no reminder as I create them.  I find that seemingly at random, the VBA editor will open itself.  It doesn't happen when I use the new script, but it did happen this morning when I un-hibernated my laptop, for example.

The editor doesn't pop up any runtime errors or highlight any lines in the script, it's just there as if I had pressed Alt-F11 to launch it.  Sometimes I close other apps and see that it's been sitting back there for a while.

This behavior has only been occurring since I created this new script.  Any ideas why this would occur?

答:
If you have previously set breakpoints, it may be that you still have a phantom breakpoint. Try choosing "remove all breakpoints" and see if that clears the problem.

Check also that you have not chosen "Break on all errors" under options, and that your error handler is functioning properly.

OwnerDisplayName: Kevin Finn

OwnerDisplayName: Remou


问:
What is the correct way to stop a checkout from an event observer in Magento?
I am verifying shipping quotes during the event checkout_controller_onepage_save_shipping_method and if the verification fails i want to send the user back to shipping method selection but I would also like to display a message saying why it failed. Does Magento have a way of doing this built in?

I am already verifying the data I just lack the redirect to shipping methods and way to display a message.

答:
Alan Storm's answer is, as ever, informative and enlightening. But in this situation the onepage checkout is mostly AJAX which ignores the session error message, you won't see it until leaving the checkout page.

In saveShippingMethodAction there is the following line:

```<code>$result = $this->getOnepage()->saveShippingMethod($data);
</code>```

...and then $result is JSON encoded. If you override Mage_Checkout_Model_Type_Onepage::saveShippingMethod to perform your check then control what is returned you can insert an error message that will be returned to the browser and shown to the user in a popup.

Your override might look something like this:

```<code>public function saveShippingMethod($shippingMethod)
{
    if ($this->doesntApplyHere()) {
        return array('error' => -1, 'message' => $this->_helper->__('Explain the problem here.'));
    }
    return parent::saveShippingMethod($shippingMethod);
}
</code>```

Body:
Alan Storm's answer is, as ever, informative and enlightening. But in this situation the onepage checkout is mostly AJAX which ignores the session error message, you won't see it until leaving the checkout page.

In saveShippingMethodAction there is the following line:

$result = $this->getOnepage()->saveShippingMethod($data);

...and then $result is JSON encoded. If you override Mage_Checkout_Model_Type_Onepage::saveShippingMethod to perform your check then control what is returned you can insert an error message that will be returned to the browser and shown to the user in a popup.

Your override might look something like this:

public function saveShippingMethod($shippingMethod)
{
    if ($this->doesntApplyHere()) {
        return array('error' => -1, 'message' => $this->_helper->__('Explain the problem here.'));
    }
    return parent::saveShippingMethod($shippingMethod);
}


问:
Lock a ToggleButton after checking
I have a GUI which is built with the MVVM-Pattern. In the View there is a Toggle-Button, which IsChecked property is bound to a bool property in the ViewModel.

Now it is only allowed to turn the ToggleButton (and the bool property in the ViewModel) from false to true over the View. A method resets the bool property in the ViewModel, so the user can switch the Toggle-Button again from false to true.

How can I lock the Toggle-Button in the View, without using the IsEnabled Property?

Thanks.

答:
Although I highly advise using the IsEnabled property, binding the toggle state to a the visibility of a transparent canvas using an IValueConverter should work for you.

```<code><Grid>
    <ToggleButton Content="Hello"/>
    <Canvas Background="Transparent" Visibility="Visible"/>
</Grid>
</code>```

Here's a link to the MSDN page for the BooleanToVisibilityConverter

Title: Lock a ToggleButton after checking

Body:
Although I highly advise using the IsEnabled property, binding the toggle state to a the visibility of a transparent canvas using an IValueConverter should work for you.

<Grid>
    <ToggleButton Content="Hello"/>
    <Canvas Background="Transparent" Visibility="Visible"/>
</Grid>

Here's a link to the MSDN page for the BooleanToVisibilityConverter


问:
Error installing nodejs in arch linux
Okay so i just made a fresh install of nodejs package on archlinux using pacman. Command for the same was
sudo pacman -S nodejs npm . Now when i tried to run the same i am getting error as

node: error while loading shared libraries: libicui18n.so.57: Which pretty much means that libicu is either not there or not the correct version. The problem that i am facing is that it is not there in pacman. I tried
sudo pacman -S libicu, which returned not able to find the package. What is the right way to resolve this issue. FYI : just a note, i would prefer not to install from source and prefer using pacman for the same. If there is any other output that you need to know please comment below and will let you know about the same.

I am currently on manjaro i3 fresh install.

答:
did you use testing repo?
If you enabled testing repositories, but later on decided to disable them, you should:

Remove/Comment them from /etc/pacman.conf

pacman -Syuu to "rollback" your updates from these repositories.

The second item is optional, but keep it in mind if you notice any problems.

Also you can install stable ver : pacman -S core/icu

Title: Error installing nodejs in arch linux

ContentLicense: CC BY-SA 4.0


问:
Android Studio 3.0 migration AAPT2 error
After migrating my existing project to Android Studio 3.0, it is not compiling. Below are the log details:

```<code>Error:java.util.concurrent.ExecutionException:
    java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for
details
Error:Execution failed for task ':app:processDebugResources'.
Failed to execute aapt
Information:BUILD FAILED in 27s
Information:11 errors
Information:0 warnings
</code>```

答:
Is your username in OS cyrillic? If so - you need to change the .gradle resource folder in settings to path which does not contain cyrillic symbols.
In ->Settings-> Build, Execution -> Gradle change Service directory path to "C:/Users/Public/.gradle"

Body:
After migrating my existing project to Android Studio 3.0, it is not compiling. Below are the log details:

Error:java.util.concurrent.ExecutionException:
    java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for
details
Error:Execution failed for task ':app:processDebugResources'.
Failed to execute aapt
Information:BUILD FAILED in 27s
Information:11 errors
Information:0 warnings


问:
Read CSV data and add it into dictionary
This is an empty Dictionary

```<code>d = {}
</code>```

This is the csv file data

```<code>M, Max, Sporting, Football, Cricket
M, Jack, Sporting, Cricket, Tennis
M, Kevin, Sporting, Cricket, Basketball
M, Ben, Sporting, Football, Rugby
</code>```

I tried to use the following code to append data from the csv to dictionary.

```<code>with open('example.csv', "r") as csvfile:
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            if row:
                d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
</code>```

But it gives me an error:

```<code>d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
IndexError: list index out of range
</code>```

It there any way, i can add data from csv to the dictionary, in the form:

```<code>d = {'M': {'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}}}
</code>```

I am new to this so help me.

答:
Straightforwardly:

```<code>import csv, collections

with open('example.csv', 'r') as f:
    reader = csv.reader(f, skipinitialspace=True)
    result = collections.defaultdict(dict)
    for r in reader:
        if not result[r[0]].get(r[1]): result[r[0]][r[1]] = {}
        if not result[r[0]][r[1]].get(r[2]):
            result[r[0]][r[1]][r[2]] = r[-2:]

print(dict(result))
</code>```

The output:

```<code>{'M': {'Kevin': {'Sporting': ['Cricket', 'Basketball']}, 'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}, 'Ben': {'Sporting': ['Football', 'Rugby']}}}
</code>```

Body:
This is an empty Dictionary

d = {}

This is the csv file data

M, Max, Sporting, Football, Cricket
M, Jack, Sporting, Cricket, Tennis
M, Kevin, Sporting, Cricket, Basketball
M, Ben, Sporting, Football, Rugby

I tried to use the following code to append data from the csv to dictionary.

with open('example.csv', "r") as csvfile:
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            if row:
                d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}

But it gives me an error:

d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
IndexError: list index out of range

It there any way, i can add data from csv to the dictionary, in the form:

d = {'M': {'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}}}

I am new to this so help me.

Body:
Straightforwardly:

import csv, collections

with open('example.csv', 'r') as f:
    reader = csv.reader(f, skipinitialspace=True)
    result = collections.defaultdict(dict)
    for r in reader:
        if not result[r[0]].get(r[1]): result[r[0]][r[1]] = {}
        if not result[r[0]][r[1]].get(r[2]):
            result[r[0]][r[1]][r[2]] = r[-2:]

print(dict(result))

The output:

{'M': {'Kevin': {'Sporting': ['Cricket', 'Basketball']}, 'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}, 'Ben': {'Sporting': ['Football', 'Rugby']}}}


问:
VHDL - Why are you not allowed to use variables in generate loops
I know, variables are only allowed in processes, but why are you not allowed to use them in generate loops.
There are no problems for synthesizing such constructs, because they are evaluated before.

The code could get more readable without this restriction.

```<code>lbl1: for i in data_out'range generate
    lbl2a: component comp_a
        port map(
            clk => clk,
            out => out(0)(i)
            in_a => data_in(i*w + offset to i*w + w + offset));
    lbl2b: component comp_b
        port map(
            clk => clk,
            out => out(1)(i)
            in_b => data_in(i*w + offset to i*w + w + offset));
    .
    .
    .
    lbl2n: component comp_n
        port map(
            clk => clk,
            out => out(n)(i)
            in_n => data_in(i*w + offset to i*w + w + offset));
end generate lbl1;
</code>```

Or just write

```<code>lbl1: for i in data_out'range generate
    variable lower : integer := i*w + offset;
    variable upper : integer := i*w + w + offset;
    lbl2a: component comp_a
        port map(
            clk => clk,
            out => out(0)(i)
            in_a => data_in(lower to upper));
    lbl2b: component comp_b
        port map(
            clk => clk,
            out => out(1)(i)
            in_b => data_in(lower to upper));
    .
    .
    .
    lbl2n: component comp_n
        port map(
            clk => clk,
            out => out(n)(i)
            in_n => data_in(lower to upper));
end generate lbl1;
</code>```

The code is not from any example, it could fail at any point, but i think you get my point. It would be easier to read and maintain. The generated variable could get out of scope outside the generate process.

So is there any reason WHY this isn't allowed or is it just a historical artefact from previous vhdl standards?

答:
If you would like to declare something, it needs to be in a declarative region. A generate statement is a bit special in that it does not need a begin; you can (as you have) use:

```<code>GenerateLoop : for i in data_out'range generate
  -- Code here
end generate;
</code>```

If you would like to declare things as part of the loop, you must have a declarative region, which, with a generate statement, would look like this:

```<code>GenerateLoop : for i in data_out'range generate
  -- Declarative region
begin
  -- Code here
end generate;
</code>```

You should be able to declare things in this declarative region. Note that you will need to use a signal or constant (it looks like a constant will be more appropriate) instead of a variable.

Body:
I know, variables are only allowed in processes, but why are you not allowed to use them in generate loops.
There are no problems for synthesizing such constructs, because they are evaluated before.

The code could get more readable without this restriction.

lbl1: for i in data_out'range generate
    lbl2a: component comp_a
        port map(
            clk => clk,
            out => out(0)(i)
            in_a => data_in(i*w + offset to i*w + w + offset));
    lbl2b: component comp_b
        port map(
            clk => clk,
            out => out(1)(i)
            in_b => data_in(i*w + offset to i*w + w + offset));
    .
    .
    .
    lbl2n: component comp_n
        port map(
            clk => clk,
            out => out(n)(i)
            in_n => data_in(i*w + offset to i*w + w + offset));
end generate lbl1;

Or just write

lbl1: for i in data_out'range generate
    variable lower : integer := i*w + offset;
    variable upper : integer := i*w + w + offset;
    lbl2a: component comp_a
        port map(
            clk => clk,
            out => out(0)(i)
            in_a => data_in(lower to upper));
    lbl2b: component comp_b
        port map(
            clk => clk,
            out => out(1)(i)
            in_b => data_in(lower to upper));
    .
    .
    .
    lbl2n: component comp_n
        port map(
            clk => clk,
            out => out(n)(i)
            in_n => data_in(lower to upper));
end generate lbl1;

The code is not from any example, it could fail at any point, but i think you get my point. It would be easier to read and maintain. The generated variable could get out of scope outside the generate process.

So is there any reason WHY this isn't allowed or is it just a historical artefact from previous vhdl standards?

Body:
If you would like to declare something, it needs to be in a declarative region. A generate statement is a bit special in that it does not need a begin; you can (as you have) use:

GenerateLoop : for i in data_out'range generate
  -- Code here
end generate;

If you would like to declare things as part of the loop, you must have a declarative region, which, with a generate statement, would look like this:

GenerateLoop : for i in data_out'range generate
  -- Declarative region
begin
  -- Code here
end generate;

You should be able to declare things in this declarative region. Note that you will need to use a signal or constant (it looks like a constant will be more appropriate) instead of a variable.


问:
Parallax background-image in wrapper not responsive
I made a website using an HTML5 template and adjusting it. Everything worked fine so far (apart from probably having messy files).

Now, my issue:

I am using a parallax background image inside a section-element, and it is not responsive on mobile. If I resize my browser window, it works fine. But if I look at the actual size on my smartphone screen, it's not working.

This is the code I used in my CSS-file. I tried to do it with code that I found in this community and merged it with what was already inside the template.

```<code>.wrapper.rechtsgebiete {
    background-color: #ffffff;
    color: rgba(255, 255, 255, 0.75);
    padding: 10em 0 6em 0 ;
    display: -moz-flex;
    display: -webkit-flex;
    display: -ms-flex;
    display: flex;
    -moz-align-items: center;
    -webkit-align-items: center;
    -ms-align-items: center;
    align-items: center;
    -moz-justify-content: center;
    -webkit-justify-content: center;
    -ms-justify-content: center;
    justify-content: center;
    background-attachment: fixed;
    background-color: rgba(51,153,255, 0.80);
    background-image: url(../../images/la-rechtsgebiete.jpg);
    background-position: top left;
    background-size: cover;
    border: none;
    min-height: 50vh !important;
    position: relative;
    text-align: center;
    width: 100%;
        }
</code>```

This is the HTML-element:

```<code>    <section id="rechtsgebiete" class="wrapper rechtsgebiete" style="padding-top: 30vh; padding-bottom: 25vh;">
    <div class="inner"><center>
    <h1 class="font-volkhov2"><span style="color:white;">Services & Rechtsgebiete</span></h1></center>
    </div>
    </section>
</code>```

Here you can see the issue; the first header-image works fine, everything else doesn't: http://lexadvice.de/leistungen.html

How can I solve this issue?
I tried changing the position value, but I guess it might have something to do with the width-property. Trial and error did not get me far this time.

答:
One of the media style rules is overriding the background-attachment: fixed; in file:    leistungen-banner.css

```<code>@media screen and (max-width: 1280px)
    #banner {
        padding: 6em 0 3em 0;
        background-attachment: scroll;
     }
}
</code>```

that's why its not working on mobile. Please fix that.

Alternatively you can add and inline rule background-attachment:fixed to your #banner element.

Refer below screenshot (taken from chrome dev tools):

Body:
I made a website using an HTML5 template and adjusting it. Everything worked fine so far (apart from probably having messy files).

Now, my issue:

I am using a parallax background image inside a section-element, and it is not responsive on mobile. If I resize my browser window, it works fine. But if I look at the actual size on my smartphone screen, it's not working.

This is the code I used in my CSS-file. I tried to do it with code that I found in this community and merged it with what was already inside the template.

.wrapper.rechtsgebiete {
    background-color: #ffffff;
    color: rgba(255, 255, 255, 0.75);
    padding: 10em 0 6em 0 ;
    display: -moz-flex;
    display: -webkit-flex;
    display: -ms-flex;
    display: flex;
    -moz-align-items: center;
    -webkit-align-items: center;
    -ms-align-items: center;
    align-items: center;
    -moz-justify-content: center;
    -webkit-justify-content: center;
    -ms-justify-content: center;
    justify-content: center;
    background-attachment: fixed;
    background-color: rgba(51,153,255, 0.80);
    background-image: url(../../images/la-rechtsgebiete.jpg);
    background-position: top left;
    background-size: cover;
    border: none;
    min-height: 50vh !important;
    position: relative;
    text-align: center;
    width: 100%;
        }

This is the HTML-element:

Services & Rechtsgebiete

Here you can see the issue; the first header-image works fine, everything else doesn't: http://lexadvice.de/leistungen.html

How can I solve this issue?
I tried changing the position value, but I guess it might have something to do with the width-property. Trial and error did not get me far this time.

Body:
One of the media style rules is overriding the background-attachment: fixed; in file:    leistungen-banner.css

@media screen and (max-width: 1280px)
    #banner {
        padding: 6em 0 3em 0;
        background-attachment: scroll;
     }
}

that's why its not working on mobile. Please fix that.

Alternatively you can add and inline rule background-attachment:fixed to your #banner element.

Refer below screenshot (taken from chrome dev tools):


问:
Injecting Generic type parameters with AutoFac
I think I am really confused about what I can do with AutoFac, can someone please put me on track.

I have a base type

```<code>class PersonBase{
    public string SaySomething(){
       return "I am base";
    }
}
</code>```

I derive two concrete classes

```<code>class FakePerson : PersonBase{
    public override string SaySomething(){
       return "I'm so Fake";
    }
}

class RealPerson : PersonBase{
    public override string SaySomething(){
       return "I am For Real";
    }
}
</code>```

Create a generic class, PersonHandler, to deal with different types of people and would like the PersonHandler to instantiate the person at the appropriate time, so I do not want an instance of Person injected, just need to derived type

```<code>class PersonHandler<T>
    where T : PersonBase, new() {

    T _Person;

    public DoWork(){
        _Person = new T();
        _Person.SaySomething();
    }
}
</code>```

Now I try to use the handler, after registering the types as detailed next, with varying results.

```<code>var ph = contrainer.Resolve<PersonHandler<PersonBase>>();
ph.DoWork();
</code>```

I attempted to register the types as follows

```<code>1. vBuilder.RegisterType<PersonHandler<FakePerson>>().As<PersonHandler<PersonBase>>();
</code>```

This gives me an error stating the PersonHandler<FakePerson> is not assignable to PersonHandler<PersonBase> (or the other way around I don't recal which)

```<code>2. vBuilder.RegisterGeneric<typeof(PersonHandler<>)>
   vBuilder.RegisterType<FakePerson>().As<PersonBase>();
</code>```

This does not resolve PersonBase to FakePerson, but just gives PersonHandler<PersonBase>, So it results in "I am Base"

```<code>3. vBuilder.RegisterGeneric(typeof(PersonHandler<FakePerson>)).As(typeof(PersonHandler<PersonBase>));
</code>```

This given an error saying that PersonHandler<FakePerson> is not an open type

So now I have been chasing my tale all day and, frankly, it is getting quit tedious,

PLEASE HELP

答:
The (almost) correct solution is this one that you already tried:

```<code>builder.RegisterType<PersonHandler<FakePerson>>()
    .As<PersonHandler<PersonBase>>();
</code>```

The reason Autofac gave you an error is that generic class types in C# don't work this way.

That is, you can't write:

```<code>PersonHandler<PersonBase> ph = new PersonHandler<FakePerson>();
</code>```

(Give it a try in your IDE - the compiler will reject it.)

The reason for this is that contravariance, the required feature added in C#4, only supports interface types.

To cut a long story short, if you create IPersonHandler<T> and use that as the service then the above code will work as expected:

```<code>interface IPersonHandler<in T>
    where T : PersonBase, new() {

    void DoWork();
}
</code>```

Note the in parameter on the interface declaration.

Make PersonHandler<T> implement IPersonHandler<T>:

```<code>class PersonHandler<T> : IPersonHandler<T>
    where T : PersonBase, new() {
</code>```

Then register like so:

```<code>builder.RegisterType<PersonHandler<FakePerson>>()
    .As<IPersonHandler<PersonBase>>();
</code>```

You can then get handlers using:

```<code>IPersonHandler<PersonBase> handler =
    container.Resolve<IPersonHandler<PersonBase>>();
</code>```

The returned handler object will be of type PersonHandler<FakePerson>.

Body:
I think I am really confused about what I can do with AutoFac, can someone please put me on track.

I have a base type

class PersonBase{
    public string SaySomething(){
       return "I am base";
    }
}

I derive two concrete classes

class FakePerson : PersonBase{
    public override string SaySomething(){
       return "I'm so Fake";
    }
}

class RealPerson : PersonBase{
    public override string SaySomething(){
       return "I am For Real";
    }
}

Create a generic class, PersonHandler, to deal with different types of people and would like the PersonHandler to instantiate the person at the appropriate time, so I do not want an instance of Person injected, just need to derived type

class PersonHandler<T>
    where T : PersonBase, new() {

    T _Person;

    public DoWork(){
        _Person = new T();
        _Person.SaySomething();
    }
}

Now I try to use the handler, after registering the types as detailed next, with varying results.

var ph = contrainer.Resolve<PersonHandler<PersonBase>>();
ph.DoWork();

I attempted to register the types as follows

1. vBuilder.RegisterType<PersonHandler<FakePerson>>().As<PersonHandler<PersonBase>>();

This gives me an error stating the PersonHandler<FakePerson> is not assignable to PersonHandler<PersonBase> (or the other way around I don't recal which)

2. vBuilder.RegisterGeneric<typeof(PersonHandler<>)>
   vBuilder.RegisterType<FakePerson>().As<PersonBase>();

This does not resolve PersonBase to FakePerson, but just gives PersonHandler<PersonBase>, So it results in "I am Base"

3. vBuilder.RegisterGeneric(typeof(PersonHandler<FakePerson>)).As(typeof(PersonHandler<PersonBase>));

This given an error saying that PersonHandler<FakePerson> is not an open type

So now I have been chasing my tale all day and, frankly, it is getting quit tedious,

PLEASE HELP

Body:
The (almost) correct solution is this one that you already tried:

builder.RegisterType<PersonHandler<FakePerson>>()
    .As<PersonHandler<PersonBase>>();

The reason Autofac gave you an error is that generic class types in C# don't work this way.

That is, you can't write:

PersonHandler<PersonBase> ph = new PersonHandler<FakePerson>();

(Give it a try in your IDE - the compiler will reject it.)

The reason for this is that contravariance, the required feature added in C#4, only supports interface types.

To cut a long story short, if you create IPersonHandler<T> and use that as the service then the above code will work as expected:

interface IPersonHandler<in T>
    where T : PersonBase, new() {

    void DoWork();
}

Note the in parameter on the interface declaration.

Make PersonHandler<T> implement IPersonHandler<T>:

class PersonHandler<T> : IPersonHandler<T>
    where T : PersonBase, new() {

Then register like so:

builder.RegisterType<PersonHandler<FakePerson>>()
    .As<IPersonHandler<PersonBase>>();

You can then get handlers using:

IPersonHandler<PersonBase> handler =
    container.Resolve<IPersonHandler<PersonBase>>();

The returned handler object will be of type PersonHandler<FakePerson>.


问:
When reading from files, do you check the EOF condition before or after reading
Using pseudocode...

```<code>aFile = open("file.txt")
//x = aFile.readLine()  <- reading before checking end of file condition
while !aFile.endOfFile()
    //x = aFile.readLine() <- only read if you have not already read
                                          from the file before the loop
    print(x)
    //x = aFile.readLine()  <- if reading before checking end of file,
                            you will read again after printing the previous x value
end while
aFile.close()
</code>```

My question is, would you need to read from the file before you can check the endOfFile condition holds false or would you check the condition before reading from the file?

答:
To get information about end of file You first have to access this file(stream). Then it depends on language/function You are using to check this condition. But for example in C You can do it in this way:</p>

```<code>FILE * pFile;
int c;
int n = 0;
pFile=fopen ("myfile.txt","r");

do {
  //First get character
  c = fgetc (pFile);
  //Then check for EOF(end of line)
} while (c != EOF);

fclose (pFile);
</code>```

Body:
Using pseudocode...

aFile = open("file.txt")
//x = aFile.readLine()  <- reading before checking end of file condition
while !aFile.endOfFile()
    //x = aFile.readLine() <- only read if you have not already read
                                          from the file before the loop
    print(x)
    //x = aFile.readLine()  <- if reading before checking end of file,
                            you will read again after printing the previous x value
end while
aFile.close()

My question is, would you need to read from the file before you can check the endOfFile condition holds false or would you check the condition before reading from the file?

Body:
To get information about end of file You first have to access this file(stream). Then it depends on language/function You are using to check this condition. But for example in C You can do it in this way:

FILE * pFile;
int c;
int n = 0;
pFile=fopen ("myfile.txt","r");

do {
  //First get character
  c = fgetc (pFile);
  //Then check for EOF(end of line)
} while (c != EOF);

fclose (pFile);