问:
Updating tableview cells
I'm still really green as Object-C so hopefully I'm able to communicate this well, so hopefully with my code examples I can explain this.

What I have is a table with four rows. Each row has a label (Clock in time, out to lunch time, etc) and a time (detailTextLabel). The label's are stored in an array and the detail's are generated from the NSDate family of functions (please forgive my terminology). In order to change the time values I use a data picker adjusted to pick time. An action is used to update the detail of a row when the time is changed using the picker.

The follow code snippets are in the same *.m class.

Here's a snipped down version of this -

```<code>// textLabel goes on the left, detailTextLabel goes on the right
// This puts the labelArray on the left and times on the right
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCustomCellID = @"CustomCellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCustomCellID] autorelease];

        // This disable the hightlighter effect when we select a row.
        // We need the highlighter, but we'll leave the code here.
        // cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    cell.textLabel.text = [self.labelArray objectAtIndex:indexPath.row];

    // --- Start of routine to work with adding hours and minutes to stuff

    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

    // --- Set Clock In time (initially time 'now').
    if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Clock In"])
    {
        self.clockIn = [NSDate date];

        cell.detailTextLabel.text = [self.dateFormatter stringFromDate:clockIn];

        NSLog(@"Clock In - %@", clockIn);
        //NSLog(@"Clock In (cell*) - %@", cell.detailTextLabel.text);

        return cell;
    }

    // --- Set Out to Lunch time (initially clockIn + 5 hours)
    if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Out to Lunch"])
    {
        [offsetComponents setHour:5];

        self.outToLunch = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
                              dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];

        cell.detailTextLabel.text = [self.dateFormatter stringFromDate:outToLunch];

        NSLog(@"indexPath.row (Out to Lunch): %i", indexPath.row);

        NSLog(@"Out to Lunch - %@", outToLunch);
        //NSLog(@"Out to Lunch (cell*) - %@", cell.detailTextLabel.text);

        return cell;
    }

    // Leaving out two other if clauses as they duplicate the Out to Lunch clause.

    //cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[NSDate date]];
    //return cell;
    return nil;
</code>```

This chunk of code work well and gives me no issues.

When a row, such as "Clock In" is selected an animiation is called that scroll's up a time picking datePicker. As the times are scrolled by the "Clock In" time updates.

Here's where I have my problem. I can't figure out how to have the "Out to Lunch" row update as the "Clock In" time is updated.

Here's the code I have for my picking action -

```<code>- (IBAction)dateAction:(id)sender
{
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.detailTextLabel.text = [self.dateFormatter stringFromDate:self.pickerView.date];

    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

    if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Clock In"])
    {
        if (cell.detailTextLabel.text != [self.dateFormatter stringFromDate:clockIn])
        {
            NSLog(@"clockIn time changed...");

            // Since clockIn time changed, we need to change outToLunch, inFromLunch, and clockOut

            // Change the outToLunch time
            [offsetComponents setHour:5];

            self.outToLunch = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
                               dateByAddingComponents:offsetComponents toDate:self.pickerView.date options:0];

            NSLog(@"New Out to Lunch time: %@", [self.dateFormatter stringFromDate:outToLunch]);

            // Here is where I get stuck
        }
        //return nil;
    }
}
</code>```

What I envision for the "Change the outToLunch time" clause is something like this...

Take the new clockIn time and add 5 hours to it, and make this the new outToLunch time.
 a. NSLog just to see that this math function worked.

Using the index of the detailTextLabel for the outToLunch time cell, put this new time there.

There will be two more rows along with the outToLunch row that will be updated at the same time.

How can I do this?

Thanks for your help.

答:
at the end of your - (IBAction)dateAction:(id)sender use the following:

```<code>    // Here is where I get stuck
      }
      //return nil;
  }
  NSArray *indexPathArray=[NSArray arrayWithObject:indexPath];
  [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
}
</code>```

alternatively, you could use [self.tableView reloadData], but that is overkill for just reloading a single row, especially if the number of rows you have is large.

Title: Updating tableview cells

Body:
I'm still really green as Object-C so hopefully I'm able to communicate this well, so hopefully with my code examples I can explain this.

What I have is a table with four rows. Each row has a label (Clock in time, out to lunch time, etc) and a time (detailTextLabel). The label's are stored in an array and the detail's are generated from the NSDate family of functions (please forgive my terminology). In order to change the time values I use a data picker adjusted to pick time. An action is used to update the detail of a row when the time is changed using the picker.

The follow code snippets are in the same *.m class.

Here's a snipped down version of this -

// textLabel goes on the left, detailTextLabel goes on the right
// This puts the labelArray on the left and times on the right
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCustomCellID = @"CustomCellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCustomCellID] autorelease];

        // This disable the hightlighter effect when we select a row.
        // We need the highlighter, but we'll leave the code here.
        // cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    cell.textLabel.text = [self.labelArray objectAtIndex:indexPath.row];

    // --- Start of routine to work with adding hours and minutes to stuff

    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

    // --- Set Clock In time (initially time 'now').
    if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Clock In"])
    {
        self.clockIn = [NSDate date];

        cell.detailTextLabel.text = [self.dateFormatter stringFromDate:clockIn];

        NSLog(@"Clock In - %@", clockIn);
        //NSLog(@"Clock In (cell*) - %@", cell.detailTextLabel.text);

        return cell;
    }

    // --- Set Out to Lunch time (initially clockIn + 5 hours)
    if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Out to Lunch"])
    {
        [offsetComponents setHour:5];

        self.outToLunch = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
                              dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];

        cell.detailTextLabel.text = [self.dateFormatter stringFromDate:outToLunch];

        NSLog(@"indexPath.row (Out to Lunch): %i", indexPath.row);

        NSLog(@"Out to Lunch - %@", outToLunch);
        //NSLog(@"Out to Lunch (cell*) - %@", cell.detailTextLabel.text);

        return cell;
    }

    // Leaving out two other if clauses as they duplicate the Out to Lunch clause.

    //cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[NSDate date]];
    //return cell;
    return nil;

This chunk of code work well and gives me no issues.

When a row, such as "Clock In" is selected an animiation is called that scroll's up a time picking datePicker. As the times are scrolled by the "Clock In" time updates.

Here's where I have my problem. I can't figure out how to have the "Out to Lunch" row update as the "Clock In" time is updated.

Here's the code I have for my picking action -

- (IBAction)dateAction:(id)sender
{
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.detailTextLabel.text = [self.dateFormatter stringFromDate:self.pickerView.date];

    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

    if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Clock In"])
    {
        if (cell.detailTextLabel.text != [self.dateFormatter stringFromDate:clockIn])
        {
            NSLog(@"clockIn time changed...");

            // Since clockIn time changed, we need to change outToLunch, inFromLunch, and clockOut

            // Change the outToLunch time
            [offsetComponents setHour:5];

            self.outToLunch = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
                               dateByAddingComponents:offsetComponents toDate:self.pickerView.date options:0];

            NSLog(@"New Out to Lunch time: %@", [self.dateFormatter stringFromDate:outToLunch]);

            // Here is where I get stuck
        }
        //return nil;
    }
}

What I envision for the "Change the outToLunch time" clause is something like this...

Take the new clockIn time and add 5 hours to it, and make this the new outToLunch time.
 a. NSLog just to see that this math function worked.

Using the index of the detailTextLabel for the outToLunch time cell, put this new time there.

There will be two more rows along with the outToLunch row that will be updated at the same time.

How can I do this?

Thanks for your help.

Body:
at the end of your - (IBAction)dateAction:(id)sender use the following:

    // Here is where I get stuck
      }
      //return nil;
  }
  NSArray *indexPathArray=[NSArray arrayWithObject:indexPath];
  [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
}

alternatively, you could use [self.tableView reloadData], but that is overkill for just reloading a single row, especially if the number of rows you have is large.


来源: stackexchange

问:
Some images don't appear on in the browser
I'm making a website, consisting of 5 pages (e.g. page1.html, page2.html, etc. and following .css sheets). Weirdly, on some pages part of images appears without problem, but others do not. It seems like problem may be with pages/files, since when I tried to use the same image in different html file in place of the appearing image and it showed without problems. I tried using both copying whole url and name of the image with extension(images are in the same directory as the html and css files). Any thoughts?
(I'm using Chrome to view the website)

```<code><!DOCTYPE html>
<html>
<head>
  <meta name="description"  />
  <title> "animātiō" is "bestowing of life"</title>
   <link rel="stylesheet" type="text/css" href="CW1_page1_style.css" />
  </head>
<body>
  <h1>Just a small website about animation</h1>

  <div class="container">
    <div id="menu">

        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page0.html">Menu & Navigation</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page1.html">History and Beginnings</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page2.html">Traditional medium</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page3.html">Computer animation</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page4.html">2D or 3D: Which is Better?</a>
    </div>
  </div>

<br /><br /><br /><br />

<div>

  <section id="section-a">
    <div class="box-1">
       The first "animations" were sequences of consecutive images, which would give an illusion of movement.
       At the beginning there existed machines like Praxinoscope - series of images rotated at high speed - and Shadow plays - moving figures on a screen.
       Not to mention the technique known to every child that is a flipbook - conjuring "moving" image upon quickly flipping paper sheets.
  </div >
</section>
<section >
  <section id=section
  <p id="ex" >Examples of machines</p>
  <div class="examples">

   <img class="slide" src='magic-lantern.png' alt='Magic Lantern' />

  <img class="slide" src='zoetrope.gif' alt='Zoetrope'/>

   <img class="slide" src='flip-book.png' alt='Flip-Book'/>

    <img class="slide" src='praxinoscope.png' alt='Praxinoscope'/>

    </div>
</section>
<br />
  <section id="section-c">
    <div class-"box-2">
      The breakthrought began with the invention of motion pictures.
      Hand-drawn and painted animation was prevalent throughout the whole 20th century. From the first short movies of the silent era, to fresh creations with color and soundtrack
      animation started growing in popularity - and bringing more and more profit.
      </div>
      <div class="box-3">
        <img scr="snow-white.jpg" alt="Snow White'"/>
        The first hand-drawn animated movie - Disney's "Snow White" (1937)
        <img scr="disney.jpg" alt="Walt Disney'"/>
        Walt Disney - pioneer of American animation industry
      </div>
  </section>

<section id="section-d">
  <div class="box-3">
After addition of sound and color and subsequent success of Disney, other studios began to produce their own features. This was, no doubt, the golden years for Hollywood animation.
  </div>
  <div class="box-4">
    With the end of the 1950s and growing popolarity of television, stations began to emit various animated productions. A lot of them were cartoons aimed to kids
  </div>
  <div class="box-5">
Major animated productions from the Golden Era of American Televison feature cartoons like "The Flinstons", "Bear Yoggy"
  <br />
  <img scr="felixc.jpg" alt="Felix the Cat"/>
  <img scr="flinstones.jpg" alt="Flinstons"/>
  </div>
</section>

</div>

  </body>
</html>
</code>```

```<code>body {
  background-color: beige;
  font-size: 17px;
}

 /** {
  box-sizing: border-box;
} */
h1 {
  color: #3e3e80;
  text-align: center;
}

.container {
  position: absolute;
  margin: 20px;
  width: auto;
}

#menu {
   overflow: hidden;
   background-color: green
 }

 #menu a {
   float: left;
   color: white;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }
 #menu a:hover {
  color: #3e3e80;
  background-color: white;
 }

  .slide {
    float: left;
    width: 25%;
    padding: 0px;
  }

  .examples::after {
    content: "";
    clear: both;
    display: inline-flex;
  }

  #section-c {
    display : inline-flex;
  }
</code>```

Example above: Here first 4 images work, the rest doesn't

And below everything appears no problem:

```<code><!DOCTYPE html>
<html>
<head>
  <meta name="description"  />
    <title> "animātiō" is "bestowing of life"</title>
    <link rel="stylesheet" type="text/css" href="CW1_page2_style.css" />
  </head>
<body>
  <h1>Just a small website about animation</h1>

  <div class="container">
    <div id="menu">

        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page0.html">Menu & Navigation</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page1.html">History and Beginnings</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page2.html">Traditional medium</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page3.html">Computer animation</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page4.html">2D or 3D: Which is Better?</a>
    </div>
  </div>

<br /><br /><br /><br />

  <div>
    <section id="section-a">
      <div class="box-0">
      Traditional animation (hand-drawn animation) is the first type of aniamtion that have been used (not counting any machines equipped with slides).
      <br /><br />
      The oldest and used commonly throughtout most of the history of animation,
      recently this style seemed to fall out of grace in favour of computer generated images.
      However, it's still used even nowadays and has many enthusiasts.
      <br />

    </div>
    <div class='box-1'>
      <img class="im" src="aniwork1.jpg" alt="Animator working on" />
    </div >
    <div class="small-fact">
      <img class="im" src="aniwork2.jpg" alt="Animator working on" />
    </div>
    <div class="small-fact">
        Did you know: The standard number of frames is 90 per minute of the movie!
        <br /> <br />
        That makes 8100 drawings for a 90 minutes-long film!
    </div>
    </section>

  <section id="section-b">
    <div class="box-2">
      The process of creating any animated piece starts with storyboards.
       Here, delegated artists prepare rough layouts of the scene, with characters and backgrounds taken into consideration.
      <img  class="board" src="storyboard.jpg" alt="Storyboard" />
    </div>
      <div class="box-3">

       <img class="phase" src="animatic phase.gif" alt="Animatic phase form Avatar: The Last Airbender" />
The next stage is animatic phase - similar to storyboarding, but consisting of key frame (the most important parts of the particular scenes).
  <br /> <br />
  (Above: animatic phase from "Avatar: The Last Airbender")
  <br /> <br />
  (Left: Storyboards indicate on surroundings, as well as the charaters and actions.)
     </div>
    <div class="box-4">
      Afterwards, there's a need to provide the in-between, additional images which will guarantee smoothness of the animation.
      Lastly, it's only the matter of inking and coloring the pages.
        <img class="slide1" src='inking.jpg' alt='Inking a character #1' />
        <img class="slide2" src='ink-color.jpg' alt='Inked and colored character' />

    </div>

  </section>
  <section>

  <div class="examples">
  <p id="ex" >Examples of traditionally animated features</p>
    <img class="pink" src='pinkp.jpg' alt='The Pink Panther'/>
     <img class="pi" src='pinoccio.jpg' alt='Pinoccio'/>
      <img class="lion" src='lion_king.webp' alt='The Lion King'/>
      <img class="eldorado" src='eldorado.jpg' alt='Road to El Dorado'/>

  </div>

</section>
  </body>
</html>
</code>```

```<code>body {
  background-color: beige;
  font-size: 17px;
}
h1 {
  color: #3e3e80;
  text-align: center;
}

.container {
  position: absolute;
  margin: 20px;
  width: auto;
}

#menu {
   overflow: hidden;
   background-color: brown;
 }

 #menu a {
   float: left;
   color: white;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }
 #menu a:hover {
  color: #3e3e80;
  background-color: white;
 }

  #section-a {
    display: flex;
  }
  #section-a .box-0{
      float: left;
      width: 70%;
      padding: 5px;
  }
  #section-a .box-1 .im{
    width: 250px;
    height: 200px;
  }
  #section-a .small-fact{
    float: left;
    width: 30%;
    padding: 5px;
  }
  #section-a .small-fact .im {
    width: 250px;
    height: 175px;
  }

  #section-b {
    display: inline-flex;
    background-color: brown;
    color: white;
  }

  #section-b .box-2{
    padding: 5px;
  }

  #section-b .box-2 .board {
    width: 400px;
    height: 400px;

  }

  #section-b .box-3 {
    padding: 5px;
  }

  #section-b .box-3 .phase .{
    width: 100vs;
    height: auto;
  }

   #section-b .box-4{
    padding: 5px;
  }

#section-b .box-4 .slide1 {
  width: 300px;
  height: 200px;

}
#section-b .box-4 .slide2 {
  width: 60%;
  height: 35%;

}

#ex {
  text-align: center;
  font-weight: bold;
  text-decoration: underline
}

.pink {
  float: left;
  width: 300px;
  padding: 0px;
}
.pi {
  float: left;
  width: 300px;
  height: 300px
  padding: 0px;
}
.lion {
  float: left;
  width: 300px;
  height: 20%;
  padding: 0px;
}
.eldorado {
  float: left;
  padding: 0px;
  height: 50vh;
  width: 65vh;
}

.examples::after {
  content: "";
  clear: both;
  display: table;
}
</code>```

答: Ok just try to replace "scr" attribute by "src"</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm making a website, consisting of 5 pages (e.g. page1.html, page2.html, etc. and following .css sheets). Weirdly, on some pages part of images appears without problem, but others do not. It seems like problem may be with pages/files, since when I tried to use the same image in different html file in place of the appearing image and it showed without problems. I tried using both copying whole url and name of the image with extension(images are in the same directory as the html and css files). Any thoughts?
(I'm using Chrome to view the website)

<!DOCTYPE html>

  <meta name="description"  />
  <title> "animātiō" is "bestowing of life"</title>
   <link rel="stylesheet" type="text/css" href="CW1_page1_style.css" />

Just a small website about animation

        Menu & Navigation
        History and Beginnings
        Traditional medium
        Computer animation
        2D or 3D: Which is Better?

       The first "animations" were sequences of consecutive images, which would give an illusion of movement.
       At the beginning there existed machines like Praxinoscope - series of images rotated at high speed - and Shadow plays - moving figures on a screen.
       Not to mention the technique known to every child that is a flipbook - conjuring "moving" image upon quickly flipping paper sheets.

  <section id=section

Examples of machines

      The breakthrought began with the invention of motion pictures.
      Hand-drawn and painted animation was prevalent throughout the whole 20th century. From the first short movies of the silent era, to fresh creations with color and soundtrack
      animation started growing in popularity - and bringing more and more profit.

        The first hand-drawn animated movie - Disney's "Snow White" (1937)

        Walt Disney - pioneer of American animation industry

After addition of sound and color and subsequent success of Disney, other studios began to produce their own features. This was, no doubt, the golden years for Hollywood animation.

    With the end of the 1950s and growing popolarity of television, stations began to emit various animated productions. A lot of them were cartoons aimed to kids

Major animated productions from the Golden Era of American Televison feature cartoons like "The Flinstons", "Bear Yoggy"

body {
  background-color: beige;
  font-size: 17px;
}

 /** {
  box-sizing: border-box;
} */
h1 {
  color: #3e3e80;
  text-align: center;
}

.container {
  position: absolute;
  margin: 20px;
  width: auto;
}

#menu {
   overflow: hidden;
   background-color: green
 }

 #menu a {
   float: left;
   color: white;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }
 #menu a:hover {
  color: #3e3e80;
  background-color: white;
 }

  .slide {
    float: left;
    width: 25%;
    padding: 0px;
  }

  .examples::after {
    content: "";
    clear: both;
    display: inline-flex;
  }

  #section-c {
    display : inline-flex;
  }

Example above: Here first 4 images work, the rest doesn't

And below everything appears no problem:

<!DOCTYPE html>

  <meta name="description"  />
    <title> "animātiō" is "bestowing of life"</title>
    <link rel="stylesheet" type="text/css" href="CW1_page2_style.css" />

Just a small website about animation

        Menu & Navigation
        History and Beginnings
        Traditional medium
        Computer animation
        2D or 3D: Which is Better?

      Traditional animation (hand-drawn animation) is the first type of aniamtion that have been used (not counting any machines equipped with slides).

      The oldest and used commonly throughtout most of the history of animation,
      recently this style seemed to fall out of grace in favour of computer generated images.
      However, it's still used even nowadays and has many enthusiasts.

        Did you know: The standard number of frames is 90 per minute of the movie!

        That makes 8100 drawings for a 90 minutes-long film!

      The process of creating any animated piece starts with storyboards.
       Here, delegated artists prepare rough layouts of the scene, with characters and backgrounds taken into consideration.

The next stage is animatic phase - similar to storyboarding, but consisting of key frame (the most important parts of the particular scenes).

  (Above: animatic phase from "Avatar: The Last Airbender")

  (Left: Storyboards indicate on surroundings, as well as the charaters and actions.)

      Afterwards, there's a need to provide the in-between, additional images which will guarantee smoothness of the animation.
      Lastly, it's only the matter of inking and coloring the pages.

Examples of traditionally animated features

body {
  background-color: beige;
  font-size: 17px;
}
h1 {
  color: #3e3e80;
  text-align: center;
}

.container {
  position: absolute;
  margin: 20px;
  width: auto;
}

#menu {
   overflow: hidden;
   background-color: brown;
 }

 #menu a {
   float: left;
   color: white;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }
 #menu a:hover {
  color: #3e3e80;
  background-color: white;
 }

  #section-a {
    display: flex;
  }
  #section-a .box-0{
      float: left;
      width: 70%;
      padding: 5px;
  }
  #section-a .box-1 .im{
    width: 250px;
    height: 200px;
  }
  #section-a .small-fact{
    float: left;
    width: 30%;
    padding: 5px;
  }
  #section-a .small-fact .im {
    width: 250px;
    height: 175px;
  }

  #section-b {
    display: inline-flex;
    background-color: brown;
    color: white;
  }

  #section-b .box-2{
    padding: 5px;
  }

  #section-b .box-2 .board {
    width: 400px;
    height: 400px;

  }

  #section-b .box-3 {
    padding: 5px;
  }

  #section-b .box-3 .phase .{
    width: 100vs;
    height: auto;
  }

   #section-b .box-4{
    padding: 5px;
  }

#section-b .box-4 .slide1 {
  width: 300px;
  height: 200px;

}
#section-b .box-4 .slide2 {
  width: 60%;
  height: 35%;

}

#ex {
  text-align: center;
  font-weight: bold;
  text-decoration: underline
}

.pink {
  float: left;
  width: 300px;
  padding: 0px;
}
.pi {
  float: left;
  width: 300px;
  height: 300px
  padding: 0px;
}
.lion {
  float: left;
  width: 300px;
  height: 20%;
  padding: 0px;
}
.eldorado {
  float: left;
  padding: 0px;
  height: 50vh;
  width: 65vh;
}

.examples::after {
  content: "";
  clear: both;
  display: table;
}


问:
Does get_dummies() function change the dtype of a column?
I have a data frame column ['Cause'] with dtype as object having the below values :

Cause
Water
Fire
Earthquake
Flood

Now when I am using get_dummies() function on this column, I got 4 additional column as below with binary values:

Water | Fire | Earthquake | Flood

My query is , all these additional 4 columns has a data type as uint8.Do I need to convert it into int64.

答:
You don't need to convert again. While converting it to get_dummies() you can define dtype :

```<code>pd.get_dummies(['Column_name'], dtype=np.int64)
</code>```

Body:
You don't need to convert again. While converting it to get_dummies() you can define dtype :

pd.get_dummies(['Column_name'], dtype=np.int64)


问:
how to switch language from an array with react hooks
i want to change the language of a quote, from French to English or inverse when i click on "lang button", the quote is generate randomly from an array when the page start.
this is my array:

```<code>const quoteData = [
  {
    quoteEn:
      "Three things cannot be long hidden: the sun, the moon, and the truth.",
    quoteFr:
      "Trois choses ne peuvent pas être cachées longtemps : le soleil, la lune et la vérité.",
    author: "Buddha"
  },
  {
    quoteEn:
      "We make a living by what we get, but we make a life by what we give.",
    quoteFr:
      "On vit de ce que l’on obtient. On construit sa vie sur ce que l’on donne.",
    author: "Winston Churchill"
  }

export default quoteData;
</code>```

and this is what i tried:

```<code>import React, { useState } from "react";
import quoteData from "./components/quoteData";
import "./App.css";
import { ReactComponent as Github } from "./icons/github-brands.svg";

function App() {
  const getRandomQuotes = () => {
    const randNumb = Math.floor(Math.random() * quoteData.length);
    return quoteData[randNumb];
  };

  const [quote, setQuote] = useState(getRandomQuotes());
  const [author, setAuthor] = useState(getRandomQuotes().author);
  const [lang, setLang] = useState("En");
  const [nextBtn, setNextBtn] = useState("Next");

  const handleClickLang = () => {
    if (lang === "Fr") {
      setLang("En");
      setNextBtn("Next");
      setQuote(quote.quoteFr);
    } else {
      setLang("Fr");
      setNextBtn("Suivant");
      setQuote(quote.quoteEn);
    }
  };

  return (
    <div id="quote-box">
      <div className="c1">
        <div className="lang">
          <button onClick={handleClickLang} className="changeLang">
            {lang}
          </button>
        </div>
        <div className="card flow">
          <p id="text">{quote}</p>
          <p id="author">{author}</p>
        </div>
      </div>
      <div className="c2">
        <Github id="github" />
        <button onClick={handleClickRandomQuote} id="new-quote">
          {nextBtn}
        </button>
      </div>
    </div>
  );
}

export default App;

</code>```

and i get this error : Error: Objects are not valid as a React child (found: object with keys {quoteEn, quoteFr, author}).

答:
You are storing in your quote state an object (the one you randomly select from your array of quoteData), not the string for the quote. This is not bad, as you also want to show the author of the random quote you randomly selected.

Also, when you do:

```<code>const [quote, setQuote] = useState(getRandomQuotes());
const [author, setAuthor] = useState(getRandomQuotes().author);
</code>```

You have to take into account that the first execution of getRandomQuotes will return a random quote that doesn't have to coincide with the second call to getRandomQuotes to get the author. This could cause that your data (quote and author) are not in sync.

So, it seems that storing the author separately from the quote is not necessary. Taking all this into account, you could do something like:

```<code>function App() {
  const getRandomQuotes = () => {
    const randNumb = Math.floor(Math.random() * quoteData.length);
    return quoteData[randNumb];
  };

  const [quote, setQuote] = useState(getRandomQuotes());
  const [lang, setLang] = useState("En");
  const [nextBtn, setNextBtn] = useState("Next");

  const handleClickLang = () => {
    if (lang === "Fr") {
      setLang("En");
      setNextBtn("Next");
    } else {
      setLang("Fr");
      setNextBtn("Suivant");
    }
  };

  return (
    <div id="quote-box">
      <div className="c1">
        <div className="lang">
          <button onClick={handleClickLang} className="changeLang">
            {lang}
          </button>
        </div>
        <div className="card flow">
          <p id="text">{quote[`quote${lang}`]}</p>
          <p id="author">{quote.author}</p>
        </div>
      </div>
      <div className="c2">
        <Github id="github" />
        <button onClick={handleClickRandomQuote} id="new-quote">
          {nextBtn}
        </button>
      </div>
    </div>
  );
}
</code>```

Body:
i want to change the language of a quote, from French to English or inverse when i click on "lang button", the quote is generate randomly from an array when the page start.
this is my array:

const quoteData = [
  {
    quoteEn:
      "Three things cannot be long hidden: the sun, the moon, and the truth.",
    quoteFr:
      "Trois choses ne peuvent pas être cachées longtemps : le soleil, la lune et la vérité.",
    author: "Buddha"
  },
  {
    quoteEn:
      "We make a living by what we get, but we make a life by what we give.",
    quoteFr:
      "On vit de ce que l’on obtient. On construit sa vie sur ce que l’on donne.",
    author: "Winston Churchill"
  }

export default quoteData;

and this is what i tried:

import React, { useState } from "react";
import quoteData from "./components/quoteData";
import "./App.css";
import { ReactComponent as Github } from "./icons/github-brands.svg";

function App() {
  const getRandomQuotes = () => {
    const randNumb = Math.floor(Math.random() * quoteData.length);
    return quoteData[randNumb];
  };

  const [quote, setQuote] = useState(getRandomQuotes());
  const [author, setAuthor] = useState(getRandomQuotes().author);
  const [lang, setLang] = useState("En");
  const [nextBtn, setNextBtn] = useState("Next");

  const handleClickLang = () => {
    if (lang === "Fr") {
      setLang("En");
      setNextBtn("Next");
      setQuote(quote.quoteFr);
    } else {
      setLang("Fr");
      setNextBtn("Suivant");
      setQuote(quote.quoteEn);
    }
  };

  return (

          <button onClick={handleClickLang} className="changeLang">
            {lang}
          </button>

{quote}

{author}

        <Github id="github" />
        <button onClick={handleClickRandomQuote} id="new-quote">
          {nextBtn}
        </button>

  );
}

export default App;

and i get this error : Error: Objects are not valid as a React child (found: object with keys {quoteEn, quoteFr, author}).

Body:
You are storing in your quote state an object (the one you randomly select from your array of quoteData), not the string for the quote. This is not bad, as you also want to show the author of the random quote you randomly selected.

Also, when you do:

const [quote, setQuote] = useState(getRandomQuotes());
const [author, setAuthor] = useState(getRandomQuotes().author);

You have to take into account that the first execution of getRandomQuotes will return a random quote that doesn't have to coincide with the second call to getRandomQuotes to get the author. This could cause that your data (quote and author) are not in sync.

So, it seems that storing the author separately from the quote is not necessary. Taking all this into account, you could do something like:

function App() {
  const getRandomQuotes = () => {
    const randNumb = Math.floor(Math.random() * quoteData.length);
    return quoteData[randNumb];
  };

  const [quote, setQuote] = useState(getRandomQuotes());
  const [lang, setLang] = useState("En");
  const [nextBtn, setNextBtn] = useState("Next");

  const handleClickLang = () => {
    if (lang === "Fr") {
      setLang("En");
      setNextBtn("Next");
    } else {
      setLang("Fr");
      setNextBtn("Suivant");
    }
  };

  return (
    <div id="quote-box">
      <div className="c1">
        <div className="lang">
          <button onClick={handleClickLang} className="changeLang">
            {lang}
          </button>
        </div>
        <div className="card flow">
          <p id="text">{quote[`quote${lang}`]}</p>
          <p id="author">{quote.author}</p>
        </div>
      </div>
      <div className="c2">
        <Github id="github" />
        <button onClick={handleClickRandomQuote} id="new-quote">
          {nextBtn}
        </button>
      </div>
    </div>
  );
}


问:
Java function that throws RuntimeException
I'm looking at some code and it's confusing me as I find it strange how a function's purpose is just to throw an error, although I'm sure there are reasons where it is helpful (at least that is what I think it's doing). My understanding of it is that if the arguments are of type String are passed into the function putExtra then a RuntimeExeption is thrown. Is my understanding correct? Below is the code,

```<code>@RecentlyNonNull
public Intent putExtra(String name, String value) {
    throw new RuntimeException("Stub!");
}

public static final String ACTION_ID = "ACTION_ID";
Intent actionIntent = new Intent(this, LoginActivity.class);
actionIntent.putExtra(Constants.ACTION_ID, userId); //Where userId is also a string
</code>```

If my understanding is correct what would be the reason behind this? Wouldn't an error be thrown automatically if any one of the arguments to the putExtra function is not of type String?

答: This RuntimeExeption might have a whole other reason (please add the stack-trace). And even when looking at the method signatures, it's not always String value. The first argument must be String, because it is the name - while the second one argument is for the value and can have various types (not any type). See work with breakpoints, which might rather explain why it crashes.

Body:
I'm looking at some code and it's confusing me as I find it strange how a function's purpose is just to throw an error, although I'm sure there are reasons where it is helpful (at least that is what I think it's doing). My understanding of it is that if the arguments are of type String are passed into the function putExtra then a RuntimeExeption is thrown. Is my understanding correct? Below is the code,

@RecentlyNonNull
public Intent putExtra(String name, String value) {
    throw new RuntimeException("Stub!");
}

public static final String ACTION_ID = "ACTION_ID";
Intent actionIntent = new Intent(this, LoginActivity.class);
actionIntent.putExtra(Constants.ACTION_ID, userId); //Where userId is also a string

If my understanding is correct what would be the reason behind this? Wouldn't an error be thrown automatically if any one of the arguments to the putExtra function is not of type String?


问:
iOS SDK broken ever after reinstall UIKit and Foundation frameworks not found
For the pch file I get these errors:

/Users/matt/Programming/iPhone Monkey Curling lite/iPhone_Monkey_Curling_Prefix.pch:6:34: error: Foundation/Foundation.h: No such file or directory

/Users/matt/Programming/iPhone Monkey Curling lite/iPhone_Monkey_Curling_Prefix.pch:7:24: error: UIKit/UIKit.h: No such file or directory

Here's the file as it is by default:

```<code>//
// Prefix header for all source files of the 'iPhone Monkey Curling' target in the 'iPhone Monkey Curling' project
//

#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#endif
</code>```

I reinstalled Xcode and the iOS SDK but that did not fix the problem. This problem occurred after adding the iAd framework to one of my projects but all of my projects won't compile.

I'm using the latest SDK (4.1).

The frameworks are there in the project. For some reason, when I try to add a new framework, it lists the OS X ones in an iOS project.

Thank you for any help.

答: This happened for me in xcode 4, it would build fine for debug but not release. Similar to your fix, the prefix header for release was pointing to UIKit.h instead of my .pch file.</p>

Body:
For the pch file I get these errors:

/Users/matt/Programming/iPhone Monkey Curling lite/iPhone_Monkey_Curling_Prefix.pch:6:34: error: Foundation/Foundation.h: No such file or directory

/Users/matt/Programming/iPhone Monkey Curling lite/iPhone_Monkey_Curling_Prefix.pch:7:24: error: UIKit/UIKit.h: No such file or directory

Here's the file as it is by default:

//
// Prefix header for all source files of the 'iPhone Monkey Curling' target in the 'iPhone Monkey Curling' project
//

#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#endif

I reinstalled Xcode and the iOS SDK but that did not fix the problem. This problem occurred after adding the iAd framework to one of my projects but all of my projects won't compile.

I'm using the latest SDK (4.1).

The frameworks are there in the project. For some reason, when I try to add a new framework, it lists the OS X ones in an iOS project.

Thank you for any help.

ContentLicense: CC BY-SA 3.0


问:
Axios 'put' request passing array as empty value
This is my 'PUT' request using Axios.

The problem is: the data array inside the variable userdata is passing as an empty value to the backend.
but the console.log just before the api call shows the correct value.

```<code>let userdata = {
  "epoch_time": "1581850307",
  "auth_key": "b22dfe2f8d93445c26f5c261f6a426d2",
  "user_mode": " driver",
  "action": "location",
  "data": [{
    "lat": 20.123657,
    "lon": 80.12453
  }, {
    "lat": 20.123654,
    "lon": 80.12456
  }]
}
</code>```

This is the api call..

```<code>export const locationTrackingApi = (userdata) => {
  console.log("locationTrackingApi data", userdata);
  return dispatch => {
    axios({
      method: 'PUT',
      url: BASEURL,
      data: userdata
    })
      .then(function (response) {
        console.log("locationTrackingApi response", response);
      }).catch(function (error) {
        dispatch(apiLoadingIndicator(false));
        console.log(error);
      })
  };

}
</code>```

答:
Try this.

  axios.put(BASEURL,{
    userdata
  })
  .then(response => console.log(response.data))
  .catch(error => console.log(error))
```

Body:
This is my 'PUT' request using Axios.

The problem is: the data array inside the variable userdata is passing as an empty value to the backend.
but the console.log just before the api call shows the correct value.

let userdata = {
  "epoch_time": "1581850307",
  "auth_key": "b22dfe2f8d93445c26f5c261f6a426d2",
  "user_mode": " driver",
  "action": "location",
  "data": [{
    "lat": 20.123657,
    "lon": 80.12453
  }, {
    "lat": 20.123654,
    "lon": 80.12456
  }]
}

This is the api call..

export const locationTrackingApi = (userdata) => {
  console.log("locationTrackingApi data", userdata);
  return dispatch => {
    axios({
      method: 'PUT',
      url: BASEURL,
      data: userdata
    })
      .then(function (response) {
        console.log("locationTrackingApi response", response);
      }).catch(function (error) {
        dispatch(apiLoadingIndicator(false));
        console.log(error);
      })
  };

}


问:
Why my ViewModel is still alive after I replaced current fragment in Android?
Example, If I replaced 'fragmentA' with 'fragmentB', the 'viewModelA' of fragmentA is still live. why ?

onCreate() of Fragment

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    viewModel = ViewModelProvider.NewInstanceFactory().create(InvoicesViewModel::class.java)
}
</code>```

ViewModel

```<code>class InvoicesViewModel : ViewModel() {

init {
    getInvoices()
}

private fun getInvoices() {

    viewModelScope.launch {

        val response = safeApiCall() {
            // Call API here
        }

        while (true) {
            delay(1000)
            println("Still printing although the fragment of this viewModel destroied")
        }

        if (response is ResultWrapper.Success) {
            // Do work here
        }
    }
}
}
</code>```

This method used to replace fragment

```<code>fun replaceFragment(activity: Context, fragment: Fragment, TAG: String) {
    val myContext = activity as AppCompatActivity
    val transaction = myContext.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.content_frame, fragment, TAG)
    transaction.commitNow()
}
</code>```

You will note the while loop inside the Coroutine still work although after replace fragment to another fragment.

答:
this is about your implementation of ViewModelProvider.
use this way for creating your viewModel.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModel = ViewModelProvider(this).get(InvoicesViewModel::class.java)
}
```

in this way you give your fragment as live scope of view model.

Body:
Example, If I replaced 'fragmentA' with 'fragmentB', the 'viewModelA' of fragmentA is still live. why ?

onCreate() of Fragment

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    viewModel = ViewModelProvider.NewInstanceFactory().create(InvoicesViewModel::class.java)
}

ViewModel

class InvoicesViewModel : ViewModel() {

init {
    getInvoices()
}

private fun getInvoices() {

    viewModelScope.launch {

        val response = safeApiCall() {
            // Call API here
        }

        while (true) {
            delay(1000)
            println("Still printing although the fragment of this viewModel destroied")
        }

        if (response is ResultWrapper.Success) {
            // Do work here
        }
    }
}
}

This method used to replace fragment

fun replaceFragment(activity: Context, fragment: Fragment, TAG: String) {
    val myContext = activity as AppCompatActivity
    val transaction = myContext.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.content_frame, fragment, TAG)
    transaction.commitNow()
}

You will note the while loop inside the Coroutine still work although after replace fragment to another fragment.

Body:
this is about your implementation of ViewModelProvider.
use this way for creating your viewModel.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModel = ViewModelProvider(this).get(InvoicesViewModel::class.java)
}

in this way you give your fragment as live scope of view model.


问:
Symfony authentification form does not run
I have the form type :

```<code>class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ->add('email')
            ->add('username', TextType::class)
            ->add('password', PasswordType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}
</code>```

The entity User :

```<code>    class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Email()
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min=2, minMessage="Nom trop petit")
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min=4, minMessage="Mot de passe trop petit")
     */
    private $password;

    /**
     * @Assert\EqualTo(propertyPath="password", message="Le mot de passe ne correspond pas")
     */
    public $confirm_password;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;
        return $this;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;
        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;
        return $this;
    }

    /**
     * @inheritDoc
     */
    public function getRoles()
    {
        return ["ROLE_USER"];
    }

    /**
     * @inheritDoc
     */
    public function getSalt()
    {
        // TODO: Implement getSalt() method.
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
        // TODO: Implement eraseCredentials() method.
    }
}
</code>```

The controller :

```<code>/**
 * @Route("/login", name="login")
 */
public function login()
{
    // the identification is done thanks Symfony security configuration

    return $this->render("security/login.html.twig", [
        "form" => $this->createForm(UserType::class )->createView()
    ]);
}
</code>```

The security firewall configuration file :

```<code>firewalls:
    main:
        anonymous: lazy
        provider: in_database
        form_login:
            login_path: security_login
            check_path: security_login
        logout:
            path: security_logout
            target: home
</code>```

And the view :

```<code>{% extends 'base.html.twig' %}
{% block title %}Hello SecurityController!{% endblock %}
{% block body %}
    <h1>Login</h1>
    <form action="{{ path('security_login') }}" method="post">
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Nom" required name="_username">
        </div>
        <div class="form-group">
            <input type="password" class="form-control" placeholder="Mot de passe" required name="_password">
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-success">Connexion</button>
        </div>
    </form>
{% endblock %}
</code>```

With this code the identication runs.

Now, I want use the Twig form tags in the Twig file as follows:

```<code>{{ form_start(form) }}
{{ form_row(form.username, {"attr": {"placeholder": "Nom", "name": "_username", "required": "required"}, "label": "Nom" }) }}
{{ form_row(form.password, {"attr": {"placeholder": "Mot de passe", "name": "_password", "required": "required"}, "label": "Mot de passe" }) }}
<button type="submit" class="btn btn-success">Valider</button>
{{ form_end(form) }}
</code>```

But when I use this code, I obtain the error message :

The key "_username" must be a string, "NULL" given.

Normally, my forms run correctly. Why, here, doesn't the form work?

Thank for yours answers.

答:
I think your forgot to handle your form request in the controller, to do that you need to inject Symfony\Component\HttpFoundation\Request argument to your login() method, an example below :

```<code>public function login(Request $request)
{
    $form->handleRequest($request);

    if (true === $form->isSubmitted() && true === $form->isValid()) {
        // stuff
    }
}
</code>```

Also in firewall, please edit form_login, the route path are incorrects since in controller annotation you specified name="login":

```<code>form_login:
    login_path: login
    check_path: login
</code>```

Body:
I have the form type :

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ->add('email')
            ->add('username', TextType::class)
            ->add('password', PasswordType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

The entity User :

    class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Email()
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min=2, minMessage="Nom trop petit")
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min=4, minMessage="Mot de passe trop petit")
     */
    private $password;

    /**
     * @Assert\EqualTo(propertyPath="password", message="Le mot de passe ne correspond pas")
     */
    public $confirm_password;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;
        return $this;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;
        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;
        return $this;
    }

    /**
     * @inheritDoc
     */
    public function getRoles()
    {
        return ["ROLE_USER"];
    }

    /**
     * @inheritDoc
     */
    public function getSalt()
    {
        // TODO: Implement getSalt() method.
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
        // TODO: Implement eraseCredentials() method.
    }
}

The controller :

/**
 * @Route("/login", name="login")
 */
public function login()
{
    // the identification is done thanks Symfony security configuration

    return $this->render("security/login.html.twig", [
        "form" => $this->createForm(UserType::class )->createView()
    ]);
}

The security firewall configuration file :

firewalls:
    main:
        anonymous: lazy
        provider: in_database
        form_login:
            login_path: security_login
            check_path: security_login
        logout:
            path: security_logout
            target: home

And the view :

{% extends 'base.html.twig' %}
{% block title %}Hello SecurityController!{% endblock %}
{% block body %}

Login

    <form action="{{ path('security_login') }}" method="post">

            <input type="text" class="form-control" placeholder="Nom" required name="_username">

            <input type="password" class="form-control" placeholder="Mot de passe" required name="_password">

            <button type="submit" class="btn btn-success">Connexion</button>

    </form>
{% endblock %}

With this code the identication runs.

Now, I want use the Twig form tags in the Twig file as follows:

{{ form_start(form) }}
{{ form_row(form.username, {"attr": {"placeholder": "Nom", "name": "_username", "required": "required"}, "label": "Nom" }) }}
{{ form_row(form.password, {"attr": {"placeholder": "Mot de passe", "name": "_password", "required": "required"}, "label": "Mot de passe" }) }}
<button type="submit" class="btn btn-success">Valider</button>
{{ form_end(form) }}

But when I use this code, I obtain the error message :

The key "_username" must be a string, "NULL" given.

Normally, my forms run correctly. Why, here, doesn't the form work?

Thank for yours answers.

Body:
I think your forgot to handle your form request in the controller, to do that you need to inject Symfony\Component\HttpFoundation\Request argument to your login() method, an example below :

public function login(Request $request)
{
    $form->handleRequest($request);

    if (true === $form->isSubmitted() && true === $form->isValid()) {
        // stuff
    }
}

Also in firewall, please edit form_login, the route path are incorrects since in controller annotation you specified name="login":

form_login:
    login_path: login
    check_path: login


问:
isEnabled() function not working in Protractor
I want to select a date in calendar picker using protractor. Below is the snippet of code, that I have written in my script:

```<code>if (dat <= 24) {
    var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[1]"));
} else {
    var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[1]"));
    if (us_dat.isEnabled() == false) {
        var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[2]"));
    }
}

us_dat.click();
browser.sleep(1000);
</code>```

where dat is a variable, where I have stored the date that needs to be selected in the calendar picker.

During debugging, I found that, when the date is greater than 24, the code is checking the "if" block present under the "else" block. However, it returns a value of undefined and hence it is skipping the action written inside the "if" block. May I know why it is returning a value of "undefined", instead of true or false please?

Please let me know if any further details are required.

答:
```<code>try to use this method will work

isEnable: function (element) {
        return element.isEnabled();
    },
</code>```

Body:
I want to select a date in calendar picker using protractor. Below is the snippet of code, that I have written in my script:

if (dat <= 24) {
    var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[1]"));
} else {
    var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[1]"));
    if (us_dat.isEnabled() == false) {
        var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[2]"));
    }
}

us_dat.click();
browser.sleep(1000);

where dat is a variable, where I have stored the date that needs to be selected in the calendar picker.

During debugging, I found that, when the date is greater than 24, the code is checking the "if" block present under the "else" block. However, it returns a value of undefined and hence it is skipping the action written inside the "if" block. May I know why it is returning a value of "undefined", instead of true or false please?

Please let me know if any further details are required.


问:
How to get the string from its String.hashCode() value?
I need to somehow get the text from its hash in java.
I have this code:

String myString = new String("creashaks organzine");
int hashCode = myString.hashCode();
System.out.println("Hash:" + hashCode);
```

The result of this code will be 0.
But the hash of "pollinating sandboxes" string will also be 0.

There might be collisions, for example with "creashaks organzine" and "pollinating sandboxes" and I want to find collisions like in this case.

答:
This is a very interesting thing. Regarding the specification in https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#hashCode() says that the hashCode is calculated from the string content but the example seems to shows that is not true for the first string:

```<code>class Main
{
    public static void main(String[] args)
    {
        String myString1 = "creashaks organzine";
        String myString2 = "crsomething else";
        String myString3 = "crsomething else";

        System.out.println("Hash1:" + myString1.hashCode());
        System.out.println("Hash2:" + myString2.hashCode());
        System.out.println("Hash3:" + myString3.hashCode());
    }
}
</code>```

Outputs:

```<code>Hash1:0
Hash2:444616526
Hash3:444616526
</code>```

But when I modify the string, then I get a different output:

```<code>String myString1 = "creashaks organzine...";
System.out.println("Hash1:" + myString1.hashCode());
</code>```

Outputs:

```<code>Hash1:45678
</code>```

So it seems that somebody tricked us by giving a very rare example string that produced exactly the "0" as output. Here you see that the hashCode is not very unique, so you cannot use is safely to compare strings.

Coming back to your initial question: The hashCode is a number with reduced details, so you cannot calculate it back to the original string. This applies to all hash codes.

Hash codes are so often used in server side databases instead of real password strings. They can be compared but not reconstructed.

Body:
I need to somehow get the text from its hash in java.
I have this code:

String myString = new String("creashaks organzine");
int hashCode = myString.hashCode();
System.out.println("Hash:" + hashCode);

The result of this code will be 0.
But the hash of "pollinating sandboxes" string will also be 0.

There might be collisions, for example with "creashaks organzine" and "pollinating sandboxes" and I want to find collisions like in this case.

Body:
This is a very interesting thing. Regarding the specification in https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#hashCode() says that the hashCode is calculated from the string content but the example seems to shows that is not true for the first string:

class Main
{
    public static void main(String[] args)
    {
        String myString1 = "creashaks organzine";
        String myString2 = "crsomething else";
        String myString3 = "crsomething else";

        System.out.println("Hash1:" + myString1.hashCode());
        System.out.println("Hash2:" + myString2.hashCode());
        System.out.println("Hash3:" + myString3.hashCode());
    }
}

Outputs:

Hash1:0
Hash2:444616526
Hash3:444616526

But when I modify the string, then I get a different output:

String myString1 = "creashaks organzine...";
System.out.println("Hash1:" + myString1.hashCode());

Outputs:

Hash1:45678

So it seems that somebody tricked us by giving a very rare example string that produced exactly the "0" as output. Here you see that the hashCode is not very unique, so you cannot use is safely to compare strings.

Coming back to your initial question: The hashCode is a number with reduced details, so you cannot calculate it back to the original string. This applies to all hash codes.

Hash codes are so often used in server side databases instead of real password strings. They can be compared but not reconstructed.


问:
rails view with bootstrap nav-tabs
I have two models. parent, and child. each parent has many children

```<code>#parent model
class Parent < ApplicationRecord
  has_many :children
end

#child model
class Child < ApplicationRecord
  belongs_to :parent
end
</code>```

I want to use bootstrap nav-tabs, each tab should show parent's children only. any help.

答:
First thing do select when id in parent table = children.parent.id

in ParentController

```<code>@parent_children = Parent.select('DISTINCT name').joins(:children).where('id' = 'children.parent.id')
</code>```

@parent_children return unique name of parent has children

Title: rails view with bootstrap nav-tabs

Body:
I have two models. parent, and child. each parent has many children

#parent model
class Parent < ApplicationRecord
  has_many :children
end

#child model
class Child < ApplicationRecord
  belongs_to :parent
end

I want to use bootstrap nav-tabs, each tab should show parent's children only. any help.

Body:
First thing do select when id in parent table = children.parent.id

in ParentController

@parent_children = Parent.select('DISTINCT name').joins(:children).where('id' = 'children.parent.id')

@parent_children return unique name of parent has children


问:
Flutter Bloc - Widget tree growing endlessy
When I'm going back from the final view to my "initial view" every State of all 3 BlocProviders is being saved.

See Widget tree:

My Code is linked here:
GIST

I don't understand what I am missing, on first run everything works fine.

However, when I go back to InitialView when I'm in GameView, set everything up again and move to the GameModeSelectionView again, its getting called multiple times (States are somehow saved instead of dumped??)(1):

```<code>flutter: State of GameSelectionState GameSelectionInitial
flutter: State of GameSelectionState GameSelectionStart
flutter: State of QuestionState StopQuestion
flutter: OK?
flutter: State of GameSelectionState GameSelectionStart
flutter: State of QuestionState StopQuestion
flutter: OK?
flutter: State of GameSelectionState GameSelectionStart
flutter: State of QuestionState StopQuestion
flutter: OK?
flutter: State of GameSelectionState GameSelectionInitial
</code>```

This process grows with each iteration (1)

I am using the flutter_bloc dependency:
https://pub.dev/packages/flutter_bloc

答:
I fixed the issue using MaterialPageRoute onGenerateRoute (since I need to route dynamically)

I replaced the code in my Buttons onPressed method to like:

```<code>Navigator.of(context).pushReplacementNamed(
              GameModeSelectionView.routeName,
              arguments: players);
</code>```

Works like a charm and no more growing tree.

Body:
When I'm going back from the final view to my "initial view" every State of all 3 BlocProviders is being saved.

See Widget tree:

My Code is linked here:
GIST

I don't understand what I am missing, on first run everything works fine.

However, when I go back to InitialView when I'm in GameView, set everything up again and move to the GameModeSelectionView again, its getting called multiple times (States are somehow saved instead of dumped??)(1):

flutter: State of GameSelectionState GameSelectionInitial
flutter: State of GameSelectionState GameSelectionStart
flutter: State of QuestionState StopQuestion
flutter: OK?
flutter: State of GameSelectionState GameSelectionStart
flutter: State of QuestionState StopQuestion
flutter: OK?
flutter: State of GameSelectionState GameSelectionStart
flutter: State of QuestionState StopQuestion
flutter: OK?
flutter: State of GameSelectionState GameSelectionInitial

This process grows with each iteration (1)

I am using the flutter_bloc dependency:
https://pub.dev/packages/flutter_bloc

Body:
I fixed the issue using MaterialPageRoute onGenerateRoute (since I need to route dynamically)

I replaced the code in my Buttons onPressed method to like:

Navigator.of(context).pushReplacementNamed(
              GameModeSelectionView.routeName,
              arguments: players);

Works like a charm and no more growing tree.


问:
How could I solve this error please (IndexError: list index out of range)?
I have the following work in Python. I'm trying to solve an equation by using Python and showing the results by plotting it. When I run my following below code, I got this error below:

The error:

```<code>Traceback (most recent call last):
  File "C:\Users\raineen\Desktop\Raneen_Python\Sigma_theta_c.py", line 44, in <module>
    segma.append((((Tt*Ct[count])/(2*t0*lambda1))*((m.log(item*r))**Nt[count]))+(((Tb*Cb)/(2*t0*lambda1))*((m.log(item*r))**Nb))+((Tt*Ct[count])/(t0*lambda1*(Nt[count]+1)))*((m.log(item*r))**(Nt[count]+1)-(m.log(item*R0))**(Nt[count]+1))+ ((Tb*Cb)/(t0*lambda1*(Nb+1)))*((m.log(item*r))**(Nb+1)-(m.log(item*R0))**(Nb+1)))
IndexError: list index out of range
</code>```

I have three lists and I'm looping through them at the same time, they are:

```<code>t = [x/100 for x in range(1, 201)] # [0.01,0.02,0.02,..........,2]

Ct=  [126.0, 127.82549463360013, 129.67743712955985, 131.55621066590138, 133.46220397215035, 135.39581140976628, 137.35743305373825, 139.34747477536274, 141.36634832622116, 143.41447142337327]

a=  [39.960039960039964, 19.960079840319363, ..........]
</code>```

Could I get any help to fix this problem, please?

The Python

```<code>import math as m
import matplotlib.pyplot as plt

lambda1 = 1
t = [x/100 for x in range(1, 201)]
t0 = 2
Tt = 1.5
Kt = 126
Kb = 1261
Rt = 5
Nt = [x/10 for x in range(0, 10)]
Nb = 0.36
Tb = 0.5
r = 6.5

R0 = Rt + t0
z = 2/m.sqrt(3)
#Ct = Kt*(z**Nt)
Cb = Kb*(z**Nb)

print('t= ', t)
print('Nt= ', Nt)
Ct = []
for n in Nt:
    Ct.append(Kt*(z**n))

Rm = []
for j in t:
    Rm.append(5+(j/2))

print('Rm= ',Rm)
print('Ct= ',Ct)

a = []
for k,i in zip(Rm,t):
    a.append(t0/(k*i))
    print(k, i)
print('a= ',a)

segma = []
for count, item in enumerate(a):
    segma.append((((Tt*Ct[count])/(2*t0*lambda1))*((m.log(item*r))**Nt[count]))+(((Tb*Cb)/(2*t0*lambda1))*((m.log(item*r))**Nb))+((Tt*Ct[count])/(t0*lambda1*(Nt[count]+1)))*((m.log(item*r))**(Nt[count]+1)-(m.log(item*R0))**(Nt[count]+1))+ ((Tb*Cb)/(t0*lambda1*(Nb+1)))*((m.log(item*r))**(Nb+1)-(m.log(item*R0))**(Nb+1)))

print('Sigma_theta_c = ', segma)

##for i in segma:
##    print(i)

plt.plot(t,segma)

plt.xlabel('t')
plt.ylabel('Sigma_theta_c')

plt.show()
</code>```

This is below the equation:

答:
I have checked your code and the problem is that the length of Ct and Nt arrays is 10 while the length of list a is 200.
In this case you are enumerating a list a and using count to access the elements in lists Ct and Nt which causes IndexError.

Body:
I have the following work in Python. I'm trying to solve an equation by using Python and showing the results by plotting it. When I run my following below code, I got this error below:

The error:

Traceback (most recent call last):
  File "C:\Users\raineen\Desktop\Raneen_Python\Sigma_theta_c.py", line 44, in <module>
    segma.append((((Tt*Ct[count])/(2*t0*lambda1))*((m.log(item*r))**Nt[count]))+(((Tb*Cb)/(2*t0*lambda1))*((m.log(item*r))**Nb))+((Tt*Ct[count])/(t0*lambda1*(Nt[count]+1)))*((m.log(item*r))**(Nt[count]+1)-(m.log(item*R0))**(Nt[count]+1))+ ((Tb*Cb)/(t0*lambda1*(Nb+1)))*((m.log(item*r))**(Nb+1)-(m.log(item*R0))**(Nb+1)))
IndexError: list index out of range

I have three lists and I'm looping through them at the same time, they are:

t = [x/100 for x in range(1, 201)] # [0.01,0.02,0.02,..........,2]

Ct=  [126.0, 127.82549463360013, 129.67743712955985, 131.55621066590138, 133.46220397215035, 135.39581140976628, 137.35743305373825, 139.34747477536274, 141.36634832622116, 143.41447142337327]

a=  [39.960039960039964, 19.960079840319363, ..........]

Could I get any help to fix this problem, please?

The Python

import math as m
import matplotlib.pyplot as plt

lambda1 = 1
t = [x/100 for x in range(1, 201)]
t0 = 2
Tt = 1.5
Kt = 126
Kb = 1261
Rt = 5
Nt = [x/10 for x in range(0, 10)]
Nb = 0.36
Tb = 0.5
r = 6.5

R0 = Rt + t0
z = 2/m.sqrt(3)
#Ct = Kt*(z**Nt)
Cb = Kb*(z**Nb)

print('t= ', t)
print('Nt= ', Nt)
Ct = []
for n in Nt:
    Ct.append(Kt*(z**n))

Rm = []
for j in t:
    Rm.append(5+(j/2))

print('Rm= ',Rm)
print('Ct= ',Ct)

a = []
for k,i in zip(Rm,t):
    a.append(t0/(k*i))
    print(k, i)
print('a= ',a)

segma = []
for count, item in enumerate(a):
    segma.append((((Tt*Ct[count])/(2*t0*lambda1))*((m.log(item*r))**Nt[count]))+(((Tb*Cb)/(2*t0*lambda1))*((m.log(item*r))**Nb))+((Tt*Ct[count])/(t0*lambda1*(Nt[count]+1)))*((m.log(item*r))**(Nt[count]+1)-(m.log(item*R0))**(Nt[count]+1))+ ((Tb*Cb)/(t0*lambda1*(Nb+1)))*((m.log(item*r))**(Nb+1)-(m.log(item*R0))**(Nb+1)))

print('Sigma_theta_c = ', segma)

##for i in segma:
##    print(i)

plt.plot(t,segma)

plt.xlabel('t')
plt.ylabel('Sigma_theta_c')

plt.show()

This is below the equation:


问:
Files deleted after push in GitHub remote repository
I have my first Git repository that I have created online named myName/python-algorithms.

It was containing many Python scripts. I tried to add a file test.py from my local Ubuntu terminal with the commands:

```<code>git init
git config user.name "myName"
git config user.e-mail "myEmail@myEmail.se"
git add test.py
git commit -m "some init msg"
git remote add origin https://github.com/myname/Python_Algorithms.git
git remote -v
git push -f origin master
</code>```

which deleted all my Python scripts and replaced them with the file test.py on GitHub.

Any idea how I can get back my scripts that were deleted?

答:
FIXED: Thanks to torek comment, I fixed it as follows. From:

```<code>https://api.github.com/repos/myName/Python_Algorithms/events
</code>```

I found the old HASH_ID, before the force push happened. Then I went to the link:

```<code>https://github.com/myNAme/Python_Algorithms/commit/HASH_ID
</code>```

and I managed with Browse files and went back to my files.

Thanks toreks

Body:
I have my first Git repository that I have created online named myName/python-algorithms.

It was containing many Python scripts. I tried to add a file test.py from my local Ubuntu terminal with the commands:

git init
git config user.name "myName"
git config user.e-mail "myEmail@myEmail.se"
git add test.py
git commit -m "some init msg"
git remote add origin https://github.com/myname/Python_Algorithms.git
git remote -v
git push -f origin master

which deleted all my Python scripts and replaced them with the file test.py on GitHub.

Any idea how I can get back my scripts that were deleted?

Body:
FIXED: Thanks to torek comment, I fixed it as follows. From:

https://api.github.com/repos/myName/Python_Algorithms/events

I found the old HASH_ID, before the force push happened. Then I went to the link:

https://github.com/myNAme/Python_Algorithms/commit/HASH_ID

and I managed with Browse files and went back to my files.

Thanks toreks


问:
Is there replacement for cat on Windows
I need to join two binary files with a *.bat script on Windows.

How can I achieve that?

答:
You can use copy /b like this:

```<code>copy /b file1+file2 destfile
</code>```

OwnerDisplayName: Artem Tikhomirov

Title: Is there replacement for cat on Windows

LastEditorDisplayName: Greg Hewgill

Body:
You can use copy /b like this:

copy /b file1+file2 destfile

OwnerDisplayName: Greg Hewgill

ContentLicense: CC BY-SA 2.5


答:
General way to solve similar problems like this - check out length of the lists you are accessing, creating. Could you share full equations and your domain model? What exactly are you solving? What's the desired input and output?

len(t) # 200

len(segma) # 10

plt.plot(segma) works and actually creates the plot

Title: How could I solve this error please (IndexError: list index out of range)?


问:
Is anybody else getting errors when upgrading to com.google.android.material:material:1.1.0?
I was upgrading my material library in my Gradle file and suddenly I get this error.

```<code>\material-1.2.0-alpha04\res\values\values.xml:3360:5-3382:23: AAPT: error: duplicate value for resource 'attr/animationMode' with config ''.
</code>```

I have already changed all libraries to androidX. Is there somebody who faces the same problem?

答:
Make sure you are on either all Android X, or all Support Library. If you're moving to Android X, make sure you have

```<code>android.useAndroidX=true
android.enableJetifier=true
</code>```

set to true in your gradle.properties file.

Body:
I was upgrading my material library in my Gradle file and suddenly I get this error.

\material-1.2.0-alpha04\res\values\values.xml:3360:5-3382:23: AAPT: error: duplicate value for resource 'attr/animationMode' with config ''.

I have already changed all libraries to androidX. Is there somebody who faces the same problem?

Body:
Make sure you are on either all Android X, or all Support Library. If you're moving to Android X, make sure you have

android.useAndroidX=true
android.enableJetifier=true

set to true in your gradle.properties file.


问:
Regexp to match http header format with "g_regex_match_simple"
I'm trying to match HTTP header format in C using glib's g_regex_match_simple:

```<code>static const char header_regex[] = "/([\\w-]+): (\\w+)";

...

const char header[] = "Test: header1";
if (g_regex_match_simple(header_regex, header, 0, 0))
{
    headers[index] = g_strdup(header);
    index++;
}
else
{
    error_setg(errp, "%s is not a valid http header format", header);
    goto cleanup;
}
</code>```

I'm getting FALSE out of g_regex_match_simple() even though "Test: header1" should be valid.

What am I missing?

I tried the answer in
Regexp to match logcat brief format with g_regex_match_simple
but it didn't work for me.

Ideas?

答:
The following are compiled with clang -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include youe_file.c -lgobject-2.0 -lglib-2.0.

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

static const char header_regex[] = "([\\w-]+): (\\w+)";

int main()
{
const char header[] = "Test: header1";
if (g_regex_match_simple(header_regex, header, 0, 0)){
 printf("+\n");}
else {
    printf("-\n");
}

return 0;
}
</code>```

And it gives a positive match. The difference were in regexp pattern. I've removed a slash.

Original string static const char header_regex[] = "/([\\w-]+): (\\w+)";
needs to be static const char header_regex[] = "([\\w-]+): (\\w+)";

```<code>                                   ^
                                   |
                                no slash here
</code>```

Body:
I'm trying to match HTTP header format in C using glib's g_regex_match_simple:

static const char header_regex[] = "/([\\w-]+): (\\w+)";

...

const char header[] = "Test: header1";
if (g_regex_match_simple(header_regex, header, 0, 0))
{
    headers[index] = g_strdup(header);
    index++;
}
else
{
    error_setg(errp, "%s is not a valid http header format", header);
    goto cleanup;
}

I'm getting FALSE out of g_regex_match_simple() even though "Test: header1" should be valid.

What am I missing?

I tried the answer in
Regexp to match logcat brief format with g_regex_match_simple
but it didn't work for me.

Ideas?

Body:
The following are compiled with clang -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include youe_file.c -lgobject-2.0 -lglib-2.0.

#include <stdio.h>
#include <glib.h>

static const char header_regex[] = "([\\w-]+): (\\w+)";

int main()
{
const char header[] = "Test: header1";
if (g_regex_match_simple(header_regex, header, 0, 0)){
 printf("+\n");}
else {
    printf("-\n");
}

return 0;
}

And it gives a positive match. The difference were in regexp pattern. I've removed a slash.

Original string static const char header_regex[] = "/([\\w-]+): (\\w+)";
needs to be static const char header_regex[] = "([\\w-]+): (\\w+)";

                                   ^
                                   |
                                no slash here


问:
how do i create a prompt in javascript with 3 checkboxes/radio buttons as choices?
How do I create a javascript prompt box where you have to select 1 of 3 choices? I'm looking to do something similar to a html form's radio buttons except within a javascript prompt.</p>

答:
You could use jQuery and do a 3 button dialog().  Check out this working jsFiddle demo:

```<code>$("#dialog").dialog({

    autoOpen: true,
    buttons: {

        Yes: function() {

            alert("Yes!");
            $(this).dialog("close");
        },
        No: function() {

            alert("No!");
            $(this).dialog("close");

        },
        Maybe: function() {

            alert("Maybe!");
            $(this).dialog("close");
        }

    },
    width: "400px"

});
</code>```

Body:
You could use jQuery and do a 3 button dialog().  Check out this working jsFiddle demo:

$("#dialog").dialog({

    autoOpen: true,
    buttons: {

        Yes: function() {

            alert("Yes!");
            $(this).dialog("close");
        },
        No: function() {

            alert("No!");
            $(this).dialog("close");

        },
        Maybe: function() {

            alert("Maybe!");
            $(this).dialog("close");
        }

    },
    width: "400px"

});


问:
How to source workspace in python script
I am using a python script in order to run four different python scripts that each execute a command, the purpose of this is to run the main python script on startup. This is what is inside the main python script:

```<code>#!/usr/bin/env/python
import os
os.system('x-terminal-emulator -e python ./one.py')
os.system('x-terminal-emulator -e python ./two.py')
os.system('x-terminal-emulator -e python ./three.py')
os.system('x-terminal-emulator -e python ./four.py')
</code>```

When I run it, it does create four terminals and executes each of the .py in each terminal, but the one.py, two.py, and three.py return an error of "sh: 1: source: not found". I know this is because I am using these lines:

```<code>os.system('cd /home/nvidia/catkin_ws')
os.system('source devel/setup.bash')
</code>```

Sourcing is needed in order the commands after it, how do I fix this problem? I am using ROS Kinetic with Linux Ubuntu 16.04.

Content of one.py

```<code>#!/bin/bash
import os
os.system('cd /home/nvidia/catkin_ws')
os.system('source devel/setup.bash')
os.system('roslaunch pocketsphinx continuous.launch spdict:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/speaker_test.dic spkws:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/speaker_test.kwlist sphmm:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/speaker_verification/an4.ci_cont_adapt/ dict:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/keywords_spk_verification.dic kws:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/keywords_spk_verification.kwlist gram:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/asr_spk grammar:=asr rule:=rule sp_verif:=false')
</code>```

Content of two.py

```<code>#!/bin/bash
import os
os.system('cd /home/nvidia/catkin_ws')
os.system('source devel/setup.bash')
os.system('rosrun pocketsphinx execute_commands.py')
</code>```

Content of three.py

```<code>#!/bin/bash
import os
os.system('cd ~/catkin_astra')
os.system('source devel/setup.bash')
os.system('roslaunch astra_launch astra.launch')
</code>```

答: os.system() starts a new shell, executes whatever you pass it and then closes the shell down again. Subsequently created shells are not affected by any changes to that shell, like changing the working directory or sourcing stuff.

Body:
I am using a python script in order to run four different python scripts that each execute a command, the purpose of this is to run the main python script on startup. This is what is inside the main python script:

#!/usr/bin/env/python
import os
os.system('x-terminal-emulator -e python ./one.py')
os.system('x-terminal-emulator -e python ./two.py')
os.system('x-terminal-emulator -e python ./three.py')
os.system('x-terminal-emulator -e python ./four.py')

When I run it, it does create four terminals and executes each of the .py in each terminal, but the one.py, two.py, and three.py return an error of "sh: 1: source: not found". I know this is because I am using these lines:

os.system('cd /home/nvidia/catkin_ws')
os.system('source devel/setup.bash')

Sourcing is needed in order the commands after it, how do I fix this problem? I am using ROS Kinetic with Linux Ubuntu 16.04.

Content of one.py

#!/bin/bash
import os
os.system('cd /home/nvidia/catkin_ws')
os.system('source devel/setup.bash')
os.system('roslaunch pocketsphinx continuous.launch spdict:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/speaker_test.dic spkws:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/speaker_test.kwlist sphmm:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/speaker_verification/an4.ci_cont_adapt/ dict:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/keywords_spk_verification.dic kws:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/keywords_spk_verification.kwlist gram:=/home/nvidia/catkin_ws/src/pocketsphinx/demo/asr_spk grammar:=asr rule:=rule sp_verif:=false')

Content of two.py

#!/bin/bash
import os
os.system('cd /home/nvidia/catkin_ws')
os.system('source devel/setup.bash')
os.system('rosrun pocketsphinx execute_commands.py')

Content of three.py

#!/bin/bash
import os
os.system('cd ~/catkin_astra')
os.system('source devel/setup.bash')
os.system('roslaunch astra_launch astra.launch')


问:
How to avoid Node.Js app quit when there's a Javascript error?
Suppose I have the following typo in my Node.Js app Javascript code:

    max_weight = Match.floor(max_weight/min_weight)
```

It's supposed to be Math.floor instead of Match.floor so when the code executes I get the error:

ReferenceError: Match is not defined

and then my Node.Js app quits.

How can I ensure that even if an error like this occurs, the app does not quit but simply reports the error and continues the code execution?

I understand I should solve problems like this before launching into production, but, still, what if I want the code to continue the execution despite the error?

答:
This could be achieved in two ways.

First approach is to use node.js global error handling way:

```<code>process.on('uncaughtException', function(err) {
  console.log(err); // do something with error or ignore it
});

let max_weight = 17, min_weight = 5;
max_weight = Match.floor(max_weight / min_weight);
</code>```

Other approach is to handle it locally at code level:

```<code>try {
    // trying to do something that might fail should be inside try block
    let max_weight = 17, min_weight = 5;
    max_weight = Match.floor(max_weight/min_weight);
} catch(err) {
    console.log(err); // do something with error or ignore it
}
</code>```

Clone node-cheat error-handling, run node error-handling.js.

Body:
Suppose I have the following typo in my Node.Js app Javascript code:

    max_weight = Match.floor(max_weight/min_weight)

It's supposed to be Math.floor instead of Match.floor so when the code executes I get the error:

ReferenceError: Match is not defined

and then my Node.Js app quits.

How can I ensure that even if an error like this occurs, the app does not quit but simply reports the error and continues the code execution?

I understand I should solve problems like this before launching into production, but, still, what if I want the code to continue the execution despite the error?

Body:
This could be achieved in two ways.

First approach is to use node.js global error handling way:

process.on('uncaughtException', function(err) {
  console.log(err); // do something with error or ignore it
});

let max_weight = 17, min_weight = 5;
max_weight = Match.floor(max_weight / min_weight);

Other approach is to handle it locally at code level:

try {
    // trying to do something that might fail should be inside try block
    let max_weight = 17, min_weight = 5;
    max_weight = Match.floor(max_weight/min_weight);
} catch(err) {
    console.log(err); // do something with error or ignore it
}

Clone node-cheat error-handling, run node error-handling.js.


问:
Unable to validate bootstrap 4 custom-radio with Parsley.js
I use parsley to validate my form <input>, <select> and it works great, but when i work with <input type="radio"> i have some issue. this is how i get my output. As you can see other two options are not listed with text-invalid.

As show in image other two option are not hilighted with text-invalid. I even added required to other two radio input but nothing works.

Here is my code: With quick demo

$(document).ready(function() {
  $("#adform").parsley({
    errorClass: "is-invalid text-danger",
    successClass: "is-valid",
    errorsWrapper: '

',
    errorTemplate: ''
  }).on("form:submit", function() {
    $("#submiting").modal("show"), $(".st").css("display", "none")
  })
}), $(".selectpicker").attr("data-trigger", "change").attr("data-required", "true");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.9.1/parsley.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<form id="adform" role="form" method="post" action="" enctype="multipart/form-data" autocomplete="off" data-parsley-validate>
  <label class="text-black-50">Fuel Type<b class="text-danger ml-1">*</b></label>
  <div class="col-12 mb-3">
    <span class="border p-2 shadow-sm rounded">
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="diesel" name="fue" class="custom-control-input" value="Diesel" required data-parsley-error-message="Select fuel type" data-parsley-errors-container="#fuelerr">
            <label class="custom-control-label" for="diesel">Diesel</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="petrol" name="fue" class="custom-control-input" value="Petrol">
            <label class="custom-control-label" for="petrol">Petrol</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="hybrid" name="fue" class="custom-control-input" value="Hybrid">
            <label class="custom-control-label" for="hybrid">Hybrid</label>
        </div>
    </span>
    <div id="fuelerr" class="pt-2"></div>
  </div>
  <input type="submit" name="submit" value="Submit Ad" />
</form></code>```

con some one help me solve this, How do i make other two option to be highlighted with text-invalid or text-danger

答:
Since input code is wrapped with separate divs , the error class is not getting applied, So you need to make of classLoader like below.

```<code>classHandler: function (el) {
        return el.$element.closest('.fuel-type');
    }
</code>```

and add fuel-type class to

```<code><span class="border p-2 shadow-sm rounded fuel-type">
</code>```

Check out following demo, hope this helps.

$(document).ready(function() {
  $("#adform").parsley({
    errorClass: "is-invalid text-danger",
    successClass: "is-valid",
    classHandler: function (el) {
        return el.$element.closest('.fuel-type');
    },
    errorsWrapper: '

',
    errorTemplate: ''
  }).on("form:submit", function() {
    $("#submiting").modal("show"), $(".st").css("display", "none")
  })
}), $(".selectpicker").attr("data-trigger", "change").attr("data-required", "true");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.9.1/parsley.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<form id="adform" role="form" method="post" action="" enctype="multipart/form-data" autocomplete="off" data-parsley-validate>
  <label class="text-black-50">Fuel Type<b class="text-danger ml-1">*</b></label>
  <div class="col-12 mb-3">
    <span class="border p-2 shadow-sm rounded fuel-type">
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="diesel" name="fue" class="custom-control-input" value="Diesel" required data-parsley-error-message="Select fuel type" data-parsley-errors-container="#fuelerr">
            <label class="custom-control-label" for="diesel">Diesel</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="petrol" name="fue" class="custom-control-input" value="Petrol">
            <label class="custom-control-label" for="petrol">Petrol</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="hybrid" name="fue" class="custom-control-input" value="Hybrid">
            <label class="custom-control-label" for="hybrid">Hybrid</label>
        </div>
    </span>
    <div id="fuelerr" class="pt-2"></div>
  </div>
  <input type="submit" name="submit" value="Submit Ad" />
</form></code>```

Body:
I use parsley to validate my form <input>, <select> and it works great, but when i work with <input type="radio"> i have some issue. this is how i get my output. As you can see other two options are not listed with text-invalid.

As show in image other two option are not hilighted with text-invalid. I even added required to other two radio input but nothing works.

Here is my code: With quick demo

$(document).ready(function() {
  $("#adform").parsley({
    errorClass: "is-invalid text-danger",
    successClass: "is-valid",
    errorsWrapper: '

',
    errorTemplate: ''
  }).on("form:submit", function() {
    $("#submiting").modal("show"), $(".st").css("display", "none")
  })
}), $(".selectpicker").attr("data-trigger", "change").attr("data-required", "true");

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<form id="adform" role="form" method="post" action="" enctype="multipart/form-data" autocomplete="off" data-parsley-validate>
  Fuel Type*

            <input type="radio" id="diesel" name="fue" class="custom-control-input" value="Diesel" required data-parsley-error-message="Select fuel type" data-parsley-errors-container="#fuelerr">
            Diesel

            <input type="radio" id="petrol" name="fue" class="custom-control-input" value="Petrol">
            Petrol

            <input type="radio" id="hybrid" name="fue" class="custom-control-input" value="Hybrid">
            Hybrid

  <input type="submit" name="submit" value="Submit Ad" />
</form>

con some one help me solve this, How do i make other two option to be highlighted with text-invalid or text-danger

Body:
Since input code is wrapped with separate divs , the error class is not getting applied, So you need to make of classLoader like below.

classHandler: function (el) {
        return el.$element.closest('.fuel-type');
    }

and add fuel-type class to

<span class="border p-2 shadow-sm rounded fuel-type">

Check out following demo, hope this helps.

$(document).ready(function() {
  $("#adform").parsley({
    errorClass: "is-invalid text-danger",
    successClass: "is-valid",
    classHandler: function (el) {
        return el.$element.closest('.fuel-type');
    },
    errorsWrapper: '<div class="form-group"></div>',
    errorTemplate: '<small class="form-text text-danger"></small>'
  }).on("form:submit", function() {
    $("#submiting").modal("show"), $(".st").css("display", "none")
  })
}), $(".selectpicker").attr("data-trigger", "change").attr("data-required", "true");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.9.1/parsley.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<form id="adform" role="form" method="post" action="" enctype="multipart/form-data" autocomplete="off" data-parsley-validate>
  <label class="text-black-50">Fuel Type<b class="text-danger ml-1">*</b></label>
  <div class="col-12 mb-3">
    <span class="border p-2 shadow-sm rounded fuel-type">
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="diesel" name="fue" class="custom-control-input" value="Diesel" required data-parsley-error-message="Select fuel type" data-parsley-errors-container="#fuelerr">
            <label class="custom-control-label" for="diesel">Diesel</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="petrol" name="fue" class="custom-control-input" value="Petrol">
            <label class="custom-control-label" for="petrol">Petrol</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" id="hybrid" name="fue" class="custom-control-input" value="Hybrid">
            <label class="custom-control-label" for="hybrid">Hybrid</label>
        </div>
    </span>
    <div id="fuelerr" class="pt-2"></div>
  </div>
  <input type="submit" name="submit" value="Submit Ad" />
</form>


问:
How to create a horizontal list view or recycler view with fixed size by changing the width of its items
I'm beginner in Android Development and trying to create a display of items in such a way that the size of these varieties according to the quantity, as they have done in this app. Any suggestions?

Screenshot 1

Screenshot 2

答:
So according to your question you have to add weight to the child elements which you can be given from parent layout like ex: recyclerview weight 3, and its item weight 1 each(if you have 3 items and fit in the width with margins on either sides) and consider to assign 3 to 6 elements in the width of the screen with horizontal scrolling

```<code>mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
</code>```

check here how to set weights for the views How to set layout_weight attribute dynamically from code?

Body:
So according to your question you have to add weight to the child elements which you can be given from parent layout like ex: recyclerview weight 3, and its item weight 1 each(if you have 3 items and fit in the width with margins on either sides) and consider to assign 3 to 6 elements in the width of the screen with horizontal scrolling

mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));

check here how to set weights for the views How to set layout_weight attribute dynamically from code?