问:
Cannot convert value of type '[Page]' to expected element type 'Page'
So here is what I'm doing.  Made a table with different "rides"  the "ride cells" all link to one pageControllerView, but I want them to link to static information (var) about that one specific ride.  Meaning that each click on a tableview RideCell will link to that specific 'rides' information stored in a pageview, not to a generic page view...

The error is on Ride2 and says "cannot convert" and I am sure that it is related to the info[Page] component to the end of the line of code:

```<code>    func setupRides() {

    let ride2 = Ride(title: "Contacts", route: "", image: #imageLiteral(resourceName: "main"), info: [tron])
//  let ride3 = Ride(title: "Pirates of the Caribbean", route: "Event", image: #imageLiteral(resourceName: "pirates"), info: [Page(title: "Pirates of the Caribbean", message: "Soaring Over the Horizon (FP)", imageName: "main")])
</code>```

I am just trying to get it to work on one before I bring the process to the rest.

Other important code as follows:

```<code>var tron: [Page] = {
let firstPage = Page(title: "Share a great listen", message: "It's free to send your books to the people in your life. Every recipient's first book is on us.", imageName: "main")
let secondPage = Page(title: "Send from your library", message: "Tap the More menu next to any book. Choose \"Send this Book\"", imageName: "main")
let thirdPage = Page(title: "Send from the player", message: "Tap the More menu in the upper corner. Choose \"Send this Book\"", imageName: "main")
return [firstPage, secondPage, thirdPage]
}()
</code>```

This is what my Ride and Page Classes look like.

```<code>class Ride {
let title: String
let route: String
let image: UIImage
let info: [Page]

init(title: String, route: String, image: UIImage, info: [Page]){
    self.title = title
    self.route = route
    self.image = image
    self.info = info
}
}

class Page {
let title: String
let message: String
let imageName: String

init(title: String, message: String, imageName: String) {
    self.title = title
    self.message = message
    self.imageName = imageName
}
}
</code>```

Sorry if this is a Noob question.  I did RTFF, but haven't found yet...

答:
tron is an array of Page since it is declared as [Page].

When you do [tron] you are putting tron in another array. You now you have [[Page]] which is an array of arrays of Page.

So simply do:

```<code>let ride2 = Ride(title: "Contacts", route: "", image: #imageLiteral(resourceName: "main"), info: tron)
</code>```

Body:
So here is what I'm doing.  Made a table with different "rides"  the "ride cells" all link to one pageControllerView, but I want them to link to static information (var) about that one specific ride.  Meaning that each click on a tableview RideCell will link to that specific 'rides' information stored in a pageview, not to a generic page view...

The error is on Ride2 and says "cannot convert" and I am sure that it is related to the info[Page] component to the end of the line of code:

    func setupRides() {

    let ride2 = Ride(title: "Contacts", route: "", image: #imageLiteral(resourceName: "main"), info: [tron])
//  let ride3 = Ride(title: "Pirates of the Caribbean", route: "Event", image: #imageLiteral(resourceName: "pirates"), info: [Page(title: "Pirates of the Caribbean", message: "Soaring Over the Horizon (FP)", imageName: "main")])

I am just trying to get it to work on one before I bring the process to the rest.

Other important code as follows:

var tron: [Page] = {
let firstPage = Page(title: "Share a great listen", message: "It's free to send your books to the people in your life. Every recipient's first book is on us.", imageName: "main")
let secondPage = Page(title: "Send from your library", message: "Tap the More menu next to any book. Choose \"Send this Book\"", imageName: "main")
let thirdPage = Page(title: "Send from the player", message: "Tap the More menu in the upper corner. Choose \"Send this Book\"", imageName: "main")
return [firstPage, secondPage, thirdPage]
}()

This is what my Ride and Page Classes look like.

class Ride {
let title: String
let route: String
let image: UIImage
let info: [Page]

init(title: String, route: String, image: UIImage, info: [Page]){
    self.title = title
    self.route = route
    self.image = image
    self.info = info
}
}

class Page {
let title: String
let message: String
let imageName: String

init(title: String, message: String, imageName: String) {
    self.title = title
    self.message = message
    self.imageName = imageName
}
}

Sorry if this is a Noob question.  I did RTFF, but haven't found yet...

Body:
tron is an array of Page since it is declared as [Page].

When you do [tron] you are putting tron in another array. You now you have [[Page]] which is an array of arrays of Page.

So simply do:

let ride2 = Ride(title: "Contacts", route: "", image: #imageLiteral(resourceName: "main"), info: tron)


来源: stackexchange

问:
How do I strip a file extension from a string in C?
How do I strip a file extension from a string in C?

For example,

If I have the filenames with the file extensions

hello.txt

hello.c

hello.java

should all result in just the filename without the extension as

hello

the length of the file extension shouldn't matter.

the function should also be portable and not system dependent.

I know how to get the file extension using strchr or strrchr. I've done this in Bash and in Python, but I've never had to do this in C.

Note: This is for a personal exercise to help strengthen my understanding of the C programming language.

答:
It may not be the best way, but a possible solution is putting a NULL terminator in the place of the dot, which can be achieved by the following code.</p>

```<code>char *filename_dot = strchr(filename, '.');
int offset = filename_dot - filename;
filename[offset] = '\0';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It may not be the best way, but a possible solution is putting a NULL terminator in the place of the dot, which can be achieved by the following code.

char *filename_dot = strchr(filename, '.');
int offset = filename_dot - filename;
filename[offset] = '\0';


问:
C: char* is not modifiable
I am writing a really basic trim function in my code:

```<code>void trim(char a[]){
    if (a[0] == 'a')
    {
        a += 4;
    }else{
        a += 5;
    }
}

int main(){
    char a[] = "add abc";
    char* b = "find abc";
    trim(a);
    trim(b);
    printf("a=%s, b=%s\n", a,b);
}
</code>```

For the trim function, it is supposed to return just "abc" for both a and b. And I checked in gdb, trim(a) worked perfectly inside the trim function. At end of the trim function, a is pointing to "abc". However, when it get returned back to the main function, a became "add abc" again.

Need some help from the community. Really appreciate!!!

答: a is passed by value to trim, so it's value is lost after the function returns. Pass it by reference (pointer to array or pointer to pointer) to retain the value in the calling program.

Title: C: char* is not modifiable

Body:
I am writing a really basic trim function in my code:

void trim(char a[]){
    if (a[0] == 'a')
    {
        a += 4;
    }else{
        a += 5;
    }
}

int main(){
    char a[] = "add abc";
    char* b = "find abc";
    trim(a);
    trim(b);
    printf("a=%s, b=%s\n", a,b);
}

For the trim function, it is supposed to return just "abc" for both a and b. And I checked in gdb, trim(a) worked perfectly inside the trim function. At end of the trim function, a is pointing to "abc". However, when it get returned back to the main function, a became "add abc" again.

Need some help from the community. Really appreciate!!!


问:
Where can I find the source code for the gmail, facebook, and twitter apps for android? Are they even open source?
There are some components I need to use from these three 'supposedly' open source apps for android.

I looked at the source code for android, but I can't seem to find the gmail app; I can only find the email app.

I looked at the source code for the official facebook sdk for android, but there is no source code for the actual facebook app; there only is the source for the sdk, not the app.

And as for the twitter app, I can't even find the source code repository despite a million articles on the web saying that the twitter for android is open source.

Does anyone know where?

答:
None of those apps are open-source as of November 2010, and I wouldn't hold out hope for any of them except the Twitter app (and even there, don't hold your breath). Here's why:

Facebook's client apps aren't open-source on any platforms that I know of, only their SDK is, and they've never made any claims that it would be, so I don't think there's any reason to expect it to ever be publicly available.

GMail, Maps, Talk, and the Market are part of the "Google Experience" apps that are the carrot Google uses to force carriers and manufacturers to make highly compatible Google-cobranded phones and not run off and break the system's ability to work with 3rd-party apps and services, so I'd also never expect those to go open-source (at least any more than I'd expect to see the entire source-code of the GMail web client pop up any time soon). In fact, they threaten/send C&D letters to companies and even ROM-makers that try to even distribute those apps in binary form without proper permission.

While you can't prove the nonexistence of something, the Twitter app's source hasn't been released to my knowledge as of 11/2010. They said in their I/O 2010 design presentation and the blog entry that accompanied it that it would be in the "next few weeks" and news outlets picked up on that and turned that into "it's open source," but there hasn't been a peep from them on that point since then. In fact, in the latest revisions of the Twitter app on the Market they seem to have also backpedaled and nuked a lot of the design elements they talked about in the IO presentations (quickaction popups are now iPhone-style in-row sliding actions, for example).
Google eventually opensourced the 2010 IO schedule app, which has a lot of the same goodies (Dashboard, action bar, sync management), though.

ContentLicense: CC BY-SA 2.5


问:
SQL Query for Vehicle Mileage
I’m trying to design a fleet management database for my university course.

Currently my query searches the “view” that I have created and calculates employees total mileage based on year, by subtracting their journey's end miles from their start miles, which works and groups them in a result.
But what I can’t do, no matter how hard I try, is to then query what employees do more than 25,000 miles a year from the result that I have created. I not sure if this is even possible to query the result of an alias column?

```<code>SELECT Assigned_Vehicle_id "Assigned Vehicle id",
       Payroll_Number "Payroll Number", First_Name "First Name",
       Surname, Vehicle_Registration "Vehicle Registration",
       Manufacturer_Name "Manufacturer Name", Model_Name "Model Name",
       SUM(End_Miles - Start_Miles) "Total Miles Driven"
  FROM Destinations
 WHERE YEAR(Start_Date) = 2016
 GROUP BY Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
       Vehicle_Registration, Manufacturer_Name, Model_Name;
</code>```

答:
In some ways, a HAVING clause as suggested by Jason in his answer is good, simple, and quite probably what's expected — even though it involves writing out the expression twice rather than allowing you to use the alias.  Some DBMS do, I believe, allow you to use an output column alias in subsequent clauses such as the GROUP BY or HAVING clauses, but the standard does not, so most DBMS do not either.

However, there is another alternative which would probably work:

```<code>SELECT "Assigned Vehicle id",
       "Payroll Number", "First Name",
       Surname, "Vehicle Registration",
       "Manufacturer Name", "Model Name",
       "Total Miles Driven"
  FROM (SELECT Assigned_Vehicle_id "Assigned Vehicle id",
               Payroll_Number "Payroll Number", First_Name "First Name",
               Surname, Vehicle_Registration "Vehicle Registration",
               Manufacturer_Name "Manufacturer Name", Model_Name "Model Name",
               SUM(End_Miles - Start_Miles) "Total Miles Driven"
          FROM Destinations
         WHERE YEAR(Start_Date) = 2016
         GROUP BY Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
               Vehicle_Registration, Manufacturer_Name, Model_Name
       ) AS Mileages_In_2016
 WHERE "Total Miles Driven" > 25000
</code>```

This runs your original query as 'sub-query' in the FROM clause, which allows you to write a filter in the outer query against the "Total Miles Driven" column in the outer query.

Title: SQL Query for Vehicle Mileage

Body:
I’m trying to design a fleet management database for my university course.

Currently my query searches the “view” that I have created and calculates employees total mileage based on year, by subtracting their journey's end miles from their start miles, which works and groups them in a result.
But what I can’t do, no matter how hard I try, is to then query what employees do more than 25,000 miles a year from the result that I have created. I not sure if this is even possible to query the result of an alias column?

SELECT Assigned_Vehicle_id "Assigned Vehicle id",
       Payroll_Number "Payroll Number", First_Name "First Name",
       Surname, Vehicle_Registration "Vehicle Registration",
       Manufacturer_Name "Manufacturer Name", Model_Name "Model Name",
       SUM(End_Miles - Start_Miles) "Total Miles Driven"
  FROM Destinations
 WHERE YEAR(Start_Date) = 2016
 GROUP BY Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
       Vehicle_Registration, Manufacturer_Name, Model_Name;

Body:
In some ways, a HAVING clause as suggested by Jason in his answer is good, simple, and quite probably what's expected — even though it involves writing out the expression twice rather than allowing you to use the alias.  Some DBMS do, I believe, allow you to use an output column alias in subsequent clauses such as the GROUP BY or HAVING clauses, but the standard does not, so most DBMS do not either.

However, there is another alternative which would probably work:

SELECT "Assigned Vehicle id",
       "Payroll Number", "First Name",
       Surname, "Vehicle Registration",
       "Manufacturer Name", "Model Name",
       "Total Miles Driven"
  FROM (SELECT Assigned_Vehicle_id "Assigned Vehicle id",
               Payroll_Number "Payroll Number", First_Name "First Name",
               Surname, Vehicle_Registration "Vehicle Registration",
               Manufacturer_Name "Manufacturer Name", Model_Name "Model Name",
               SUM(End_Miles - Start_Miles) "Total Miles Driven"
          FROM Destinations
         WHERE YEAR(Start_Date) = 2016
         GROUP BY Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
               Vehicle_Registration, Manufacturer_Name, Model_Name
       ) AS Mileages_In_2016
 WHERE "Total Miles Driven" > 25000

This runs your original query as 'sub-query' in the FROM clause, which allows you to write a filter in the outer query against the "Total Miles Driven" column in the outer query.


问:
Elasticsearch, Failed to obtain node lock, is the following location writable
Elasticsearch won't start using ./bin/elasticsearch.
It raises the following exception:

```<code>- ElasticsearchIllegalStateException[Failed to obtain node lock, is the following location writable?: [/home/user1/elasticsearch-1.4.4/data/elasticsearch]
</code>```

I checked the permissions on the same location and the location has 777 permissions on it and is owned by user1.

```<code>ls -al /home/user1/elasticsearch-1.4.4/data/elasticsearch
</code>```

```<code>drwxrwxrwx  3 user1 wheel 4096 Mar  8 13:24 .
drwxrwxrwx  3 user1 wheel 4096 Mar  8 13:00 ..
drwxrwxrwx 52 user1 wheel 4096 Mar  8 13:51 nodes
</code>```

What is the problem?

Trying to run elasticsearch 1.4.4 on linux without root access.

答:
the reason is another instance is running!

first find the id of running elastic.

```<code>ps aux | grep 'elastic'
</code>```

then kill using kill -9 <PID_OF_RUNNING_ELASTIC>.

There were some answers to remove node.lock file but that didn't help since the running instance will make it again!

Body:
Elasticsearch won't start using ./bin/elasticsearch.
It raises the following exception:

- ElasticsearchIllegalStateException[Failed to obtain node lock, is the following location writable?: [/home/user1/elasticsearch-1.4.4/data/elasticsearch]

I checked the permissions on the same location and the location has 777 permissions on it and is owned by user1.

ls -al /home/user1/elasticsearch-1.4.4/data/elasticsearch

drwxrwxrwx  3 user1 wheel 4096 Mar  8 13:24 .
drwxrwxrwx  3 user1 wheel 4096 Mar  8 13:00 ..
drwxrwxrwx 52 user1 wheel 4096 Mar  8 13:51 nodes

What is the problem?

Trying to run elasticsearch 1.4.4 on linux without root access.

Body:
the reason is another instance is running!

first find the id of running elastic.

ps aux | grep 'elastic'

then kill using kill -9 <PID_OF_RUNNING_ELASTIC>.

There were some answers to remove node.lock file but that didn't help since the running instance will make it again!


问:
Why I get an exception error on a database insert command?
```<code>public static string storeAvatar(string avatar, string gender, string species, int playerforeignkey )
{
    try
    {
        OleDbConnection myConnection = GetConnection();
        OleDbCommand dbCommand = new OleDbCommand();

        dbCommand.CommandText = "INSERT INTO AVATARS ([AVATAR_ID],[AVATAR],[DOB],[STRENGTH],[GENDER],[HOARD],[SPECIES], [METAMORPHOSED], [COST],[PLAYERID_FK]) values (?,?,?,?,?,?,?,?,?,?)"; // command to get high score data
        dbCommand.Parameters.AddWithValue("@id", "AVATARS_SEQ.NEXTVAL");
        dbCommand.Parameters.AddWithValue("@avatar", avatar);
        dbCommand.Parameters.AddWithValue("@date", "TO_CHAR(" + DateTime.Now.ToString("dd/mm/yyyy")+")");
        dbCommand.Parameters.AddWithValue("@strength", 0);
        dbCommand.Parameters.AddWithValue("@gender", gender);
        dbCommand.Parameters.AddWithValue("@hoard", 0);
        dbCommand.Parameters.AddWithValue("@species", species);
        dbCommand.Parameters.AddWithValue("@meta", 0);
        dbCommand.Parameters.AddWithValue("@cost", 0);
        dbCommand.Parameters.AddWithValue("@playerfk", playerforeignkey);
        dbCommand.Connection = myConnection;
        myConnection.Open();
        dbCommand.ExecuteNonQuery();
        myConnection.Close();
    }
    catch (Exception ex)
    {

    }
    return "ERROR";
}
</code>```

The exception error says I need miss a SELECT keyword, however I want INSERT not SELECT.

EXCEPTION =  "One or more errors occurred during processing of
  command.\r\nORA-00928: missing SELECT keyword"

答:
First, update the command text to use the actual parameter names and second the purpose of using the parameters is also to avoid SQL injection which you try to do with your parameters.

There is no need for the @id parameter as that value can be placed directly into the string as will as the TO_CHAR function.

```<code>//..other code removed for brevity
dbCommand.CommandText = "INSERT INTO AVATARS ([AVATAR_ID],[AVATAR],[DOB],[STRENGTH],[GENDER],[HOARD],[SPECIES], [METAMORPHOSED], [COST],[PLAYERID_FK]) VALUES (AVATARS_SEQ.NEXTVAL,@avatar,TO_CHAR(@date),@strength,@gender,@hoard,@species,@meta,@cost,@playerfk)";
dbCommand.Parameters.AddWithValue("@avatar", avatar);
dbCommand.Parameters.AddWithValue("@date", DateTime.Now.ToString("dd/mm/yyyy"));
dbCommand.Parameters.AddWithValue("@strength", 0);
dbCommand.Parameters.AddWithValue("@gender", gender);
dbCommand.Parameters.AddWithValue("@hoard", 0);
dbCommand.Parameters.AddWithValue("@species", species);
dbCommand.Parameters.AddWithValue("@meta", 0);
dbCommand.Parameters.AddWithValue("@cost", 0);
dbCommand.Parameters.AddWithValue("@playerfk", playerforeignkey);
//..other code removed for brevity
</code>```

In fact I would even advise that all the constant values be placed directly into the query and reduce the parameters to only the ones expected to change frequently.

for example

```<code>//..other code removed for brevity
dbCommand.CommandText = "INSERT INTO AVATARS ([AVATAR_ID],[AVATAR],[DOB],[STRENGTH],[GENDER],[HOARD],[SPECIES], [METAMORPHOSED], [COST],[PLAYERID_FK])
VALUES (AVATARS_SEQ.NEXTVAL,@avatar,TO_CHAR(@date),0,@gender,0,@species,0,0,@playerfk)";
dbCommand.Parameters.AddWithValue("@avatar", avatar);
dbCommand.Parameters.AddWithValue("@date", DateTime.Now.ToString("dd/mm/yyyy"));
dbCommand.Parameters.AddWithValue("@gender", gender);
dbCommand.Parameters.AddWithValue("@species", species);
dbCommand.Parameters.AddWithValue("@playerfk", playerforeignkey);
//..other code removed for brevity
</code>```

Body:
public static string storeAvatar(string avatar, string gender, string species, int playerforeignkey )
{
    try
    {
        OleDbConnection myConnection = GetConnection();
        OleDbCommand dbCommand = new OleDbCommand();

        dbCommand.CommandText = "INSERT INTO AVATARS ([AVATAR_ID],[AVATAR],[DOB],[STRENGTH],[GENDER],[HOARD],[SPECIES], [METAMORPHOSED], [COST],[PLAYERID_FK]) values (?,?,?,?,?,?,?,?,?,?)"; // command to get high score data
        dbCommand.Parameters.AddWithValue("@id", "AVATARS_SEQ.NEXTVAL");
        dbCommand.Parameters.AddWithValue("@avatar", avatar);
        dbCommand.Parameters.AddWithValue("@date", "TO_CHAR(" + DateTime.Now.ToString("dd/mm/yyyy")+")");
        dbCommand.Parameters.AddWithValue("@strength", 0);
        dbCommand.Parameters.AddWithValue("@gender", gender);
        dbCommand.Parameters.AddWithValue("@hoard", 0);
        dbCommand.Parameters.AddWithValue("@species", species);
        dbCommand.Parameters.AddWithValue("@meta", 0);
        dbCommand.Parameters.AddWithValue("@cost", 0);
        dbCommand.Parameters.AddWithValue("@playerfk", playerforeignkey);
        dbCommand.Connection = myConnection;
        myConnection.Open();
        dbCommand.ExecuteNonQuery();
        myConnection.Close();
    }
    catch (Exception ex)
    {

    }
    return "ERROR";
}

The exception error says I need miss a SELECT keyword, however I want INSERT not SELECT.

EXCEPTION =  "One or more errors occurred during processing of
  command.\r\nORA-00928: missing SELECT keyword"

Body:
First, update the command text to use the actual parameter names and second the purpose of using the parameters is also to avoid SQL injection which you try to do with your parameters.

There is no need for the @id parameter as that value can be placed directly into the string as will as the TO_CHAR function.

//..other code removed for brevity
dbCommand.CommandText = "INSERT INTO AVATARS ([AVATAR_ID],[AVATAR],[DOB],[STRENGTH],[GENDER],[HOARD],[SPECIES], [METAMORPHOSED], [COST],[PLAYERID_FK]) VALUES (AVATARS_SEQ.NEXTVAL,@avatar,TO_CHAR(@date),@strength,@gender,@hoard,@species,@meta,@cost,@playerfk)";
dbCommand.Parameters.AddWithValue("@avatar", avatar);
dbCommand.Parameters.AddWithValue("@date", DateTime.Now.ToString("dd/mm/yyyy"));
dbCommand.Parameters.AddWithValue("@strength", 0);
dbCommand.Parameters.AddWithValue("@gender", gender);
dbCommand.Parameters.AddWithValue("@hoard", 0);
dbCommand.Parameters.AddWithValue("@species", species);
dbCommand.Parameters.AddWithValue("@meta", 0);
dbCommand.Parameters.AddWithValue("@cost", 0);
dbCommand.Parameters.AddWithValue("@playerfk", playerforeignkey);
//..other code removed for brevity

In fact I would even advise that all the constant values be placed directly into the query and reduce the parameters to only the ones expected to change frequently.

for example

//..other code removed for brevity
dbCommand.CommandText = "INSERT INTO AVATARS ([AVATAR_ID],[AVATAR],[DOB],[STRENGTH],[GENDER],[HOARD],[SPECIES], [METAMORPHOSED], [COST],[PLAYERID_FK])
VALUES (AVATARS_SEQ.NEXTVAL,@avatar,TO_CHAR(@date),0,@gender,0,@species,0,0,@playerfk)";
dbCommand.Parameters.AddWithValue("@avatar", avatar);
dbCommand.Parameters.AddWithValue("@date", DateTime.Now.ToString("dd/mm/yyyy"));
dbCommand.Parameters.AddWithValue("@gender", gender);
dbCommand.Parameters.AddWithValue("@species", species);
dbCommand.Parameters.AddWithValue("@playerfk", playerforeignkey);
//..other code removed for brevity


问:
Count the length of a number
Hello I would like to count the number there is in a number I mean if I have this double 78.23 the functions would return 4 if I have 145.123 I would got 6. Is it possible to do this with C++ ?
Thank you !</p>

答:
the easy way of doing this is to just enter the number as a string and use .length()

```<code>#include <iostream>
#include <string>
#include <conio.h>
using namespace std; int main() {

string number;

cout << "Enter a number: ";
cin >> number;

cout << "length is " << number.length();

_getch();
return 0;
</code>```

if you need it strictly to be with integers and doubles then you'll have to create a mathematical algorithm.

Title: Count the length of a number

Body:
the easy way of doing this is to just enter the number as a string and use .length()

#include <iostream>
#include <string>
#include <conio.h>
using namespace std; int main() {

string number;

cout << "Enter a number: ";
cin >> number;

cout << "length is " << number.length();

_getch();
return 0;

if you need it strictly to be with integers and doubles then you'll have to create a mathematical algorithm.


问:
React.js - Render Components with Different Styles based on props
So let's say I am creating a simple web layout, where I have a feedback message component above the MainContent component, as so:

```<code>class WebLayout extends Component {
  render() {
    <div>
      <Header />
      <FeedBackMessage
        shouldRenderMessage={true}
        typeMessage={"error"}
        message={"Wrong input!"}
      />
      <MainContent />
    </div>
  }
}
</code>```

And let's assume that I have different types of messages such as error, warning, success.

Inside the FeedBackMessage, I may have something as so:

```<code>class FeedBackMessage extends Component {
  renderMessage(){
    const {shouldRenderMessage, typeMessage, message } = this.props;
    if (shouldRenderMessage === true){
      <div>
        {message}
      </div>
    }
  }
  render(){
    return (
      <div>
        {this.renderMessage().bind(this)}
      </div>
    )
  }
}
</code>```

I am stumped on how I can render FeedBackMessage styling based on typeMessage prop value.

For instance, if I pass typeMessage with 'error', I like to have the FeedbackMessage component with a red border styling. Or if I pass confirm, I'd like to render with green border.

答:
This all is very dependent on your styling solution.

If you want to use inline styles it might look something like this:

```<code>class FeedBackMessage extends Component {
  renderMessage(){
    const {shouldRenderMessage, typeMessage, message } = this.props;
    if (shouldRenderMessage === true){
      <div>
        {message}
      </div>
    }
  }
  render(){
    const componentStyle = {
      error: { border: "1px solid red" },
      confirm: { border: "1px solid green" }
    }[this.props.typeMessage];

    return (
      <div style={componentStyle}>
        {this.renderMessage().bind(this)}
      </div>
    )
  }
}
</code>```

If you want to style with stylesheets, you can use something like classnames to toggle classes based on some logic and then add the class your component.

```<code>class FeedBackMessage extends Component {
  renderMessage(){
    const {shouldRenderMessage, typeMessage, message } = this.props;
    if (shouldRenderMessage === true){
      <div>
        {message}
      </div>
    }
  }
  render(){
    const componentClass = classNames('FeedBackMessage', {
      "error": this.props.typeName === 'error',
      "confirm": this.props.typeName === 'confirm'
    });

    return (
      <div className={componentClass}>
        {this.renderMessage().bind(this)}
      </div>
    )
  }
}
</code>```

And have a stylesheet like so:

```<code>.FeedBackMessage .error {
  border: 1px solid red;
}

.FeedbackMessage .confirm {
  border: 1px solid green;
}
</code>```

Body:
So let's say I am creating a simple web layout, where I have a feedback message component above the MainContent component, as so:

class WebLayout extends Component {
  render() {

      <FeedBackMessage
        shouldRenderMessage={true}
        typeMessage={"error"}
        message={"Wrong input!"}
      />
      <MainContent />

  }
}

And let's assume that I have different types of messages such as error, warning, success.

Inside the FeedBackMessage, I may have something as so:

class FeedBackMessage extends Component {
  renderMessage(){
    const {shouldRenderMessage, typeMessage, message } = this.props;
    if (shouldRenderMessage === true){

        {message}

    }
  }
  render(){
    return (

        {this.renderMessage().bind(this)}

    )
  }
}

I am stumped on how I can render FeedBackMessage styling based on typeMessage prop value.

For instance, if I pass typeMessage with 'error', I like to have the FeedbackMessage component with a red border styling. Or if I pass confirm, I'd like to render with green border.

Body:
This all is very dependent on your styling solution.

If you want to use inline styles it might look something like this:

class FeedBackMessage extends Component {
  renderMessage(){
    const {shouldRenderMessage, typeMessage, message } = this.props;
    if (shouldRenderMessage === true){
      <div>
        {message}
      </div>
    }
  }
  render(){
    const componentStyle = {
      error: { border: "1px solid red" },
      confirm: { border: "1px solid green" }
    }[this.props.typeMessage];

    return (
      <div style={componentStyle}>
        {this.renderMessage().bind(this)}
      </div>
    )
  }
}

If you want to style with stylesheets, you can use something like classnames to toggle classes based on some logic and then add the class your component.

class FeedBackMessage extends Component {
  renderMessage(){
    const {shouldRenderMessage, typeMessage, message } = this.props;
    if (shouldRenderMessage === true){
      <div>
        {message}
      </div>
    }
  }
  render(){
    const componentClass = classNames('FeedBackMessage', {
      "error": this.props.typeName === 'error',
      "confirm": this.props.typeName === 'confirm'
    });

    return (
      <div className={componentClass}>
        {this.renderMessage().bind(this)}
      </div>
    )
  }
}

And have a stylesheet like so:

.FeedBackMessage .error {
  border: 1px solid red;
}

.FeedbackMessage .confirm {
  border: 1px solid green;
}


问:
Ionic livereload error
I am getting this error in my console.

```<code>No response for http://localhost:35729/livereload.js?snipver=1 found in cache. About to fetch from network...
</code>```

When I make a change to my app, the app reloads and builds but I do not see the changes in the browser.

Also, when I try ionic serve on another app, it reloads my current app.

When I go to http://localhost:8100/ my app is there even if I don't use ionic serve.

I have done npm cache clean
removed ionic from computer and re-added.

But still get that error.

Ionic info:

```<code>cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.18
Ionic App Lib Version: 2.1.9
Ionic App Scripts Version: 0.0.48
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v4.6.0
Xcode version: Not installed
</code>```

答:
It happened to me now and I solved it by opening the page with my local ip address instead of localhost.

If you are running on Windows you can open the CMD and type ipconfig. This will retrieve your local ip address. Your ip address should be at Adaptador Ethernet Ethernet -> IPv4 Address .

For example, if your ip is 10.1.1.15 you should open http://10.1.1.15:8100/ in your browser so that you can use live reload.

Title: Ionic livereload error

Body:
I am getting this error in my console.

No response for http://localhost:35729/livereload.js?snipver=1 found in cache. About to fetch from network...

When I make a change to my app, the app reloads and builds but I do not see the changes in the browser.

Also, when I try ionic serve on another app, it reloads my current app.

When I go to http://localhost:8100/ my app is there even if I don't use ionic serve.

I have done npm cache clean
removed ionic from computer and re-added.

But still get that error.

Ionic info:

cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.18
Ionic App Lib Version: 2.1.9
Ionic App Scripts Version: 0.0.48
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v4.6.0
Xcode version: Not installed


问:
Are there no built in C# GUI Layouts?
I'm used to the GUI frameworks in Java as well as the QT GUI framework, and I'm used to the various layout managers. It doesn't seem that C# has any layout managers built in, or am I missing something?

2 Year Later Edit

I just want to point out to any readers of this question that in hind-sight, my question was misplaced. With proper anchoring and docking of child controls, having a need for the layout managers of Java and QT4 is nearly non-existent.

答:
No, you  are not missing anything.

.NET does not have built in layout managers for Winforms/Webforms/Console development.

Probably because Visual Studio has good designers, obviating the need.

WPF and Silverlight (both using XAML) do have them, though they are not exactly the same as the Java ones.

Title: Are there no built in C# GUI Layouts?


问:
C++ -& CRTP . Type erasure vs polymorphism
OK here we go. I'm trying to use the CRTP template in order to remove the need of polymorphism from my app. I use an aproach like the one bellow

```<code>template <RealType> class Base
{

    void doSomething()
    {
         static_cast<RealType>(this)->doSomethingImpl()
    }

class Derived1 : public Base
{
    void doSomethingImpl()
    {
        /* do something, for real */
    }
}

class Derived2 : public Base
{
    void doSomethingImpl()
    {
        /* do something else */
    }
}
</code>```

This aproach, if I understood correctly, allows my classes to have no vtable, so function calls are direct and don't require the extra indirection.

Now imagine I want to store all my Derived# classes in a container. Let's say a vector.

First approach : I can create a non-template SuperBase class from which Base inherits and store that in the container.

However it seems to me that if I want to do that, I will have to make doSomething virtual, in SuperBase. And my goal is mainly not to have a vtable.

Second approach : I use type erasure, i.e. something like boost::any to store my elements in the Vector.
But then, I don't see a way I can iterate over the elements and call doSomething on them, because to "use" boost::any, I need to know the real type of the object when iterating.

Do you think what I want to do is even possible ?

Seems to me that it is because doSomething() is part of Base  but except using inheritance, I can't see a way to do it ....

答:
It's going to be difficult (a hack at best) to hold these objects in a container.  You have designed away polymorphism, and yet you seem to really want to use it so you can hold the objects as container<mybaseclass> and use them polymorphically.

It's not clear to me from your posting why you wish to avoid the vtable.  If this is for performance, you are probably over-optimizing.  Without more background on why you are going this route, it's hard to recommend anything but 'use a base class'.

Body:
OK here we go. I'm trying to use the CRTP template in order to remove the need of polymorphism from my app. I use an aproach like the one bellow

template <RealType> class Base
{

    void doSomething()
    {
         static_cast<RealType>(this)->doSomethingImpl()
    }

class Derived1 : public Base
{
    void doSomethingImpl()
    {
        /* do something, for real */
    }
}

class Derived2 : public Base
{
    void doSomethingImpl()
    {
        /* do something else */
    }
}

This aproach, if I understood correctly, allows my classes to have no vtable, so function calls are direct and don't require the extra indirection.

Now imagine I want to store all my Derived# classes in a container. Let's say a vector.

First approach : I can create a non-template SuperBase class from which Base inherits and store that in the container.

However it seems to me that if I want to do that, I will have to make doSomething virtual, in SuperBase. And my goal is mainly not to have a vtable.

Second approach : I use type erasure, i.e. something like boost::any to store my elements in the Vector.
But then, I don't see a way I can iterate over the elements and call doSomething on them, because to "use" boost::any, I need to know the real type of the object when iterating.

Do you think what I want to do is even possible ?

Seems to me that it is because doSomething() is part of Base  but except using inheritance, I can't see a way to do it ....


问:
C++ not showing cout in Xcode console but runs perfectly in Terminal
Basically i am running a simple program in Xcode Version 8.3 (8E162)

```<code>#include <iostream>
using namespace std;
int main() {
    int a;
    cout << "What is your age: ";
    cin >> a;
    cout << "My age is " << a << endl;
    return 0;
}
</code>```

I have seen different questions about cout need to be flushed and all std::cout won't print and Xcode debugger not showing C++ cout output. The Xcode debugger does not print cout until i put \n or endl. But, it works perfectly fine on terminal.

What if i had to use What is your age: and the user input age in the single line rather than the next line putting \n and endl?

This is what the Xcode debugger shows after build and run

This is when user inputs and it displays the result

This is on the terminal and this is what exactly what i need the output on the Xcode debugger.

答:
By doing some research, there seems to be bug on cin and cout stream on Xcode Version 8.3 Build 8E162 released on Mar 27, 2017.
Degrading to Xcode Version 8.2.1 works like a charm.

Body:
Basically i am running a simple program in Xcode Version 8.3 (8E162)

#include <iostream>
using namespace std;
int main() {
    int a;
    cout << "What is your age: ";
    cin >> a;
    cout << "My age is " << a << endl;
    return 0;
}

I have seen different questions about cout need to be flushed and all std::cout won't print and Xcode debugger not showing C++ cout output. The Xcode debugger does not print cout until i put \n or endl. But, it works perfectly fine on terminal.

What if i had to use What is your age: and the user input age in the single line rather than the next line putting \n and endl?

This is what the Xcode debugger shows after build and run

This is when user inputs and it displays the result

This is on the terminal and this is what exactly what i need the output on the Xcode debugger.


问:
Does anyone know how to return a grid into the shell based on a txt file?
Iam trying to make a small interior designing app, I type a txt file and make my program return the grid on shell.
I just need to know how to make a grid where the height and width are both 20.

These are the codes I have so far.. I only know how to make the width but not the height. I also don't know how to get the numbers and letters from my txt file but i made my txt file into a list line by line.

```<code>f = open('Apt_3_4554_Hastings_Coq.txt','r')
bigListA = [ line.strip().split(',') for line in f ]

offset = "   "
width = 20
string1 = offset
for number in range(width):
    if len(str(number)) == 1:
        string1 += " " + str(number) + " "
    else:
        string1 += str(number) + " "
print (string1)
</code>```

答:
You can represent the room as a 20x20 grid. One idea is a list of lists; personally I prefer a dict.

Read through the file and assign each point. (I assume you've handled parsing the file, since that wasn't the issue you posted.) For instance:

```<code>room[5, 13] = 'C'
</code>```

Then you can iterate over the coordinates to provide your output.

```<code>for i in range(N_ROWS):
    for j in range(N_COLS):
        # Print the character if it exists, or a blank space.
        print(room.get((i, j), default=' '), end='')
    print()  # Start a new line.
</code>```

Body:
Iam trying to make a small interior designing app, I type a txt file and make my program return the grid on shell.
I just need to know how to make a grid where the height and width are both 20.

These are the codes I have so far.. I only know how to make the width but not the height. I also don't know how to get the numbers and letters from my txt file but i made my txt file into a list line by line.

f = open('Apt_3_4554_Hastings_Coq.txt','r')
bigListA = [ line.strip().split(',') for line in f ]

offset = "   "
width = 20
string1 = offset
for number in range(width):
    if len(str(number)) == 1:
        string1 += " " + str(number) + " "
    else:
        string1 += str(number) + " "
print (string1)

Body:
You can represent the room as a 20x20 grid. One idea is a list of lists; personally I prefer a dict.

Read through the file and assign each point. (I assume you've handled parsing the file, since that wasn't the issue you posted.) For instance:

room[5, 13] = 'C'

Then you can iterate over the coordinates to provide your output.

for i in range(N_ROWS):
    for j in range(N_COLS):
        # Print the character if it exists, or a blank space.
        print(room.get((i, j), default=' '), end='')
    print()  # Start a new line.


问:
C# Instantiated object is null
I am trying to write a game of life program in a console app but keeping the runtime exception that my instantiated cell object is null.

I am looping through a 2d array and creating the objects then I am visualizing them if they are alive. I keep getting an error when I try access the position

(Console.WriteLine(cell.Isalive.ToString());)

It always happens when I try access my objects properties even through they have values

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

namespace Game_of_life
{
class Program
{

    static Random rnd = new Random();

    static void Main(string[] args)
    {

        Console.SetWindowSize(40, 40);

      Cell[,] Points = new Cell[Console.WindowHeight, Console.WindowWidth];
      for(int i = 0; i < Console.WindowHeight; i++)
        {
            for(int j = 0; j < Console.WindowWidth; j++)
            {
                bool Alive = false;
                if (rnd.Next(0, 10) == 1)
                    Alive = true;
                Cell cell = new Cell(i, j, Alive);
            }

        }

        while (true)
        {
            Console.Clear();
            foreach(Cell cell in Points)
            {
                Console.WriteLine(cell.Isalive.ToString());
                Tuple<int, int>[] points = GetNeighbors(new Point(cell.Position.X, cell.Position.Y));

                for(int i = 0; i < 4; i++){
                    if (points[0] != null)
                        cell.Neighbors[i].Position = new Point(points[i].Item1, points[i].Item2);
                }

                if(cell.Isalive == true)
                {
                    Console.SetCursorPosition(cell.Position.X, cell.Position.Y);
                    Console.Write("X");
                }
                System.Threading.Thread.Sleep(500);
            }
        }

    }

    static Tuple<int, int>[] GetNeighbors(Point pos)
    {
        Tuple<int, int>[] points = new Tuple<int, int>[4];
        if (pos.X - 1 > 0) {
            points[0] = Tuple.Create(pos.X - 1, pos.Y);
                }
        else
        {
            points[0] = null;
        }
        if(pos.X + 1< Console.WindowWidth)
        {
            points[1] = Tuple.Create(pos.X + 1, pos.Y);
        }

        if(pos.Y - 1 > 0)
        {
            points[2] = Tuple.Create(pos.X, pos.Y - 1);
        }
        else
        {
            points[0] = null;
        }

        if (pos.Y + 1 < Console.WindowHeight)
        {
            points[3] = Tuple.Create(pos.X, pos.Y + 1);
        }
        else
        {
            points[0] = null;
        }

        return points;
    }
}
</code>```

}

Here is the code for my class:

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

    namespace Game_of_life
    {
       class Cell
        {
           //Defines if the cell is currently alive
            private bool isAlive;
            public bool Isalive { get; set; }

    //Neighbors of the cell
    private Cell[] neighnors = new Cell[4];
    public Cell[] Neighbors { get; set; }

    private Point position;
    public Point Position
        {
        get
        {
            return position;
        }
        set
        {
            position = value;
        }
        }

    private int neighborCount;
    public int NeighborCount { get; set; }

    public Cell (int x , int y, bool Alive)
    {
        this.position = new Point(x, y);
        isAlive = Alive;
    }

}
    }
</code>```

答:
You're creating Cell objects for every x,y coordinate pair across the window but you aren't ever setting those cell objects in your Point array.

```<code>Cell[,] Points = new Cell[Console.WindowHeight, Console.WindowWidth];
    for(int i = 0; i < Console.WindowHeight; i++)
    {
        for(int j = 0; j < Console.WindowWidth; j++)
        {
            bool Alive = false;
            if (rnd.Next(0, 10) == 1)
                Alive = true;
            Cell cell = new Cell(i, j, Alive);
            Points[i, j] = cell; //this is missing
        }
    }
</code>```

Something like that should help.

Title: C# Instantiated object is null

Body:
I am trying to write a game of life program in a console app but keeping the runtime exception that my instantiated cell object is null.

I am looping through a 2d array and creating the objects then I am visualizing them if they are alive. I keep getting an error when I try access the position

(Console.WriteLine(cell.Isalive.ToString());)

It always happens when I try access my objects properties even through they have values

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
using System.Diagnostics;

namespace Game_of_life
{
class Program
{

    static Random rnd = new Random();

    static void Main(string[] args)
    {

        Console.SetWindowSize(40, 40);

      Cell[,] Points = new Cell[Console.WindowHeight, Console.WindowWidth];
      for(int i = 0; i < Console.WindowHeight; i++)
        {
            for(int j = 0; j < Console.WindowWidth; j++)
            {
                bool Alive = false;
                if (rnd.Next(0, 10) == 1)
                    Alive = true;
                Cell cell = new Cell(i, j, Alive);
            }

        }

        while (true)
        {
            Console.Clear();
            foreach(Cell cell in Points)
            {
                Console.WriteLine(cell.Isalive.ToString());
                Tuple<int, int>[] points = GetNeighbors(new Point(cell.Position.X, cell.Position.Y));

                for(int i = 0; i < 4; i++){
                    if (points[0] != null)
                        cell.Neighbors[i].Position = new Point(points[i].Item1, points[i].Item2);
                }

                if(cell.Isalive == true)
                {
                    Console.SetCursorPosition(cell.Position.X, cell.Position.Y);
                    Console.Write("X");
                }
                System.Threading.Thread.Sleep(500);
            }
        }

    }

    static Tuple<int, int>[] GetNeighbors(Point pos)
    {
        Tuple<int, int>[] points = new Tuple<int, int>[4];
        if (pos.X - 1 > 0) {
            points[0] = Tuple.Create(pos.X - 1, pos.Y);
                }
        else
        {
            points[0] = null;
        }
        if(pos.X + 1< Console.WindowWidth)
        {
            points[1] = Tuple.Create(pos.X + 1, pos.Y);
        }

        if(pos.Y - 1 > 0)
        {
            points[2] = Tuple.Create(pos.X, pos.Y - 1);
        }
        else
        {
            points[0] = null;
        }

        if (pos.Y + 1 < Console.WindowHeight)
        {
            points[3] = Tuple.Create(pos.X, pos.Y + 1);
        }
        else
        {
            points[0] = null;
        }

        return points;
    }
}

}

Here is the code for my class:

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

    namespace Game_of_life
    {
       class Cell
        {
           //Defines if the cell is currently alive
            private bool isAlive;
            public bool Isalive { get; set; }

    //Neighbors of the cell
    private Cell[] neighnors = new Cell[4];
    public Cell[] Neighbors { get; set; }

    private Point position;
    public Point Position
        {
        get
        {
            return position;
        }
        set
        {
            position = value;
        }
        }

    private int neighborCount;
    public int NeighborCount { get; set; }

    public Cell (int x , int y, bool Alive)
    {
        this.position = new Point(x, y);
        isAlive = Alive;
    }

}
    }

Body:
You're creating Cell objects for every x,y coordinate pair across the window but you aren't ever setting those cell objects in your Point array.

Cell[,] Points = new Cell[Console.WindowHeight, Console.WindowWidth];
    for(int i = 0; i < Console.WindowHeight; i++)
    {
        for(int j = 0; j < Console.WindowWidth; j++)
        {
            bool Alive = false;
            if (rnd.Next(0, 10) == 1)
                Alive = true;
            Cell cell = new Cell(i, j, Alive);
            Points[i, j] = cell; //this is missing
        }
    }

Something like that should help.


问:
if an a link contain something in the href change the href to this
i want to check if the href contains 'coming-soon' if it does change the href to go to my products page:

```<code>$('a[href$="coming-soon"]').attr('href', '/products.aspx');
</code>```

cant work this out.

答: $= means "ends with".  You want to find links that contain (anywhere in the URL) coming-soon? Try *= instead of $=.

Body:
i want to check if the href contains 'coming-soon' if it does change the href to go to my products page:

$('a[href$="coming-soon"]').attr('href', '/products.aspx');

cant work this out.


问:
What is the difference between these three ways to initialise static variables?
Those 2 syntaxes work. What is the difference between them?

```<code>class MyClass
{
  const static int myInt1_ {20};
  const static int myInt2_ = 20;
}
</code>```

Also, why is it not possible to do const static int myInt3_ (20)?

答:
The differences between brace and equals initialization for various classes can be involved, so I'm going to restrict to answering for integers. For integers there is basically one difference: narrowing conversions. This compiles:

```<code>const static int x = 3.0;
</code>```

This does not.

```<code>const static int x{3.0};
</code>```

Body:
Those 2 syntaxes work. What is the difference between them?

class MyClass
{
  const static int myInt1_ {20};
  const static int myInt2_ = 20;
}

Also, why is it not possible to do const static int myInt3_ (20)?

Body:
The differences between brace and equals initialization for various classes can be involved, so I'm going to restrict to answering for integers. For integers there is basically one difference: narrowing conversions. This compiles:

const static int x = 3.0;

This does not.

const static int x{3.0};


问:
remove extraneous characters from a filename
I have been tasked a little above my head with taking a repository of files and removing excess garbage characters from the filename and saving the renamed file in a different directory folder.

An example of the filenames are:

```
100-expresstoll.pdf
1000-2012-09-29.jpg
10000-2014-01-15_14.03.22.jpg
10001-2014-01-15_19.05.24.jpg
10002-2014-01-15_21.30.23.jpg
10003-2014-01-16_07.33.54.jpg
10004-2014-01-16_13.33.21.jpg
10005-Feb 4, 2014.jpeg
10006-O'Reilly_Media,_Inc..pdf
```

First group of numbers at the beginning are record IDs and are to be retained along with the file's extension. Everything else between the record IDs and the file extension needs to be dropped.

For example, the final name for first three files would be:

```
100.pdf
1000.jpg
10000.jpg
```

I have read Removing characters and Rearranging filenames in addition to other postings, but the complexity of having a variable character length at the front, a variable number of intermediary characters to be removed and variable file extension types have really tossed this beyond my limited PowerShell reach.

答:
You can use the -replace operator to do this kind of string manipulation:

```<code>Get-ChildItem | foreach {

    $old_name = $_.FullName
    $new_name = $_.Name -replace '([0-9]+).*(\.[^.]*)$', '$1$2'

    Rename-Item $old_name $new_name
}
</code>```

The regular expression is the trick here:

([0-9]+) means match a series of digits (1 or more digits)

.* means match anything

(\.[^.]*) means match a period followed by any characters other than a period

$ means that the match must reach the end of the string

The first and third are special in that they are surrounded by parentheses which means that you can use those values using the dollar notation (e.g. $1) in the replacement string.

Body:
I have been tasked a little above my head with taking a repository of files and removing excess garbage characters from the filename and saving the renamed file in a different directory folder.

An example of the filenames are:

100-expresstoll.pdf
1000-2012-09-29.jpg
10000-2014-01-15_14.03.22.jpg
10001-2014-01-15_19.05.24.jpg
10002-2014-01-15_21.30.23.jpg
10003-2014-01-16_07.33.54.jpg
10004-2014-01-16_13.33.21.jpg
10005-Feb 4, 2014.jpeg
10006-O'Reilly_Media,_Inc..pdf

First group of numbers at the beginning are record IDs and are to be retained along with the file's extension. Everything else between the record IDs and the file extension needs to be dropped.

For example, the final name for first three files would be:

100.pdf
1000.jpg
10000.jpg

I have read Removing characters and Rearranging filenames in addition to other postings, but the complexity of having a variable character length at the front, a variable number of intermediary characters to be removed and variable file extension types have really tossed this beyond my limited PowerShell reach.

Body:
You can use the -replace operator to do this kind of string manipulation:

Get-ChildItem | foreach {

    $old_name = $_.FullName
    $new_name = $_.Name -replace '([0-9]+).*(\.[^.]*)$', '$1$2'

    Rename-Item $old_name $new_name
}

The regular expression is the trick here:

([0-9]+) means match a series of digits (1 or more digits)

.* means match anything

(\.[^.]*) means match a period followed by any characters other than a period

$ means that the match must reach the end of the string

The first and third are special in that they are surrounded by parentheses which means that you can use those values using the dollar notation (e.g. $1) in the replacement string.


问:
SparkR, split a column of nested JSON strings into columns
I am coming from R, new to SparkR, and trying to split a SparkDataFrame column of JSON strings into respective columns. The columns in the Spark DataFrame are arrays with a schema like this:

```<code>> printSchema(tst)
root
 |-- FromStation: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- ToStation: array (nullable = true)
 |    |-- element: string (containsNull = true)
</code>```

If I look at the data in the viewer, View(head(tst$FromStation)) I can see the SparkDataFrame's FromStation column has a form like this in each row:

```<code>list("{\"Code\":\"ABCDE\",\"Name\":\"StationA\"}", "{\"Code\":\"WXYZP\",\"Name\":\"StationB\"}", "{...
</code>```

Where the ... indicates the pattern repeats an unknown amount of times.

My Question

How do I extract this information and put it in a flat dataframe? Ideally, I would like to make a FromStationCode and FromStationName column for each observation in the nested array column. I have tried various combinations of explode and getItem...but to no avail. I keep getting a data type mismatch error. I've searched through examples of other people with this challenge in Spark, but SparkR examples are more scarce. I'm hoping someone with more experience using Spark/SparkR could provide some insight.

Many thanks,
nate

答:
I guess you need to convert tst into usual R object

```<code>df = collect(tst)
</code>```

Then you operate with df like with any other R data.frame

Body:
I am coming from R, new to SparkR, and trying to split a SparkDataFrame column of JSON strings into respective columns. The columns in the Spark DataFrame are arrays with a schema like this:

> printSchema(tst)
root
 |-- FromStation: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- ToStation: array (nullable = true)
 |    |-- element: string (containsNull = true)

If I look at the data in the viewer, View(head(tst$FromStation)) I can see the SparkDataFrame's FromStation column has a form like this in each row:

list("{\"Code\":\"ABCDE\",\"Name\":\"StationA\"}", "{\"Code\":\"WXYZP\",\"Name\":\"StationB\"}", "{...

Where the ... indicates the pattern repeats an unknown amount of times.

My Question

How do I extract this information and put it in a flat dataframe? Ideally, I would like to make a FromStationCode and FromStationName column for each observation in the nested array column. I have tried various combinations of explode and getItem...but to no avail. I keep getting a data type mismatch error. I've searched through examples of other people with this challenge in Spark, but SparkR examples are more scarce. I'm hoping someone with more experience using Spark/SparkR could provide some insight.

Many thanks,
nate

Body:
I guess you need to convert tst into usual R object

df = collect(tst)

Then you operate with df like with any other R data.frame


问:
How do I create a button in javascript that appears next to output? I am including more specification inside
In my html file I have a div tag to add output from an external Javascript file which looks like this.

```<code><div id="section" class="format" align="left"></div>
</code>```

The output is passed to the div with this code.

```<code>document.getElementById("section").innerHTML = output;
</code>```

Now, the next piece of code is output that is passed to the code previous to this to be displayed on the webpage. What I want is to add a button that is displayed, on the right, next to the location output in the html file and the code looks like this.

```<code>output+="Location: ";
output+=x[i].getElementsByTagName("location")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+="Well Depth: ";
output+=x[i].getElementsByTagName("welldepth")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+="Perf Depth: ";
output+=x[i].getElementsByTagName("perfdepth")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+="Perf Zone: ";
output+=x[i].getElementsByTagName("perfzone")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+="Stroke: ";
output+=x[i].getElementsByTagName("stroke")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+="Stroke/min: ";
output+=x[i].getElementsByTagName("strokepermin")[0].childNodes[0].nodeValue;
</code>```

I've tried many different solutions on google and the most notable example is as follows.

```<code>var button = document.createElement("button");
button.innerHTML = "Do Something";

var body = document.getElementsByTagName("body")[0];
body.appendChild(button);

button.addEventListener ("click", function() {
alert("did something");
});
</code>```

I think it's close but I want the button next to the location output and not after the output as shown in this image.

The thing is though the output is based on a search and the code assigning output to this line,

```<code>document.getElementById("section").innerHTML = output;
</code>```

is in a loop because multiple results can come from the search.

Output shown here

I am not sure how I would make a button next to the location output.

Thank you very much!

答:
It's not clear what you're trying to do. Since you are assigning the value of output to the innerHTML property of a div, you could just include the markup for a button in the value, e.g.

```<code>output+=x[i].getElementsByTagName("location")[0].childNodes[0].nodeValue +
        " <button>Do something</button>";
</code>```

But this seems to be tabular data, so perhaps better to create a table using a helper function that takes the title and text for each row then appends a button, e.g.

function fillTable(id, data) {
  var table = document.getElementById(id);
  if (!table) return;
  var tbody = table.tBodies[0];
  Object.keys(data).forEach(function(key) {
    tbody.appendChild(makeRow(key, data[key]));
  });
}

function makeRow(title, text) {
  var row = document.createElement('tr');
  var titleCell = row.appendChild(document.createElement('th'));
  titleCell.appendChild(document.createTextNode(title));
  var textCell = row.appendChild(document.createElement('td'));
  textCell.appendChild(document.createTextNode(text));
  var buttonCell = row.appendChild(document.createElement('td'));
  var button = buttonCell.appendChild(document.createElement('button'));
  button.appendChild(document.createTextNode('Do Something'));
  button.onclick = function() {
    console.log('Did something');
  };
  return row;
}

var data = {
  'Location': 'loc0',
  'Well Depth': '23 m'
};

window.onload = function() {
  fillTable('results', data);
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  border-collapse: collapse;
  border-top: 1px solid #999999;
  border-left: 1px solid #999999;
}
th {
  text-align: left;
}
th, td {
  border-right: 1px solid #999999;
  border-bottom: 1px solid #999999;
  padding-right: 10px;
  padding-left: 5px;
}</code>```

```

If you have many sets of data, you might want to run the headers across the top.

Body:
In my html file I have a div tag to add output from an external Javascript file which looks like this.

The output is passed to the div with this code.

document.getElementById("section").innerHTML = output;

Now, the next piece of code is output that is passed to the code previous to this to be displayed on the webpage. What I want is to add a button that is displayed, on the right, next to the location output in the html file and the code looks like this.

output+="Location: ";
output+=x[i].getElementsByTagName("location")[0].childNodes[0].nodeValue + " ";
output+="
";
output+="Well Depth: ";
output+=x[i].getElementsByTagName("welldepth")[0].childNodes[0].nodeValue + " ";
output+="
";
output+="Perf Depth: ";
output+=x[i].getElementsByTagName("perfdepth")[0].childNodes[0].nodeValue + " ";
output+="
";
output+="Perf Zone: ";
output+=x[i].getElementsByTagName("perfzone")[0].childNodes[0].nodeValue + " ";
output+="
";
output+="Stroke: ";
output+=x[i].getElementsByTagName("stroke")[0].childNodes[0].nodeValue + " ";
output+="
";
output+="Stroke/min: ";
output+=x[i].getElementsByTagName("strokepermin")[0].childNodes[0].nodeValue;

I've tried many different solutions on google and the most notable example is as follows.

var button = document.createElement("button");
button.innerHTML = "Do Something";

var body = document.getElementsByTagName("body")[0];
body.appendChild(button);

button.addEventListener ("click", function() {
alert("did something");
});

I think it's close but I want the button next to the location output and not after the output as shown in this image.

The thing is though the output is based on a search and the code assigning output to this line,

document.getElementById("section").innerHTML = output;

is in a loop because multiple results can come from the search.

Output shown here

I am not sure how I would make a button next to the location output.

Thank you very much!

Body:
It's not clear what you're trying to do. Since you are assigning the value of output to the innerHTML property of a div, you could just include the markup for a button in the value, e.g.

output+=x[i].getElementsByTagName("location")[0].childNodes[0].nodeValue +
        " <button>Do something</button>";

But this seems to be tabular data, so perhaps better to create a table using a helper function that takes the title and text for each row then appends a button, e.g.

function fillTable(id, data) {
  var table = document.getElementById(id);
  if (!table) return;
  var tbody = table.tBodies[0];
  Object.keys(data).forEach(function(key) {
    tbody.appendChild(makeRow(key, data[key]));
  });
}

function makeRow(title, text) {
  var row = document.createElement('tr');
  var titleCell = row.appendChild(document.createElement('th'));
  titleCell.appendChild(document.createTextNode(title));
  var textCell = row.appendChild(document.createElement('td'));
  textCell.appendChild(document.createTextNode(text));
  var buttonCell = row.appendChild(document.createElement('td'));
  var button = buttonCell.appendChild(document.createElement('button'));
  button.appendChild(document.createTextNode('Do Something'));
  button.onclick = function() {
    console.log('Did something');
  };
  return row;
}

var data = {
  'Location': 'loc0',
  'Well Depth': '23 m'
};

window.onload = function() {
  fillTable('results', data);
};

table {
  border-collapse: collapse;
  border-top: 1px solid #999999;
  border-left: 1px solid #999999;
}
th {
  text-align: left;
}
th, td {
  border-right: 1px solid #999999;
  border-bottom: 1px solid #999999;
  padding-right: 10px;
  padding-left: 5px;
}

<table id="results"><tbody></tbody></table>

If you have many sets of data, you might want to run the headers across the top.


问:
How to find specific words from all text files in a directory using python
I have text file. i want to open that text file and search one word called "OPR" if that
word occured in the Final.txt file write 3 line of that particular string example code
given below

```<code>text1="Some decoders allow you to manipulate the image reading"
text2="file.This can often be used to speed up decoding when creating"
text3="when speed is usually more important than quality  printing"
text4="monochrome laser printer when only a greyscale"
text4="Note that the resulting image may not exactly match the requested"
text5="mode and size. To make sure that the image is not larger"
text6="given size, use the thumbnail method instead."

output_file=open("Final.txt","a")
output_file.write(text1)
output_file.write(text2)
output_file.write(text3)
output_file.write(text4)
output_file.write(text5)
output_file.write(text6)
output_file.close()

import collections
import itertools
import sys
with open('output\\Final.txt') as f:
  for line in f:
    if 'used' in line:
        print("OPR")
        sys.stdout.write(line)
        sys.stdout.writelines(itertools.islice(f, 4))
</code>```

my doubt is i have 3 text files called Finaltxt.1,Finaltxt.2,Finaltxt.3 in the some directory
how i do check the "used" word for all three text files and write 3 lines of text
which i have done above code

答:
Check out the code below, as I think it does what you want to accomplish:

```<code>output_file=open("file.txt","w")
output_file.write("file: lineNo1 \n")
output_file.write("file: lineNo2 used \n")
output_file.write("file: lineNo3 \n")
output_file.write("file: lineNo4 used \n")
output_file.write("file: lineNo5 \n")
output_file.write("file: lineNo6 \n")
output_file.close()

output_file=open("file1.txt","w")
output_file.write("file1: lineNo1 \n")
output_file.write("file1: lineNo2 \n")
output_file.write("file1: lineNo3 \n")
output_file.write("file1: lineNo4 used \n")
output_file.write("file1: lineNo5 \n")
output_file.write("file1: lineNo6 \n")
output_file.close()

output_file=open("file2.txt","w")
output_file.write("file2: lineNo1 \n")
output_file.write("file2: lineNo2 \n")
output_file.write("file2: lineNo3 \n")
output_file.write("file2: lineNo4 \n")
output_file.write("file2: lineNo5 \n")
output_file.write("file2: lineNo6 used \n")
output_file.close()

import collections
import itertools
import sys
with open('file.txt') as f, open('file1.txt') as f1, open('file2.txt') as f2 :
  fTXT, f1TXT, f2TXT = f.readlines(), f1.readlines(), f2.readlines()
  for lineNo in range(0, min(len(fTXT), len(f1TXT), len(f2TXT)) ):
      if 'used' in fTXT[lineNo] or 'used' in f1TXT[lineNo] or 'used' in f2TXT[lineNo]:
          print("OPR")
          sys.stdout.write("###" + fTXT[lineNo] + "###" + f1TXT[lineNo] + "###" + f2TXT[lineNo])
</code>```

It outputs:

```<code>OPR
###file: lineNo2 used
###file1: lineNo2
###file2: lineNo2
OPR
###file: lineNo4 used
###file1: lineNo4 used
###file2: lineNo4
OPR
###file: lineNo6
###file1: lineNo6
###file2: lineNo6 used
</code>```

Body:
I have text file. i want to open that text file and search one word called "OPR" if that
word occured in the Final.txt file write 3 line of that particular string example code
given below

text1="Some decoders allow you to manipulate the image reading"
text2="file.This can often be used to speed up decoding when creating"
text3="when speed is usually more important than quality  printing"
text4="monochrome laser printer when only a greyscale"
text4="Note that the resulting image may not exactly match the requested"
text5="mode and size. To make sure that the image is not larger"
text6="given size, use the thumbnail method instead."

output_file=open("Final.txt","a")
output_file.write(text1)
output_file.write(text2)
output_file.write(text3)
output_file.write(text4)
output_file.write(text5)
output_file.write(text6)
output_file.close()

import collections
import itertools
import sys
with open('output\\Final.txt') as f:
  for line in f:
    if 'used' in line:
        print("OPR")
        sys.stdout.write(line)
        sys.stdout.writelines(itertools.islice(f, 4))

my doubt is i have 3 text files called Finaltxt.1,Finaltxt.2,Finaltxt.3 in the some directory
how i do check the "used" word for all three text files and write 3 lines of text
which i have done above code

Body:
Check out the code below, as I think it does what you want to accomplish:

output_file=open("file.txt","w")
output_file.write("file: lineNo1 \n")
output_file.write("file: lineNo2 used \n")
output_file.write("file: lineNo3 \n")
output_file.write("file: lineNo4 used \n")
output_file.write("file: lineNo5 \n")
output_file.write("file: lineNo6 \n")
output_file.close()

output_file=open("file1.txt","w")
output_file.write("file1: lineNo1 \n")
output_file.write("file1: lineNo2 \n")
output_file.write("file1: lineNo3 \n")
output_file.write("file1: lineNo4 used \n")
output_file.write("file1: lineNo5 \n")
output_file.write("file1: lineNo6 \n")
output_file.close()

output_file=open("file2.txt","w")
output_file.write("file2: lineNo1 \n")
output_file.write("file2: lineNo2 \n")
output_file.write("file2: lineNo3 \n")
output_file.write("file2: lineNo4 \n")
output_file.write("file2: lineNo5 \n")
output_file.write("file2: lineNo6 used \n")
output_file.close()

import collections
import itertools
import sys
with open('file.txt') as f, open('file1.txt') as f1, open('file2.txt') as f2 :
  fTXT, f1TXT, f2TXT = f.readlines(), f1.readlines(), f2.readlines()
  for lineNo in range(0, min(len(fTXT), len(f1TXT), len(f2TXT)) ):
      if 'used' in fTXT[lineNo] or 'used' in f1TXT[lineNo] or 'used' in f2TXT[lineNo]:
          print("OPR")
          sys.stdout.write("###" + fTXT[lineNo] + "###" + f1TXT[lineNo] + "###" + f2TXT[lineNo])

It outputs:

OPR
###file: lineNo2 used
###file1: lineNo2
###file2: lineNo2
OPR
###file: lineNo4 used
###file1: lineNo4 used
###file2: lineNo4
OPR
###file: lineNo6
###file1: lineNo6
###file2: lineNo6 used


问:
Android Studio 1.2.2 ClassNotFoundException android.widget.viewstub
I just installed Android Studio and whenever I start a project (even the default "Hello world" activity created by the IDE).

I have this exception which is raised :

java.lang.ClassNotFoundException: Didn't find class
  "android.widget.ViewStub" on path: DexPathList[[zip file
  "/data/app/com.example.noname.exceptiontest-2/base.apk"],nativeLibraryDirectories=[/vendor/lib
  /system/lib]]

I wished I had some logcat to show but it doesn't seems like this exception is logged in it.

It doesn't stop the project or any other project that I have from working, just a little bit frustrating to go through the stack of this exception every time I run my projects in debug.

After looking around the Internet it doesn't seem that that many people have this problem, only answer that would match my issue would be a problem with Android studio. However those answers dated from more than one year.

I just changed my computer and wanted to move from Eclipse to Android Studio to do some development on my free time. I don't have access to my previous environment for the moment to try to install Android studio and reproduce that error.

Does anyone have or already had this error ? (To reproduce New Hello world Activity, activate any exception in Android Studio and run in debug)

Cheers

答:
Old question, but I had this same issue with Android Studio 2.3

With a project that had 4 modules, the trouble was that I had a misspelling in one of the gradle.build files for one of the modules in the applicationId value.

```<code>defaultConfig {
        applicationId "com.my.project"
}
</code>```

After fixing this, and verifying all of the AndroidManifest.xml values for package matched the build.gradle value above within each module, it worked.

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my.project">

</manifest>
</code>```

You may also need to go to File > Invalidate Caches / Restart... to clean it all out.

Body:
Old question, but I had this same issue with Android Studio 2.3

With a project that had 4 modules, the trouble was that I had a misspelling in one of the gradle.build files for one of the modules in the applicationId value.

defaultConfig {
        applicationId "com.my.project"
}

After fixing this, and verifying all of the AndroidManifest.xml values for package matched the build.gradle value above within each module, it worked.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my.project">

</manifest>

You may also need to go to File > Invalidate Caches / Restart... to clean it all out.


问:
how to convert System.IO.Stream into string and then back to System.IO.Stream
I have property of Stream type

```<code>public System.IO.Stream UploadStream { get; set; }
</code>```

How can I convert it into a string and send on to other side where I can again convert it into System.IO.Stream?

答:
I don't know what do you mean by converting a stream to a string. Also what's the other side?

In order to convert a stream to a string you need to use an encoding. Here's an example of how this could be done if we suppose that the stream represents UTF-8 encoded bytes:

```<code>using (var reader = new StreamReader(foo.UploadStream, Encoding.UTF8))
{
    string value = reader.ReadToEnd();
    // Do something with the value
}
</code>```

Body:
I have property of Stream type

public System.IO.Stream UploadStream { get; set; }

How can I convert it into a string and send on to other side where I can again convert it into System.IO.Stream?

Body:
I don't know what do you mean by converting a stream to a string. Also what's the other side?

In order to convert a stream to a string you need to use an encoding. Here's an example of how this could be done if we suppose that the stream represents UTF-8 encoded bytes:

using (var reader = new StreamReader(foo.UploadStream, Encoding.UTF8))
{
    string value = reader.ReadToEnd();
    // Do something with the value
}


问:
Finding largest product in a series
I am trying to solve the following problem: https://projecteuler.net/problem=8

Basically I am going through the 2D array and getting the 13 digit product from each of the eight directions (N, NW, NE, E, W, S, SW, SE) and setting the return value to the largest one (if there is one).

But I am getting an answer of 64497254400, which is incorrect. Any hints as to what I could possibly be doing wrong?

Following is my straightforward, inefficient solution:

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

using namespace std;

long long int MAX(long long int a, long long int b)
{
    if (a > b)
    {
        return a;
    }
    else
    {
        return b;
    }
}

void largest_product_in_series(int param)
{
    char filename[] = "8_.txt";
    char my_character ;
    int column = 0; int row = 0;
    int c = 0; int r = 0; int cc = 0; int rr = 0;
    int list[100][100];
    int num = param - 1;

    ifstream fin;
    fin.open(filename, ios::in);

    while (!fin.eof() )
    {
        fin.get(my_character);
        if (my_character == '\n')
        {
            row++;
            r++;
            c = 0;
            cout << endl;
        }
        else
        {
            if (row == 0)
            {
                column++;
            }
            list[r][c] = (my_character - '0');
            cout << list[r][c];
            c++;
        }
    }

    cout << "Column: " << column << endl;
    cout << "Row: " << row << endl;

    long long int greatest_product = 0;

    long long int product = 0;

    for (rr = 0; rr < row; rr++)
    {
        for (cc = 0; cc < column; cc++)
        {
            //cout << "Column: " << cc << " Row: " << rr << endl;
            if (rr >= num)
            {
                r = rr;
                c = cc;
                product = list[r--][c];

                for (int i = 0; i < num; i++)
                {
                    product *= list[r--][c];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if ((rr + num) <= row)
            {
                r = rr;
                c = cc;
                product = list[r++][c];

                for (int i = 0; i < num; i++)
                {
                    product *= list[r++][c];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if (cc >= num)
            {
                r = rr;
                c = cc;
                product = list[r][c--];

                for (int i = 0; i < num; i++)
                {
                    product *= list[r][c--];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if ((cc + num) <= column)
            {
                r = rr;
                c = cc;
                product = list[r][c++];

                for (int i = 0; i < num; i++)
                {
                    product *= list[r][c++];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if ((rr >= num) && (cc >= num)) // NW
            {
                r = rr;
                c = cc;
                product = list[r--][c--];
                for (int i = 0; i < num; i++)
                {
                    product = list[r--][c--];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if ((rr >= num) && ((cc + num) <= column)) // NE
            {
                r = rr;
                c = cc;
                product = list[r--][c++];
                for (int i = 0; i < num; i++)
                {
                    product = list[r--][c++];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if (((rr + num) <= row) && ((cc >= num))) // SW
            {
                r = rr;
                c = cc;
                product = list[r++][c--];
                for (int i = 0; i < num; i++)
                {
                    product = list[r++][c--];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if (((rr + num) <= row) && ((cc + num) <= column)) // SE
            {
                r = rr;
                c = cc;
                product = list[r++][c++];
                for (int i = 0; i < num; i++)
                {
                    product = list[r++][c++];
                }
                greatest_product = MAX(greatest_product, product);
            }
            //cout << "G: " << greatest_product << endl;
        }
    }
    cout << "Greatest Product: " << greatest_product << endl;
}

int main(void)
{
    largest_product_in_series(13);
    return 0;
}
</code>```

答:
When I run your code, it says the column is 50, and the row is 21. That seems a little odd, since it should be a 20x50 array, not a 21x50 array, that would be a 1050-digit number. Best guess is that you're accidentally storing some unprintable characters in a 21st row and the product involves some of those.

Also, some of the loops have product = ... instead of product *= ...

And lastly, it wouldn't influence the answer, but multiplication is commutative, so if you get the product of some numbers forward and backward, the result will be the same. So you can simplify your solution a little by getting rid of everything with N xor W in the direction.

Title: Finding largest product in a series

Body:
I am trying to solve the following problem: https://projecteuler.net/problem=8

Basically I am going through the 2D array and getting the 13 digit product from each of the eight directions (N, NW, NE, E, W, S, SW, SE) and setting the return value to the largest one (if there is one).

But I am getting an answer of 64497254400, which is incorrect. Any hints as to what I could possibly be doing wrong?

Following is my straightforward, inefficient solution:

#include <stdio.h>
#include <iostream>
#include <fstream>

using namespace std;

long long int MAX(long long int a, long long int b)
{
    if (a > b)
    {
        return a;
    }
    else
    {
        return b;
    }
}

void largest_product_in_series(int param)
{
    char filename[] = "8_.txt";
    char my_character ;
    int column = 0; int row = 0;
    int c = 0; int r = 0; int cc = 0; int rr = 0;
    int list[100][100];
    int num = param - 1;

    ifstream fin;
    fin.open(filename, ios::in);

    while (!fin.eof() )
    {
        fin.get(my_character);
        if (my_character == '\n')
        {
            row++;
            r++;
            c = 0;
            cout << endl;
        }
        else
        {
            if (row == 0)
            {
                column++;
            }
            list[r][c] = (my_character - '0');
            cout << list[r][c];
            c++;
        }
    }

    cout << "Column: " << column << endl;
    cout << "Row: " << row << endl;

    long long int greatest_product = 0;

    long long int product = 0;

    for (rr = 0; rr < row; rr++)
    {
        for (cc = 0; cc < column; cc++)
        {
            //cout << "Column: " << cc << " Row: " << rr << endl;
            if (rr >= num)
            {
                r = rr;
                c = cc;
                product = list[r--][c];

                for (int i = 0; i < num; i++)
                {
                    product *= list[r--][c];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if ((rr + num) <= row)
            {
                r = rr;
                c = cc;
                product = list[r++][c];

                for (int i = 0; i < num; i++)
                {
                    product *= list[r++][c];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if (cc >= num)
            {
                r = rr;
                c = cc;
                product = list[r][c--];

                for (int i = 0; i < num; i++)
                {
                    product *= list[r][c--];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if ((cc + num) <= column)
            {
                r = rr;
                c = cc;
                product = list[r][c++];

                for (int i = 0; i < num; i++)
                {
                    product *= list[r][c++];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if ((rr >= num) && (cc >= num)) // NW
            {
                r = rr;
                c = cc;
                product = list[r--][c--];
                for (int i = 0; i < num; i++)
                {
                    product = list[r--][c--];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if ((rr >= num) && ((cc + num) <= column)) // NE
            {
                r = rr;
                c = cc;
                product = list[r--][c++];
                for (int i = 0; i < num; i++)
                {
                    product = list[r--][c++];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if (((rr + num) <= row) && ((cc >= num))) // SW
            {
                r = rr;
                c = cc;
                product = list[r++][c--];
                for (int i = 0; i < num; i++)
                {
                    product = list[r++][c--];
                }
                greatest_product = MAX(greatest_product, product);
            }
            if (((rr + num) <= row) && ((cc + num) <= column)) // SE
            {
                r = rr;
                c = cc;
                product = list[r++][c++];
                for (int i = 0; i < num; i++)
                {
                    product = list[r++][c++];
                }
                greatest_product = MAX(greatest_product, product);
            }
            //cout << "G: " << greatest_product << endl;
        }
    }
    cout << "Greatest Product: " << greatest_product << endl;
}

int main(void)
{
    largest_product_in_series(13);
    return 0;
}


问:
Python3 socket client to send and receive hex string
I am stuck in this socket client Python3 code:

```<code>import socket
import codecs

def Main():
        host = '127.0.0.2'
        port = 502

        mySocket = socket.socket()
        mySocket.connect((host,port))

        message = codecs.encode('\x00\x00\x00\x00\x00\x06\x01\x04\x00\x01\x00\x02')

        mySocket.send(message)
        data = codecs.decode(mySocket.recv(1024))

        print ('Received from server: ' + data)

        mySocket.close()

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

It gives the error

File "C:\Python34\lib\encodings\utf_8.py", line 16, in decode
      return codecs.utf_8_decode(input, errors, True)
  UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 11: invalid start byte

I am trying to connect to a Ananas - Modbus/TCP -server

What is the error?

Thanks!

答:
It's because it try to convert data into an utf-8 string (and some of the bytes contained are not possible to represent in utf-8).

If you want to see the hexadecial value of a byte array you can:

Python3.5+

```<code>data = mySocket.recv(1024)
data.hex()
</code>```

Othewrise

```<code>>>> import binascii
>>> data = mySocket.recv(1024)
>>> data = binascii.hexlify(data).decode()
</code>```

Body:
I am stuck in this socket client Python3 code:

import socket
import codecs

def Main():
        host = '127.0.0.2'
        port = 502

        mySocket = socket.socket()
        mySocket.connect((host,port))

        message = codecs.encode('\x00\x00\x00\x00\x00\x06\x01\x04\x00\x01\x00\x02')

        mySocket.send(message)
        data = codecs.decode(mySocket.recv(1024))

        print ('Received from server: ' + data)

        mySocket.close()

if __name__ == '__main__':
    Main()

It gives the error

File "C:\Python34\lib\encodings\utf_8.py", line 16, in decode
      return codecs.utf_8_decode(input, errors, True)
  UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 11: invalid start byte

I am trying to connect to a Ananas - Modbus/TCP -server

What is the error?

Thanks!

Body:
It's because it try to convert data into an utf-8 string (and some of the bytes contained are not possible to represent in utf-8).

If you want to see the hexadecial value of a byte array you can:

Python3.5+

data = mySocket.recv(1024)
data.hex()

Othewrise

>>> import binascii
>>> data = mySocket.recv(1024)
>>> data = binascii.hexlify(data).decode()


问:
Count the length of a number
Hello I would like to count the number there is in a number I mean if I have this double 78.23 the functions would return 4 if I have 145.123 I would got 6. Is it possible to do this with C++ ?
Thank you !</p>

答:
Precision - in the sense that you are asking about it - is as much a property of the output stream, as of the value being output.   Assuming you are outputting using an C++ ostream (ofstream, ostrstream, etc), look up properties ios_base::precision, ios_base::width, etc or stream manipulator like setprecision.    If you are using C I/O (sprintf(), etc), the answer depends upon modifiers specified for the %f format.

So the method to get the value you seek would probably be to output the value using your chosen method (stream manipulators, format specifiers) to a string.   Then compute the length of the string, subtract one for every trailing 0, the decimal point, etc.

Also, floating point variables with a base 2 mantissa (which includes most real-world floating point representations) cannot exactly represent any value that is not a sum of integral powers of 0.5  (the stored value is an approximation).     Among other things, this means a floating point variable cannot exactly represent values like 0.1 and 0.01.   Both  of your sample values 78.23 and 145.123 cannot be represented exactly using floating point variables.    Which is part of the reason why the answer to questions like yours depends on how the variable is output, as much as the value itself.

Title: Count the length of a number


问:
Using dot leaders for a food menu with bootstrap grids
I'm creating a food menu using the grid column system with bootstrap 3, and I'm trying to create dot leaders between the menu item and the price. I kind of got it to work, but I can't seem to get the dot leaders to extend to the right of the item, instead it breaks the line and continues under the menu.
Here's what I'm getting:

I tried

```<code>display:block; display:inline-block; display:inline;
</code>```

in the CSS. The only way I seem to be able to stop it from breaking is shortening the

```<code>content: '...'
</code>```

Is there a way I can get this to work, or do I have put the content in a table or use list items?

Here is the rest of my code, if anyone could help, I would appreciate it, thanks.

Cheese

White

Special

$8.99

$9.99

$13.50

$10.99

$11.99

$15.50

$12.99

$13.99

$17.50

    .dots::after {
       display: inline-flex;
       white-space: nowrap;
       overflow: hidden;
       text-overflow: clip;
       content:
        " . . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
     }```

答:
Would this do the trick for you? http://codepen.io/panchroma/pen/YZBZRx

As you'll see the important detail is that I've used a border style of dotted and made a few fixes to your HTML

I hope this helps!

HTML

```<code><div class="container">
  <div class="row">
         <div class="col-xs-6">
              <p class="item dots">Cheese</p>
              <p class="item dots">White</p>
              <p class="item dots">Special</p>
         </div>

         <div class="col-xs-2">
             <p class="item">$8.99</p>
             <p class="item">$9.99</p>
             <p class="item">$13.50</p>
         </div>

         <div class="col-xs-2">
             <p class="item">$10.99</p>
             <p class="item">$11.99</p>
             <p class="item">$15.50</p>
         </div>

         <div class="col-xs-2">
             <p class="item">$12.99</p>
             <p class="item">$13.99</p>
             <p class="item">$17.50</p>
         </div>
    </div>
</div>
</code>```

CSS

```<code>p.dots{
  border-bottom:1px #333 dotted;
}
</code>```

Body:
I'm creating a food menu using the grid column system with bootstrap 3, and I'm trying to create dot leaders between the menu item and the price. I kind of got it to work, but I can't seem to get the dot leaders to extend to the right of the item, instead it breaks the line and continues under the menu.
Here's what I'm getting:

I tried

display:block; display:inline-block; display:inline;

in the CSS. The only way I seem to be able to stop it from breaking is shortening the

content: '...'

Is there a way I can get this to work, or do I have put the content in a table or use list items?

Here is the rest of my code, if anyone could help, I would appreciate it, thanks.

Cheese

White

Special

$8.99

$9.99

$13.50

$10.99

$11.99

$15.50

$12.99

$13.99

$17.50

    .dots::after {
       display: inline-flex;
       white-space: nowrap;
       overflow: hidden;
       text-overflow: clip;
       content:
        " . . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
     }

Body:
Would this do the trick for you? http://codepen.io/panchroma/pen/YZBZRx

As you'll see the important detail is that I've used a border style of dotted and made a few fixes to your HTML

I hope this helps!

HTML

<div class="container">
  <div class="row">
         <div class="col-xs-6">
              <p class="item dots">Cheese</p>
              <p class="item dots">White</p>
              <p class="item dots">Special</p>
         </div>

         <div class="col-xs-2">
             <p class="item">$8.99</p>
             <p class="item">$9.99</p>
             <p class="item">$13.50</p>
         </div>

         <div class="col-xs-2">
             <p class="item">$10.99</p>
             <p class="item">$11.99</p>
             <p class="item">$15.50</p>
         </div>

         <div class="col-xs-2">
             <p class="item">$12.99</p>
             <p class="item">$13.99</p>
             <p class="item">$17.50</p>
         </div>
    </div>
</div>

CSS

p.dots{
  border-bottom:1px #333 dotted;
}


问:
Omitting the datatype (e.g. "unsigned" instead of "unsigned int")
I know that if the data type declaration is omitted in C/C++ code in such way: unsigned test=5;, the compiler automatically makes this variable an int (an unsigned int in this case). I've heard that it's a C standard and it will work in all compilers.

But I've also heard that doing this is considered a bad practice.

What do you think? Should I really type unsigned int instead of just unsigned?

Are short, long and long long also datatypes?

答: Gratuitous verbosity considered harmful. I would never write unsigned int or long int or signed anything (except char or bitfields) because it increases clutter and decreases the amount of meaningful code you can fit in 80 columns. (Or more likely, encourages people to write code that does not fit in 80 columns...)


问:
How to pass an argument to 'isa' function in matlab
I want to check a variable is existing in Matlab workspace, then check its class.
All thing was done by commands in m file.
In the case, the name of the variable is a symbolic or character, how I can use isa function.

```<code>a='x';
isa(a,'timeseries')
</code>```

the above code is not worked, but if I change to

```<code>isa(x,'timeseries')
</code>```

it is ok, so how I can check the class of an object by not directly pass its name?
Thank you!

答:
You want to use the function exist: https://www.mathworks.com/help/matlab/ref/exist.html

```<code>if exist('x','var')
   class(x)
end
</code>```

You pass a string with the name of the variable to exist. Once you have established it exists, you can use it in your isa call.

Body:
I want to check a variable is existing in Matlab workspace, then check its class.
All thing was done by commands in m file.
In the case, the name of the variable is a symbolic or character, how I can use isa function.

a='x';
isa(a,'timeseries')

the above code is not worked, but if I change to

isa(x,'timeseries')

it is ok, so how I can check the class of an object by not directly pass its name?
Thank you!

Body:
You want to use the function exist: https://www.mathworks.com/help/matlab/ref/exist.html

if exist('x','var')
   class(x)
end

You pass a string with the name of the variable to exist. Once you have established it exists, you can use it in your isa call.


问:
Rank top 10 but sort alphabetically then by rank. SQL
I have a table for a county that holds testing stats for all the schools in that county. Im trying to display the top 10 ranking schools where the difference between the writing and reading scores are the greatest

```<code>select *
    from
        (select  SchoolName, WriPassingPer, ReaPassingPer,
        (WriPassingPer - WriPassingPer) as Difference, dense_rank() over
                (order by ABS(WriPassingPer - WriPassingPer) desc) as rnk from Pima)
    where rnk <= 10;
</code>```

I want it to look like

```<code>Rank | School Name | Writing Score | Reading Score | Difference
</code>```

But at the moment it's just listing every single school in the county with a rank of either 1 or 2. There are 283 schools in the county

答: You are computing WriPassingPer - WriPassingPer instead of WriPassingPer - ReaPassingPer or something like that...

Body:
I have a table for a county that holds testing stats for all the schools in that county. Im trying to display the top 10 ranking schools where the difference between the writing and reading scores are the greatest

select *
    from
        (select  SchoolName, WriPassingPer, ReaPassingPer,
        (WriPassingPer - WriPassingPer) as Difference, dense_rank() over
                (order by ABS(WriPassingPer - WriPassingPer) desc) as rnk from Pima)
    where rnk <= 10;

I want it to look like

Rank | School Name | Writing Score | Reading Score | Difference

But at the moment it's just listing every single school in the county with a rank of either 1 or 2. There are 283 schools in the county