问:
How do I put a Google Chart in Angular 4
How do you integrate a google chart in an angular 4 application?

I read the answer to the SO question here, but I believe it's incomplete. Basically, I'm attempting the same strategy as the previous answer, using a GoogleChartComponent and another component that extends it. Two errors arise, the first is a missing call to super() for the child component and the second is the call to "new" in this code

```<code>  createBarChart(element: any): any {
      return new google.visualization.BarChart(element);
  }
</code>```

I'm getting the error "google.visualization.BarChart is not a constructor".

I see one of the comments also mentions the use of <ng-content> for data projection but it isn't clearly outlined.

In trying to ask a "good" question, here is my GoogleChartComponent:

```<code>export class GoogleChartComponent implements OnInit {
  private static googleLoaded: any;
  constructor() {
    console.log('Here is GoogleChartComponent');
  }

  getGoogle() {
    return google;
  }

  ngOnInit() {
    console.log('ngOnInit');
    if (!GoogleChartComponent.googleLoaded) {
      GoogleChartComponent.googleLoaded = true;
      google.charts.load('current', {
        'packages': ['bar']
      });
      google.charts.setOnLoadCallback(() => this.drawGraph());
    }
  }

  drawGraph() {
      console.log('DrawGraph base class!!!! ');
  }

  createBarChart(element: any): any {
      return new google.visualization.BarChart(element);
  }

  createDataTable(array: any[]): any {
      return google.visualization.arrayToDataTable(array);
  }
}
</code>```

And my child component that extends it:

```<code>@Component({
  selector: 'app-bitcoin-chart',
  template: `
   <div id="barchart_material" style="width: 700px; height: 500px;"></div>
  `,
  styles: []
})
export class BitcoinChartComponent extends GoogleChartComponent  {
 private options;
  private data;
  private chart;
  // constructor() {
  //   super();
  //   console.log('Bitcoin Chart Component');
  // }
  drawGraph() {
    console.log('Drawing Bitcoin Graph');
    this.data = this.createDataTable([
     ['Price', 'Coinbase', 'Bitfinex', 'Poloniex', 'Kraken'],
     ['*', 1000, 400, 200, 500]
    ]);

    this.options = {
     chart: {
                    title: 'Bitcoin Price',
                    subtitle: 'Real time price data across exchanges',
                },
                bars: 'vertical' // Required for Material Bar Charts.
    };

    this.chart = this.createBarChart(document.getElementById('barchart_material'));
    this.chart.draw(this.data, this.options);
  }
}
</code>```

答:
I believe there is better way to integrate Google Chart in Angular 4. Library ng2-google-charts already has GoogleChartComponent. Link to npm page describes pretty well how to use it. Below is example of component:

```<code>import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {ViewChild} from '@angular/core';

import {GoogleChartComponent} from 'ng2-google-charts';

// needed for advanced usage of ng2-google-charts
import {HostListener} from '@angular/core';

@Component({
  selector: '[your-widget]',
  templateUrl: './your-widget.html',
  encapsulation: ViewEncapsulation.None
})
export class YourWidget implements OnInit {

  // type GoogleChartComponent and import for it can be ommited
  @ViewChild('your_chart') chart: GoogleChartComponent;

  // shows spinner while data is loading
  showSpinner: boolean;

  public chartData = {
    chartType: 'AnyChartType', // your type
    dataTable: [
      ['Col1', 'Col2']
    ],
    options: {}
  };

  constructor() {
  }

  ngOnInit(): void {

    this.showSpinner = true;
    this.yourService.getData()
          .subscribe((data) => {
            //this.data = data;
            this.processYourData();
            this.showSpinner = false;
        });
      }

  private processYourData() {
  }

  // advanced usage of chart
  //   in this case redraw function on window:resize event
  @HostListener('window:resize', ['$event'])
  onWindowResize(event: any) {
    // console.log(event.target.innerWidth);
    // Make sure you don't call redraw() in ngOnInit()
    //   - chart would not be initialised by that time, and
    //   - this would cause chart being drawn twice
    this.chart.redraw();
  }
}
</code>```

And your markup would look like this:

```<code><header class="widget-handle">
  <h5>Widget Title</h5>
  <div class="widget-controls">
    <a title="Refresh">
      <i *ngIf="showSpinner" class="fa fa-refresh fa-spin"></i>
    </a>
  </div>
</header>

<div class="widget-body">
  <google-chart #your_chart [data]="chartData" *ngIf="!showSpinner">
  </google-chart>
</div>
</code>```

Body:
How do you integrate a google chart in an angular 4 application?

I read the answer to the SO question here, but I believe it's incomplete. Basically, I'm attempting the same strategy as the previous answer, using a GoogleChartComponent and another component that extends it. Two errors arise, the first is a missing call to super() for the child component and the second is the call to "new" in this code

  createBarChart(element: any): any {
      return new google.visualization.BarChart(element);
  }

I'm getting the error "google.visualization.BarChart is not a constructor".

I see one of the comments also mentions the use of <ng-content> for data projection but it isn't clearly outlined.

In trying to ask a "good" question, here is my GoogleChartComponent:

export class GoogleChartComponent implements OnInit {
  private static googleLoaded: any;
  constructor() {
    console.log('Here is GoogleChartComponent');
  }

  getGoogle() {
    return google;
  }

  ngOnInit() {
    console.log('ngOnInit');
    if (!GoogleChartComponent.googleLoaded) {
      GoogleChartComponent.googleLoaded = true;
      google.charts.load('current', {
        'packages': ['bar']
      });
      google.charts.setOnLoadCallback(() => this.drawGraph());
    }
  }

  drawGraph() {
      console.log('DrawGraph base class!!!! ');
  }

  createBarChart(element: any): any {
      return new google.visualization.BarChart(element);
  }

  createDataTable(array: any[]): any {
      return google.visualization.arrayToDataTable(array);
  }
}

And my child component that extends it:

@Component({
  selector: 'app-bitcoin-chart',
  template: `

  `,
  styles: []
})
export class BitcoinChartComponent extends GoogleChartComponent  {
 private options;
  private data;
  private chart;
  // constructor() {
  //   super();
  //   console.log('Bitcoin Chart Component');
  // }
  drawGraph() {
    console.log('Drawing Bitcoin Graph');
    this.data = this.createDataTable([
     ['Price', 'Coinbase', 'Bitfinex', 'Poloniex', 'Kraken'],
     ['*', 1000, 400, 200, 500]
    ]);

    this.options = {
     chart: {
                    title: 'Bitcoin Price',
                    subtitle: 'Real time price data across exchanges',
                },
                bars: 'vertical' // Required for Material Bar Charts.
    };

    this.chart = this.createBarChart(document.getElementById('barchart_material'));
    this.chart.draw(this.data, this.options);
  }
}

Body:
I believe there is better way to integrate Google Chart in Angular 4. Library ng2-google-charts already has GoogleChartComponent. Link to npm page describes pretty well how to use it. Below is example of component:

import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {ViewChild} from '@angular/core';

import {GoogleChartComponent} from 'ng2-google-charts';

// needed for advanced usage of ng2-google-charts
import {HostListener} from '@angular/core';

@Component({
  selector: '[your-widget]',
  templateUrl: './your-widget.html',
  encapsulation: ViewEncapsulation.None
})
export class YourWidget implements OnInit {

  // type GoogleChartComponent and import for it can be ommited
  @ViewChild('your_chart') chart: GoogleChartComponent;

  // shows spinner while data is loading
  showSpinner: boolean;

  public chartData = {
    chartType: 'AnyChartType', // your type
    dataTable: [
      ['Col1', 'Col2']
    ],
    options: {}
  };

  constructor() {
  }

  ngOnInit(): void {

    this.showSpinner = true;
    this.yourService.getData()
          .subscribe((data) => {
            //this.data = data;
            this.processYourData();
            this.showSpinner = false;
        });
      }

  private processYourData() {
  }

  // advanced usage of chart
  //   in this case redraw function on window:resize event
  @HostListener('window:resize', ['$event'])
  onWindowResize(event: any) {
    // console.log(event.target.innerWidth);
    // Make sure you don't call redraw() in ngOnInit()
    //   - chart would not be initialised by that time, and
    //   - this would cause chart being drawn twice
    this.chart.redraw();
  }
}

And your markup would look like this:

<header class="widget-handle">
  <h5>Widget Title</h5>
  <div class="widget-controls">
    <a title="Refresh">
      <i *ngIf="showSpinner" class="fa fa-refresh fa-spin"></i>
    </a>
  </div>
</header>

<div class="widget-body">
  <google-chart #your_chart [data]="chartData" *ngIf="!showSpinner">
  </google-chart>
</div>


来源: stackexchange

问:
How to convert date to the format in which date is saved in MongoDB using Java and Spring?
```<code> @GetMapping("/{dateFrom}/{dateTo}")
       public List<com.example.demo.attendance> getRange(@PathVariable("dateFrom")  String dateFrom,@PathVariable("dateTo") String dateTo) throws ParseException{
          Date date1= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(dateFrom);
          Date date2= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(dateTo);
          System.out.println(date1);
          System.out.println(date2);
           List<com.example.demo.attendance> att =  this.attRepo.findDateBetween(date1,date2);

           return att;
        }
</code>```

here i am trying tho convert the date in the format (yyyy-MM-dd) to the format in which date is saved in mongodb to perform queries

答:
In my opinion date parameters should be rather passed as request parameters but anyway. Why don't you do this instead:

```<code>@GetMapping("/{dateFrom}/{dateTo}")
public List < com.example.demo.attendance > getRange(@PathVariable("dateFrom") @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate,
  @PathVariable("dateTo") @DateTimeFormat(pattern = "yyyy-MM-dd") Date dateTo) throws ParseException {
    System.out.println(date1);
    System.out.println(date2);
    List < com.example.demo.attendance > att = this.attRepo.findDateBetween(date1, date2);

    return att;
}
</code>```

Currently MongoDB driver supports only java.util.Date
I don't know which version of MongoDB Java Driver you use but here is the Documentation of the driver’s support for BSON document representations for 3.4. You can keep up-to-date in case something changes. Here to find the latest documentation for the MongoDB Java Driver

ContentLicense: CC BY-SA 3.0

Body:
 @GetMapping("/{dateFrom}/{dateTo}")
       public List<com.example.demo.attendance> getRange(@PathVariable("dateFrom")  String dateFrom,@PathVariable("dateTo") String dateTo) throws ParseException{
          Date date1= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(dateFrom);
          Date date2= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(dateTo);
          System.out.println(date1);
          System.out.println(date2);
           List<com.example.demo.attendance> att =  this.attRepo.findDateBetween(date1,date2);

           return att;
        }

here i am trying tho convert the date in the format (yyyy-MM-dd) to the format in which date is saved in mongodb to perform queries

Body:
In my opinion date parameters should be rather passed as request parameters but anyway. Why don't you do this instead:

@GetMapping("/{dateFrom}/{dateTo}")
public List < com.example.demo.attendance > getRange(@PathVariable("dateFrom") @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate,
  @PathVariable("dateTo") @DateTimeFormat(pattern = "yyyy-MM-dd") Date dateTo) throws ParseException {
    System.out.println(date1);
    System.out.println(date2);
    List < com.example.demo.attendance > att = this.attRepo.findDateBetween(date1, date2);

    return att;
}

Currently MongoDB driver supports only java.util.Date
I don't know which version of MongoDB Java Driver you use but here is the Documentation of the driver’s support for BSON document representations for 3.4. You can keep up-to-date in case something changes. Here to find the latest documentation for the MongoDB Java Driver


问:
Accessing singular_association_ids from model in Rails
I've been using the association_collection method "other_ids" throughout my Rails app with no issues.  However whenever I try to access it from within the model defining the association, Rails has no idea what I'm taking about.  For example:

```<code>class Membership < ActiveRecord::Base
    belongs_to  :course, :touch => true
    belongs_to  :person, :touch => true
end

class Day < ActiveRecord::Base
    belongs_to  :course,    :touch => true, :counter_cache => true
    has_many    :presents,  :dependent => :delete_all
    has_many    :people,    :through => :presents

    before_destroy  :clear_attendance

    def clear_attendance
        mems = Membership.where(:course_id => course.id, :person_id => person_ids)
        mems.update_all(["attendance = attendance - ?", (1 / course.days.size.to_f)])
    end
end
</code>```

In this case, person_ids is always null.  I've tried self.person_ids, people.ids, etc.  All nothing.  I have used day.person_ids elsewhere with no issues, so why can't I use it here?

I am using Ruby 1.9.1 and Rails 3.0.3.  Here is the SQL call from my log:

[1m[36mAREL (0.0ms)[0m  [1mUPDATE "memberships" SET attendance = attendance - 0.3333333333333333 WHERE ("memberships"."course_id" = 4) AND ("memberships"."person_id" IN (NULL))[0m

edit: added more code to clarify question

答:
What you really want there is:

```<code>def a_method
  self.people.all
end
</code>```

But to answer your question, person_ids is the correct method, and it should return an empty array, not nil. I just tried an association like that out in 2.3.10. Maybe you can post some more of your code, rails version, etc.

ContentLicense: CC BY-SA 2.5

Body:
I've been using the association_collection method "other_ids" throughout my Rails app with no issues.  However whenever I try to access it from within the model defining the association, Rails has no idea what I'm taking about.  For example:

class Membership < ActiveRecord::Base
    belongs_to  :course, :touch => true
    belongs_to  :person, :touch => true
end

class Day < ActiveRecord::Base
    belongs_to  :course,    :touch => true, :counter_cache => true
    has_many    :presents,  :dependent => :delete_all
    has_many    :people,    :through => :presents

    before_destroy  :clear_attendance

    def clear_attendance
        mems = Membership.where(:course_id => course.id, :person_id => person_ids)
        mems.update_all(["attendance = attendance - ?", (1 / course.days.size.to_f)])
    end
end

In this case, person_ids is always null.  I've tried self.person_ids, people.ids, etc.  All nothing.  I have used day.person_ids elsewhere with no issues, so why can't I use it here?

I am using Ruby 1.9.1 and Rails 3.0.3.  Here is the SQL call from my log:

[1m[36mAREL (0.0ms)[0m  [1mUPDATE "memberships" SET attendance = attendance - 0.3333333333333333 WHERE ("memberships"."course_id" = 4) AND ("memberships"."person_id" IN (NULL))[0m

edit: added more code to clarify question

Body:
What you really want there is:

def a_method
  self.people.all
end

But to answer your question, person_ids is the correct method, and it should return an empty array, not nil. I just tried an association like that out in 2.3.10. Maybe you can post some more of your code, rails version, etc.


问:
Sklearn cosine similarity for strings, Python
I am writing an algorithm that checks how much a string is equal to another string. I am using Sklearn cosine similarity.

My code is:

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

example_1 = ("I am okey", "I am okeu")
example_2 = ("I am okey", "I am crazy")

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(example_1)
result_cos = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix)
print(result_cos[0][1])
</code>```

Running this code for example_1, prints 0.336096927276. Running it for example_2, it prints the same score. The result is the same in both cases because there is only one different word.

What I want is to get a higher score for example_1 because the different words "okey vs okeu" have only one different letter. In contrast in example_2 there are two completely different words "okey vs crazy".

How can my code take in consideration that in some cases the different words are not completely different?

答:
For short strings, Levenshtein distance will probably yield better results than cosine similarity based on words. The algorithm below is adapted from Wikibooks. Since this is a distance metric, smaller score is better. </p>

```<code>def levenshtein(s1, s2):
    if len(s1) < len(s2):
        s1, s2 = s2, s1

    if len(s2) == 0:
        return len(s1)

    previous_row = range(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1
            deletions = current_row[j] + 1
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row

    return previous_row[-1]/float(len(s1))

example_1 = ("I am okey", "I am okeu")
example_2 = ("I am okey", "I am crazy")

print(levenshtein(*example_1))
print(levenshtein(*example_2))
</code>```

Body:
I am writing an algorithm that checks how much a string is equal to another string. I am using Sklearn cosine similarity.

My code is:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

example_1 = ("I am okey", "I am okeu")
example_2 = ("I am okey", "I am crazy")

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(example_1)
result_cos = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix)
print(result_cos[0][1])

Running this code for example_1, prints 0.336096927276. Running it for example_2, it prints the same score. The result is the same in both cases because there is only one different word.

What I want is to get a higher score for example_1 because the different words "okey vs okeu" have only one different letter. In contrast in example_2 there are two completely different words "okey vs crazy".

How can my code take in consideration that in some cases the different words are not completely different?

Body:
For short strings, Levenshtein distance will probably yield better results than cosine similarity based on words. The algorithm below is adapted from Wikibooks. Since this is a distance metric, smaller score is better.

def levenshtein(s1, s2):
    if len(s1) < len(s2):
        s1, s2 = s2, s1

    if len(s2) == 0:
        return len(s1)

    previous_row = range(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1
            deletions = current_row[j] + 1
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row

    return previous_row[-1]/float(len(s1))

example_1 = ("I am okey", "I am okeu")
example_2 = ("I am okey", "I am crazy")

print(levenshtein(*example_1))
print(levenshtein(*example_2))


问:
ASP.net Core MVC 2.0 Passing FormEditModel from view to controller

Hello, i am doing a simple blog using Microsoft asp.net MVC Core 2.0 for a school project and have encountered a problem while implementing CRUD operations for Articles. More precisely i have an issue only with the edit article method.
Here is my controller method

```<code>[HttpPost]
[ValidateModelState]
     public async Task<IActionResult> EditArticle(ArticleEditServiceModel parameter)
        {
            parameter.Title = this.html.Sanitize(parameter.Title);
            parameter.Content = this.html.Sanitize(parameter.Content);

            //var user = this.userManager.GetUserName(User.Identity.Name)

            await this.articles.EditAsync(parameter.Id, parameter.Title, parameter.Content);

            return RedirectToAction(nameof(Index));
        }
</code>```

And here is my service "EditAsync" method:

```<code>public async Task<bool> EditAsync(int id, string title, string content)
        {
            var article = await this.db.Articles.Where(a => a.Id == id).FirstOrDefaultAsync();

            if (article == null)
            {
                return false;
            }

            article.Title = title;
            article.Content = content;

            await this.db.SaveChangesAsync();
            return true;
        }
</code>```

The View:

```<code>@model ArticleEditServiceModel

@{
    ViewData["Title"] = "Edit Article";
}

<h2>@ViewData["Title"]</h2>

<div class="row">
    <div class="col-md-4">
        <form asp-controller="Article" asp-action="EditArticle"  asp-route-parameter=@Model method="post">
            <div class="form-group">
                <label asp-for="Title"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="form-text text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="Content"></label>
                <input asp-for="Content"  required class="form-control" />
                <span asp-validation-for="Content" class="form-text text-danger"></span>
            </div>
            <a asp-controller="Article" asp-action="Index" class="btn btn-default">Back</a>
            <button type="submit" formmethod="post" class="btn btn-success">Edit Article</button>
        </form>
    </div>
</div>

@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}
</code>```

It finds the correct article by Id and gives me the two input fields where i can edit the text, but when i click the submit button there are no changes applied to the Article. I tried debugging and found out that the view send a null model to the controller post method. I can't seem to find what's wrong with the code so i figured i should ask more experienced developers for input.

答: you should take out asp-route-id=@Model.Id from the form cuz you send the model directly to EditArticle. Create one input type="hidden" asp-for="Id" class="form-control" And will work.</p>

Body:
Hello, i am doing a simple blog using Microsoft asp.net MVC Core 2.0 for a school project and have encountered a problem while implementing CRUD operations for Articles. More precisely i have an issue only with the edit article method.
Here is my controller method

[HttpPost]
[ValidateModelState]
     public async Task<IActionResult> EditArticle(ArticleEditServiceModel parameter)
        {
            parameter.Title = this.html.Sanitize(parameter.Title);
            parameter.Content = this.html.Sanitize(parameter.Content);

            //var user = this.userManager.GetUserName(User.Identity.Name)

            await this.articles.EditAsync(parameter.Id, parameter.Title, parameter.Content);

            return RedirectToAction(nameof(Index));
        }

And here is my service "EditAsync" method:

public async Task<bool> EditAsync(int id, string title, string content)
        {
            var article = await this.db.Articles.Where(a => a.Id == id).FirstOrDefaultAsync();

            if (article == null)
            {
                return false;
            }

            article.Title = title;
            article.Content = content;

            await this.db.SaveChangesAsync();
            return true;
        }

The View:

@model ArticleEditServiceModel

@{
    ViewData["Title"] = "Edit Article";
}

@ViewData["Title"]

        <form asp-controller="Article" asp-action="EditArticle"  asp-route-parameter=@Model method="post">

                <input asp-for="Title" class="form-control" />

                <input asp-for="Content"  required class="form-control" />

            Back
            <button type="submit" formmethod="post" class="btn btn-success">Edit Article</button>
        </form>

@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}

It finds the correct article by Id and gives me the two input fields where i can edit the text, but when i click the submit button there are no changes applied to the Article. I tried debugging and found out that the view send a null model to the controller post method. I can't seem to find what's wrong with the code so i figured i should ask more experienced developers for input.


问:
Find the position of a specific number that appear first in the list [python]
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

```<code>     s = [1,2,3,4,5,3,9,8]  => s[2] appears first
</code>```

答:
This is another way of doing it..

If present, it will return the first index..
If there are no duplicates available, it will raise IndexError.

```<code>[s.index(_) for _ in s if s.count(_) > 1][0]
</code>```

Body:
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

     s = [1,2,3,4,5,3,9,8]  => s[2] appears first

Body:
This is another way of doing it..

If present, it will return the first index..
If there are no duplicates available, it will raise IndexError.

[s.index(_) for _ in s if s.count(_) > 1][0]


问:
Output of mysqli_fetch_array($data) with loop and without loop
When I used while loop to print the values of a particular column using mysqli_fetch_array(), I got the correct output from the database.

```<code>while($row=mysqli_fetch_array($data))
{
  echo $row['name'];
}
</code>```

But when I used the below mentioned code without the loop, the output was different.

```<code>   $row=mysqli_fetch_array($data);
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
</code>```

When I used the below mentioned code, I could see that I get all the rows in the form of an associative array using mysqli_fetch_array().

```<code>$con=mysqli_connect("localhost", "root", "", "student_details");
$data=mysqli_query($con,"select * from `registration`");
while ($row = mysqli_fetch_array($data))
 {
    $rec[]=$row;
 }
echo "```";
print_r($rec);
echo "```";
?>
</code>```

My question is how to get all the values of a particular column (using a while loop), without usage of any loop.

答:
You can use mysqli_fetch_all to get all data.

Check in php docs

->  mysqli_result::fetch_all -- mysqli_fetch_all —
->  Fetches all result rows as an associative array, a numeric array, or both

Body:
When I used while loop to print the values of a particular column using mysqli_fetch_array(), I got the correct output from the database.

while($row=mysqli_fetch_array($data))
{
  echo $row['name'];
}

But when I used the below mentioned code without the loop, the output was different.

   $row=mysqli_fetch_array($data);
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];

When I used the below mentioned code, I could see that I get all the rows in the form of an associative array using mysqli_fetch_array().

$con=mysqli_connect("localhost", "root", "", "student_details");
$data=mysqli_query($con,"select * from `registration`");
while ($row = mysqli_fetch_array($data))
 {
    $rec[]=$row;
 }
echo "
";
print_r($rec);
echo "
";
?>

My question is how to get all the values of a particular column (using a while loop), without usage of any loop.


问:
Protractor ,Jasmine timeout issue
I'm doing e2e-testing with Protractor and Jasmine. Our application is in Angular.

I have written given getPageTimeout: 500000, allScriptsTimeout: 600000, in the config file. Added defaultTimeoutInterval:500000 as per GitHub .

Even then I'm getting the below exception. Appreciate any help.

```<code>A Jasmine spec timed out. Resetting the WebDriver Control Flow.
The last active task was:
Protractor.waitForAngular()
at [object Object].webdriver.WebDriver.schedule (C:\Users\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:345:15)
at [object Object].Protractor.executeAsyncScript_ (C:\Users\AppData\Roaming\npm\node_modules\protractor\lib\protractor.js:1141:26)
at [object Object].Protractor.waitForAngular (C:\Users\AppData\Roaming\npm\node_modules\protractor\lib\protractor.js:1159:15)
at [object Object].getWebElements (C:\Users\AppData\Roaming\npm\node_modules\protractor\lib\protractor.js:191:21)
at [object Object].getWebElements
</code>```

答:
Try adding below code, jasmine default time 5 sec. The below code will wait for all test cases to complete it task &  working fine for me.
jasmine.getEnv().defaultTimeoutInterval =15000;</p>

```<code>onPrepare: function(){
jasmine.getEnv().defaultTimeoutInterval =your time to set in milli second;
}
</code>```

Title: Protractor ,Jasmine timeout issue

Body:
I'm doing e2e-testing with Protractor and Jasmine. Our application is in Angular.

I have written given getPageTimeout: 500000, allScriptsTimeout: 600000, in the config file. Added defaultTimeoutInterval:500000 as per GitHub .

Even then I'm getting the below exception. Appreciate any help.

A Jasmine spec timed out. Resetting the WebDriver Control Flow.
The last active task was:
Protractor.waitForAngular()
at [object Object].webdriver.WebDriver.schedule (C:\Users\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:345:15)
at [object Object].Protractor.executeAsyncScript_ (C:\Users\AppData\Roaming\npm\node_modules\protractor\lib\protractor.js:1141:26)
at [object Object].Protractor.waitForAngular (C:\Users\AppData\Roaming\npm\node_modules\protractor\lib\protractor.js:1159:15)
at [object Object].getWebElements (C:\Users\AppData\Roaming\npm\node_modules\protractor\lib\protractor.js:191:21)
at [object Object].getWebElements

Body:
Try adding below code, jasmine default time 5 sec. The below code will wait for all test cases to complete it task &  working fine for me.
jasmine.getEnv().defaultTimeoutInterval =15000;

onPrepare: function(){
jasmine.getEnv().defaultTimeoutInterval =your time to set in milli second;
}


问:
Best practice: try/catch two things in JavaScript?
I am developing a web application. The android wrapper has a JavaScript interface naming android and IOS has an Interface naming ios. I have to try both interfaces but only one of them will respond.

I don't know where to place the second try? inside the first try? inside catch or finally or throw or totally separated try/catch blocks?

Which one is logically preferred and which one is better in performance?

First Idea:

```<code>try {
    ios.myMethod();
    }

catch(err) {

            try {
                 android.myMethod();
                 }
            catch{
                 console.log('The Android does not exist');
                  }

            console.log('The ios does not exist');
        }
</code>```

Second Idea:

```<code>try {

     try {
          android.myMethod();
          }
     catch{
         console.log('The Android does not exist');
          }

    ios.myMethod();
    }

catch(err) {
            console.log('The ios does not exist');
        }
</code>```

third idea:

```<code>try {
    ios.myMethod();
    }

catch(err) {
            console.log('The ios does not exist');
        }
 finally{

      try {
          android.myMethod();
          }
      catch{
         console.log('The Android does not exist');
          }
       }
</code>```

my last idea:

```<code> try {
      android.myMethod();
      }
 catch{
     console.log('The Android does not exist');
      }

 try {
      ios.myMethod();
      }
 catch{
     console.log('The IOS does not exist');
      }
</code>```

答:
The first idea seems appropriate. Also look if you can use if else statements instead like so:</p>

```<code>if (window.ios && window.ios.myMethod {
    ios.myMethod();
} else if (window.android && window.android.myMethod) {
    android.myMethod();
}
</code>```

Body:
I am developing a web application. The android wrapper has a JavaScript interface naming android and IOS has an Interface naming ios. I have to try both interfaces but only one of them will respond.

I don't know where to place the second try? inside the first try? inside catch or finally or throw or totally separated try/catch blocks?

Which one is logically preferred and which one is better in performance?

First Idea:

try {
    ios.myMethod();
    }

catch(err) {

            try {
                 android.myMethod();
                 }
            catch{
                 console.log('The Android does not exist');
                  }

            console.log('The ios does not exist');
        }

Second Idea:

try {

     try {
          android.myMethod();
          }
     catch{
         console.log('The Android does not exist');
          }

    ios.myMethod();
    }

catch(err) {
            console.log('The ios does not exist');
        }

third idea:

try {
    ios.myMethod();
    }

catch(err) {
            console.log('The ios does not exist');
        }
 finally{

      try {
          android.myMethod();
          }
      catch{
         console.log('The Android does not exist');
          }
       }

my last idea:

 try {
      android.myMethod();
      }
 catch{
     console.log('The Android does not exist');
      }

 try {
      ios.myMethod();
      }
 catch{
     console.log('The IOS does not exist');
      }

Body:
The first idea seems appropriate. Also look if you can use if else statements instead like so:

if (window.ios && window.ios.myMethod {
    ios.myMethod();
} else if (window.android && window.android.myMethod) {
    android.myMethod();
}


问:
Rest service getting (400) Bad Request for special characters even after serializing with Newtonsoft.Json.JsonConvert
I have a restful web service in C# which uses JSON POST for HttpWebRequest. In the client side, input data will be converted to JSON format using Newtonsoft.Json.JsonConvert.SerializeObject method. For sending the data IO.Stream with utf-8 encoding is used. I don't have any problem with sending data even with normal specific characters. But for some weird input text like "professional" I got (400) Bad Request error and it seems for this specific case Newtonsoft.Json cannot serialize well.

Any help will be appreciated. The relevant codes are shared below:

```<code>HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(restServiceUrl);
            request.Timeout = int.Parse((cmbTimeout.SelectedItem as ComboBoxItem).Value.ToString()) * 1000;
request.Method = "POST";
request.ContentType = "application/json;charset=utf-8";
var readTextParams = new RESTReadTextParameters();
readTextParams.Text = "professional";
readTextParams.Speaker = "M";
var data = Newtonsoft.Json.JsonConvert.SerializeObject(readTextParams);

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
      requestStream.Write(bytes, 0, bytes.Length);
}
</code>```

答:
One possible solution to this problem is using Base64 encoding. A sample of code for encoding the input text is shown below:

```<code>System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
readTextParams.Text = Convert.ToBase64String(encoding.GetBytes(readTextParams.Text.ToCharArray()));
data = Newtonsoft.Json.JsonConvert.SerializeObject(readTextParams);
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
      requestStream.Write(bytes, 0, bytes.Length);
}
</code>```

In the server side, we must decode the Base64 string.

Body:
I have a restful web service in C# which uses JSON POST for HttpWebRequest. In the client side, input data will be converted to JSON format using Newtonsoft.Json.JsonConvert.SerializeObject method. For sending the data IO.Stream with utf-8 encoding is used. I don't have any problem with sending data even with normal specific characters. But for some weird input text like "professional" I got (400) Bad Request error and it seems for this specific case Newtonsoft.Json cannot serialize well.

Any help will be appreciated. The relevant codes are shared below:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(restServiceUrl);
            request.Timeout = int.Parse((cmbTimeout.SelectedItem as ComboBoxItem).Value.ToString()) * 1000;
request.Method = "POST";
request.ContentType = "application/json;charset=utf-8";
var readTextParams = new RESTReadTextParameters();
readTextParams.Text = "professional";
readTextParams.Speaker = "M";
var data = Newtonsoft.Json.JsonConvert.SerializeObject(readTextParams);

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
      requestStream.Write(bytes, 0, bytes.Length);
}

Body:
One possible solution to this problem is using Base64 encoding. A sample of code for encoding the input text is shown below:

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
readTextParams.Text = Convert.ToBase64String(encoding.GetBytes(readTextParams.Text.ToCharArray()));
data = Newtonsoft.Json.JsonConvert.SerializeObject(readTextParams);
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
      requestStream.Write(bytes, 0, bytes.Length);
}

In the server side, we must decode the Base64 string.


问:
Bounding Box of the Line Arrangement in O(n log n) time
I want to compute the bounding box of a line arrangement (with no parallel lines). The bounding box should contain all intersections of the line arrangement.

I have done some research and found several times that computing the bounding box should be possible in O(n log n) time. Unfortunately I was not able to find the source of this claim.

I tried to come up with an algorithm that solves this problem in O(n log n) time but was not able so far. I tried to use duality to compute the envelopes but unfortunately the envelopes do not always contain the lowest and highest intersection.

I would appreciate if someone know where to find such an algorithm or how it works.

答:
It is possible to do it in O(n log n) time. We don't have to check every intersection, we just need to find the ones with highest/lowest x and y-coordinate.

Here's what I came up with. I think we are in the same lecture, and this is pretty much exactly what I am going to hand in, so please don't just copy paste it, if you want to use this solution.

Algorithm for left bound:

1) Make lines into points according to point-line duality l:y = mx + c => l* = (m, -c). O(n)

2) Order them by x-coordinate. O(n log n)

3) Save line of first two points as line with lowest slope. O(1)

4) Go through points and if a line of two points P[i] and P[i+1] has lower slope than previously saved lowest slope, save that line as line with lowest slope. O(n)

5) Make the line into a point, using duality again. O(1)

6) Return x-coordinate of that point as left bound. O(1)

The line with the lowest slope represents the intersection point with the lowest x-coordinate. Right bound works the same but with highest slope. In order to get an algorithm for upper and lower bound we can change the duality to l:y = mx + c => l* = (-c, m) (basically turning the plane 90 degrees) in order to be able to determine the lowest and highest intersection points by looking at the slopes as well.

We don't have to look at all intersection points of lines in order to find the steepest slope, looking at lines that are next to each other according to x-coordinate is enough.


问:
How to get values from JObject
I want to integrate Pipedrive with Dynamics CRM. I am calling webhook whenever deal is updated in Pipedrive. I am getting data in JObject form. I want to extract two fields from that. One is status and other is title.How can I do that?

Code to call Webhook:

```<code> [RoutePrefix("api/webhook")]
public class WebhookController : ApiController
{
    [HttpPost]
    [Route("")]
    public void Post(JObject message)
    {
        Console.WriteLine($"Received webhook: {message}");
    }
}
</code>```

Json which I am getting :

```<code>{
  "v":1,
  "matches_filters":{
    "current":[

    ]
  },
  "meta":{
    "v":1,
    "action":"updated",
    "object":"deal",
    "id":1,
    "company_id":2278508,
    "user_id":3371496,
    "host":"agniket.pipedrive.com",
    "timestamp":1512620040,
    "timestamp_micro":1512620040475200,
    "permitted_user_ids":[
      3371496
    ],
    "trans_pending":false,
    "is_bulk_update":false,
    "pipedrive_service_name":false,
    "matches_filters":{
      "current":[

      ]
    },
    "webhook_id":"31814"
  },
  "current":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-07 04:14:00",
    "stage_change_time":null,
    "active":false,
    "deleted":false,
    "status":"won",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":"2017-12-07 04:14:00",
    "pipeline_id":1,
    "won_time":"2017-12-07 04:14:00",
    "first_won_time":"2017-12-07 04:14:00",
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "previous":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-04 06:33:56",
    "stage_change_time":null,
    "active":true,
    "deleted":false,
    "status":"open",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":null,
    "pipeline_id":1,
    "won_time":null,
    "first_won_time":null,
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "event":"updated.deal",
  "retry":0
}
</code>```

答:
If it's a regular HTTP call you can just use built-in JSON model binder.
Try to change your JObject to a class which represents your message, like:
(Structure updated to provided JSON representation)

```<code>public class Message
{
    public Current Current { get; set; }
}

public class Current
{
    public string Status { get; set; }
    public string Title { get; set; }
}
</code>```

and use it in your WebHook:

```<code>[RoutePrefix("api/webhook")]
public class WebhookController : ApiController
{
    [HttpPost]
    [Route("")]
    public void Post(Message message)
    {
        Console.WriteLine($"Received webhook: {message.Current.Title} {message.Current.Status}");
    }
}
</code>```

Title: How to get values from JObject

Body:
I want to integrate Pipedrive with Dynamics CRM. I am calling webhook whenever deal is updated in Pipedrive. I am getting data in JObject form. I want to extract two fields from that. One is status and other is title.How can I do that?

Code to call Webhook:

 [RoutePrefix("api/webhook")]
public class WebhookController : ApiController
{
    [HttpPost]
    [Route("")]
    public void Post(JObject message)
    {
        Console.WriteLine($"Received webhook: {message}");
    }
}

Json which I am getting :

{
  "v":1,
  "matches_filters":{
    "current":[

    ]
  },
  "meta":{
    "v":1,
    "action":"updated",
    "object":"deal",
    "id":1,
    "company_id":2278508,
    "user_id":3371496,
    "host":"agniket.pipedrive.com",
    "timestamp":1512620040,
    "timestamp_micro":1512620040475200,
    "permitted_user_ids":[
      3371496
    ],
    "trans_pending":false,
    "is_bulk_update":false,
    "pipedrive_service_name":false,
    "matches_filters":{
      "current":[

      ]
    },
    "webhook_id":"31814"
  },
  "current":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-07 04:14:00",
    "stage_change_time":null,
    "active":false,
    "deleted":false,
    "status":"won",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":"2017-12-07 04:14:00",
    "pipeline_id":1,
    "won_time":"2017-12-07 04:14:00",
    "first_won_time":"2017-12-07 04:14:00",
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "previous":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-04 06:33:56",
    "stage_change_time":null,
    "active":true,
    "deleted":false,
    "status":"open",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":null,
    "pipeline_id":1,
    "won_time":null,
    "first_won_time":null,
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "event":"updated.deal",
  "retry":0
}

Body:
If it's a regular HTTP call you can just use built-in JSON model binder.
Try to change your JObject to a class which represents your message, like:
(Structure updated to provided JSON representation)

public class Message
{
    public Current Current { get; set; }
}

public class Current
{
    public string Status { get; set; }
    public string Title { get; set; }
}

and use it in your WebHook:

[RoutePrefix("api/webhook")]
public class WebhookController : ApiController
{
    [HttpPost]
    [Route("")]
    public void Post(Message message)
    {
        Console.WriteLine($"Received webhook: {message.Current.Title} {message.Current.Status}");
    }
}


问:
Style does not affect input in Ionic 3
I am trying create a login page for my app. But style does not work as I wish, here is the photo from problem

1

Here is the login.html codes

```<code><ion-content class="app-content padding main-bg text-center">
  <div class="logo animated pulse infinite">
      <img src="../../assets/imgs/logo1.png" />
  </div>
  <form class="app-form">
      <div class="list list-inset">
          <label class="item item-input sec-main-text">
              <input type="text" class="text-center" placeholder="username">
          </label>
          <label class="item item-input sec-main-text">
              <input type="password" class="text-center" placeholder="Password">
          </label>
      </div>
      <button class="button button-block button-clear main-btn main-bg-color" ng-click="goto('/app/home')">Login</button>
      <a href="#/register" class="main-text-color">Register</a>
      <p class="forget" ng-click="forget_password()">Forget Password?</p>
  </form>
</ion-content>
</code>```

Here is the login.scss codes

```<code> .app-form .list-inset {
    margin-left: 0;
    margin-right: 0;
    background: none;
  }

.app-form {
    .item-input {
      margin-bottom: 20px;
      background: none;
      border: 1px solid;
      border-radius: 30px;
      padding: 5px 10px;
    }
    .list-inset .item {
      border-radius: 30px;
      height: 46px;
      &.item-input input {
        padding: 0;
        color: white;
      }
    }
    input {
      &::-webkit-input-placeholder, &:-moz-placeholder {
        color: white;
        text-transform: capitalize;
      }
    }
  }

.app-form .item-select {
    select {
      width: 100%;
      max-width: 100%;
      background: none;
      text-align-last: center;
      padding: 0;
      text-align: -moz-center;
      text-align: -webkit-center;
      text-align-last: -moz-center;
      text-align-last: -webkit-center;
      direction: ltr;
    }
    &:after {
      top: 60%;
      right: 55px;
    }
  }
</code>```

And here is the what I want from original login.html :)

2

And from original html's browser screenshot

3

And from my app's browser screenshot

4

Thanks for your helping :)

EDIT

After change html tags with ion tags

答:
Ionic introduces and uses their own tags,  for example, which has default styles added to it. It seems that you are using standard tags in your app such as  and . Change your input to something like

```<code><ion-item>
  <ion-label>Username</ion-label>
  <ion-input type="text"></ion-input>
</ion-item>
</code>```

and things shall work smoother.

Ionic is fun to learn because it is easy. Have a visit the Official Doc to see how you can make things easier. With the proper syntax, you will not less styling rules.

Title: Style does not affect input in Ionic 3

Body:
I am trying create a login page for my app. But style does not work as I wish, here is the photo from problem

1

Here is the login.html codes

<ion-content class="app-content padding main-bg text-center">

  <form class="app-form">

              <input type="text" class="text-center" placeholder="username">

              <input type="password" class="text-center" placeholder="Password">

      <button class="button button-block button-clear main-btn main-bg-color" ng-click="goto('/app/home')">Login</button>
      Register

Forget Password?

  </form>
</ion-content>

Here is the login.scss codes

 .app-form .list-inset {
    margin-left: 0;
    margin-right: 0;
    background: none;
  }

.app-form {
    .item-input {
      margin-bottom: 20px;
      background: none;
      border: 1px solid;
      border-radius: 30px;
      padding: 5px 10px;
    }
    .list-inset .item {
      border-radius: 30px;
      height: 46px;
      &.item-input input {
        padding: 0;
        color: white;
      }
    }
    input {
      &::-webkit-input-placeholder, &:-moz-placeholder {
        color: white;
        text-transform: capitalize;
      }
    }
  }

.app-form .item-select {
    select {
      width: 100%;
      max-width: 100%;
      background: none;
      text-align-last: center;
      padding: 0;
      text-align: -moz-center;
      text-align: -webkit-center;
      text-align-last: -moz-center;
      text-align-last: -webkit-center;
      direction: ltr;
    }
    &:after {
      top: 60%;
      right: 55px;
    }
  }

And here is the what I want from original login.html :)

2

And from original html's browser screenshot

3

And from my app's browser screenshot

4

Thanks for your helping :)

EDIT

After change html tags with ion tags

Body:
Ionic introduces and uses their own tags,  for example, which has default styles added to it. It seems that you are using standard tags in your app such as  and . Change your input to something like

<ion-item>
  <ion-label>Username</ion-label>
  <ion-input type="text"></ion-input>
</ion-item>

and things shall work smoother.

Ionic is fun to learn because it is easy. Have a visit the Official Doc to see how you can make things easier. With the proper syntax, you will not less styling rules.


问:
Are the unit test classes in ASP.NET MVC web project a good example?
I'm learning TDD. I know about dependency injection whereby you place the class's dependencies in the constructor's parameters and have them passed in, passing in default implementations from the default constructor eg;

```<code>public AccountController() : this( RepositoryFactory.Users())
{
}

public AccountController( IUserRepository oUserRepository)
{
 m_oUserRepository = oUserRepository;
}
</code>```

RepositoryFactory is a simple static class that returns the chosen implementations for the current build

But the default ASP.NET MVC web app project doesn't do this, instead the DI takes the form of public properties that are assigned in the object initializer in the test class eg; from AccountController.cs :

```<code>protected override void Initialize(RequestContext requestContext)
{
 if (FormsService == null)
  { FormsService = new FormsAuthenticationService(); }
 if (MembershipService == null)
  { MembershipService = new AccountMembershipService(); }

 base.Initialize(requestContext);
}
</code>```

And in the test class AccountControllerTest.cs :

```<code>private static AccountController GetAccountController()
{
 AccountController controller = new AccountController()
 {
  FormsService = new MockFormsAuthenticationService(),
  MembershipService = new MockMembershipService(),
  Url = new UrlHelper(requestContext),
 };
 //snip
}
</code>```

So now my AccountController class has two approaches to dependency injection. Which one should I use? Constructor injection or public properties?

Am thinking constructor injection...

Is the ASP.NET MVC use of public properties like that because you need to provide a specific way of injecting into the constructor, and the basic "create new" web app needs to be generic as a starting point?

答:
The examples in the ASP.NET MVC are excellent demonstrations of how not to use DI.

First of all, using a default constructor as well as an overloaded constructor introduces ambiguity: does the class control its own dependencies, or does it get them from the outside? Apparently, it can't really decide.

Secondly, having a default implementation introduces tight coupling because you can't create a new instance of the default implementation without having a reference to it. However, the whole point of DI is to enable loose coupling.

Unfortunately we see this idiom a lot. In my book I call it the Bastard Injection anti-pattern; I lifted the name from one of Oren Eini/Ayende Rahien's many opinionated blog posts where he walks through a very similar example.

As a general advice I recommend using Constructor Injection in the vast majority of cases. It's easy to implement and has very strong semantics: it forces the consumer to supply an instance of the dependency, effectively stating that the dependency is mandatory.

Property Injection, on the other hand, implies that the dependency is optional, because the compiler doesn't force you to assign a value. In most cases, dependencies are not really optional, so use of this pattern should be rare.

Body:
I'm learning TDD. I know about dependency injection whereby you place the class's dependencies in the constructor's parameters and have them passed in, passing in default implementations from the default constructor eg;

public AccountController() : this( RepositoryFactory.Users())
{
}

public AccountController( IUserRepository oUserRepository)
{
 m_oUserRepository = oUserRepository;
}

RepositoryFactory is a simple static class that returns the chosen implementations for the current build

But the default ASP.NET MVC web app project doesn't do this, instead the DI takes the form of public properties that are assigned in the object initializer in the test class eg; from AccountController.cs :

protected override void Initialize(RequestContext requestContext)
{
 if (FormsService == null)
  { FormsService = new FormsAuthenticationService(); }
 if (MembershipService == null)
  { MembershipService = new AccountMembershipService(); }

 base.Initialize(requestContext);
}

And in the test class AccountControllerTest.cs :

private static AccountController GetAccountController()
{
 AccountController controller = new AccountController()
 {
  FormsService = new MockFormsAuthenticationService(),
  MembershipService = new MockMembershipService(),
  Url = new UrlHelper(requestContext),
 };
 //snip
}

So now my AccountController class has two approaches to dependency injection. Which one should I use? Constructor injection or public properties?

Am thinking constructor injection...

Is the ASP.NET MVC use of public properties like that because you need to provide a specific way of injecting into the constructor, and the basic "create new" web app needs to be generic as a starting point?


问:
how to paginate data without reloading page?
I have learned pagination from the link
How to set condition in following code for marking current page in pagination?

using code

```<code><?php
    $id=3;  //  test value
    $page=20;   //  test value

    $li=array();    //  temporary array for convenience
    $template='<li%s><a href="?id=%s">%s</a></li>';
    if($id>1) $li[]=sprintf($template,'',$id-1,'Previous');
    for($i=1;$i<=$page;$i++) {
        if($i==$id) $li[]=sprintf($template,' class="active"',$i,$i);   //  Current
        else $li[]=sprintf($template,'',$i,$i);
    }
    if($id<$page) $li[]=sprintf($template,'',$id+1,'Next');
    $li=implode('',$li); // convert to string for printing
?>
<ul class="pagination">
<?php print $li; ?>
</ul>
</code>```

But it is showing data after reloading data? is there any way to make it show without reloading page? I am new to pagination - please help.

答:
You can use pagination without page load by ajax or jQuery. Please read the example following the link below -
https://datatables.net/examples/basic_init/alt_pagination.html</p>

Body:
I have learned pagination from the link
How to set condition in following code for marking current page in pagination?

using code

<?php
    $id=3;  //  test value
    $page=20;   //  test value

    $li=array();    //  temporary array for convenience
    $template='
%s
';
    if($id>1) $li[]=sprintf($template,'',$id-1,'Previous');
    for($i=1;$i<=$page;$i++) {
        if($i==$id) $li[]=sprintf($template,' class="active"',$i,$i);   //  Current
        else $li[]=sprintf($template,'',$i,$i);
    }
    if($id<$page) $li[]=sprintf($template,'',$id+1,'Next');
    $li=implode('',$li); // convert to string for printing
?>

<?php print $li; ?>

But it is showing data after reloading data? is there any way to make it show without reloading page? I am new to pagination - please help.


Title: increment by +2 pandas to excel

Body:
I have a list of dataframes.  Is there a way for each loop to increase the increment by +2 each time?  So my dataframe in excel looks like:

while True:
    writer = pd.ExcelWriter("C:\\xzx.xlsx")
    worksheet = writer.sheets['Sheet1']
    df3.to_excel(writer, startrow=0, startcol=+2, index = False)

dataframe:

                   A         B
2000-01-01  0.469112 -0.282863
2000-01-02  1.212112 -0.173215
2000-01-03 -0.861849 -2.104569
2000-01-04  0.721555 -0.706771
2000-01-05 -0.424972  0.567020
2000-01-06 -0.673690  0.113648
2000-01-07  0.404705  0.577046
2000-01-08 -0.370647 -1.157892

Ideal:

               A         B    C     D         E
        0.469112 -0.282863        0.469112 -0.282863
        1.212112 -0.173215        1.212112 -0.173215
       -0.861849 -2.104569        0.861849 -2.104569
        0.721555 -0.706771        0.721555 -0.706771
       -0.424972  0.567020       -0.424972  0.567020
       -0.673690  0.113648       -0.673690  0.113648
        0.404705  0.577046        0.404705  0.577046
       -0.370647 -1.157892       -0.370647 -1.157892

+2 also gives the same output in each loop.

Body:
You could use pd.concattoo:

import pandas as pd

data = {'A': {'2000-01-01': 0.469112,
  '2000-01-02': 1.212112,
  '2000-01-03': -0.861849,
  '2000-01-04': 0.7215550000000001,
  '2000-01-05': -0.424972,
  '2000-01-06': -0.67369,
  '2000-01-07': 0.40470500000000004,
  '2000-01-08': -0.370647},
 'B': {'2000-01-01': -0.28286300000000003,
  '2000-01-02': -0.173215,
  '2000-01-03': -2.1045689999999997,
  '2000-01-04': -0.706771,
  '2000-01-05': 0.56702,
  '2000-01-06': 0.113648,
  '2000-01-07': 0.5770460000000001,
  '2000-01-08': -1.157892}}

# Create dataframe
df = pd.DataFrame(data)

# Create a series to append "empty" column in loop
extra_col = pd.Series(index=df.index,data=[""]*len(df))

# Create loop
while True:
    df = pd.concat((df,extra_col,df),axis=1)
    # Let's break if more than 10 columns
    if len(df.T) > 10:
        break

# Optional rename columns
alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
df.columns = (alphabet[i] for i in list(range(len(df.columns))))

# Output
df.to_excel("test.xlsx",header=False,index=False)


问:
Tail-recursive program in prolog which outputs odd numbers in a list
I've written a tail-recursive predicate in Prolog which outputs the integers between A and B in a list K. I've used "reverse" to bring the numbers into the right order:

```<code>numbers(A,B,K) :- numbers(A,B,[],K).
numbers(Y,Y,X,K) :- !, reverse([Y|X],K).
numbers(A,B,X,K) :- A<B, C is A+1, numbers(C,B,[A|X],K).
</code>```

Query:

```<code>?- numbers(3,6, K).
   K=[3,4,5,6]
</code>```

All works fine. What I now want to do is that I only want to have odd numbers of the range between A and B in the list K. How can I do that? Thanks in advance!

答:
This could be a solution, using mod/2 operator.

```<code>numbers(A,B,K) :-
    B1 is B+1,
    numbers(A,B1,[],K).
numbers(Y,Y1,X,K) :-
    Y = Y1,
    reverse(X,K).
numbers(A,B,X,K) :-
    A<B,
    C is A+1,
    C1 is mod(C,2),
    (C1 = 0 ->
        numbers(C,B,[A|X],K)
    ; numbers(C,B,X,K)).
</code>```

Body:
I've written a tail-recursive predicate in Prolog which outputs the integers between A and B in a list K. I've used "reverse" to bring the numbers into the right order:

numbers(A,B,K) :- numbers(A,B,[],K).
numbers(Y,Y,X,K) :- !, reverse([Y|X],K).
numbers(A,B,X,K) :- A<B, C is A+1, numbers(C,B,[A|X],K).

Query:

?- numbers(3,6, K).
   K=[3,4,5,6]

All works fine. What I now want to do is that I only want to have odd numbers of the range between A and B in the list K. How can I do that? Thanks in advance!

Body:
This could be a solution, using mod/2 operator.

numbers(A,B,K) :-
    B1 is B+1,
    numbers(A,B1,[],K).
numbers(Y,Y1,X,K) :-
    Y = Y1,
    reverse(X,K).
numbers(A,B,X,K) :-
    A<B,
    C is A+1,
    C1 is mod(C,2),
    (C1 = 0 ->
        numbers(C,B,[A|X],K)
    ; numbers(C,B,X,K)).


问:
Pulp Python LP - Wrong Solution
When I run the following code:

```<code>from pulp import *

x = pulp.LpVariable("x", 0, None , LpContinuous)
y = pulp.LpVariable("y", 0, None , LpContinuous)
problem = pulp.LpProblem("A simple max problem", pulp.LpMinimize)
problem += x + y, "The objective function"
problem += x + 2*y == 2, "1st constraint"
problem += 2*x + 3*y == 2, "2nd constraint"
problem += x >= 0, "3rd constraint"
problem += y >= 0, "4th constraint"
problem += x + y == 1, "5th constraint"

problem.writeLP("WhiskasModel.lp")
problem.solve()

for variable in problem.variables():
    print variable.name, "=", variable.varValue

print value(problem.objective)
</code>```

I get as output:

```<code>x = 0.0
y = 1.0
1.0
</code>```

which is clearly wrong, since 2nd constraint is not satisfied.
Now the situation is that the above problem does not have a solution. So I would expect from pulp to notify me something relevant ("Infeasible problem") or something like that. Instead, I suspect that it arbitrarily drops some of the constraints and works with the rest of them. Similarly in the following case:

```<code>x = pulp.LpVariable("x", 0, None , LpContinuous)
y = pulp.LpVariable("y", 0, None , LpContinuous)
problem = pulp.LpProblem("A simple max problem", pulp.LpMinimize)
problem += x + y, "The objective function"
problem += x + 2*y == 2, "1st constraint"
problem += 2*x + 3*y == 20, "2nd constraint"
problem += x >= 0, "3rd constraint"
problem += y >= 0, "4th constraint"
problem += x + y == 1, "5th constraint"

problem.writeLP("WhiskasModel.lp")
problem.solve()

for variable in problem.variables():
    print variable.name, "=", variable.varValue

print value(problem.objective)
</code>```

the ouput is

```<code>x = 34.0
y = -16.0
18.0
</code>```

i.e. the 4th constraint is now "dropped".

Anyone having any idea as how to solve this?

答:
Your program will just try to solve itself, starting from the first constraint down.

Think of it from a linear algebra perspective, the augmented matrix is:

```<code>[ 1 2 | 2
  2 3 | 20
  1 1 | 1 ]
</code>```

with further constraints that both variables should be >=0.
Directly subtracting twice the first row from the second you will end up with:

```<code>[ 1 2  | 2
  0 -1 | 16
  .........]
</code>```

In other words, to satisfy your first constraint, you FORCE your y variable to become -16, only possible solution. The x variable becomes 34 as consequence to solve the first line. All further constraints and the objective function do not matter anymore. This was the only possible solution.

What you want is for the system to warn you if the problem does not have a solution which satisfies all constraints. Currently this is not implemented in the package and seeing the Git, they do not plan to change this behavior, so if you want to be warned about infeasible problems, change packages.

If you don't want to change packages, you can see your problem was infeasible from the solution violating your constraints. You can write a block of code to throw a warning/exception yourself.

Title: Pulp Python LP - Wrong Solution

Body:
When I run the following code:

from pulp import *

x = pulp.LpVariable("x", 0, None , LpContinuous)
y = pulp.LpVariable("y", 0, None , LpContinuous)
problem = pulp.LpProblem("A simple max problem", pulp.LpMinimize)
problem += x + y, "The objective function"
problem += x + 2*y == 2, "1st constraint"
problem += 2*x + 3*y == 2, "2nd constraint"
problem += x >= 0, "3rd constraint"
problem += y >= 0, "4th constraint"
problem += x + y == 1, "5th constraint"

problem.writeLP("WhiskasModel.lp")
problem.solve()

for variable in problem.variables():
    print variable.name, "=", variable.varValue

print value(problem.objective)

I get as output:

x = 0.0
y = 1.0
1.0

which is clearly wrong, since 2nd constraint is not satisfied.
Now the situation is that the above problem does not have a solution. So I would expect from pulp to notify me something relevant ("Infeasible problem") or something like that. Instead, I suspect that it arbitrarily drops some of the constraints and works with the rest of them. Similarly in the following case:

x = pulp.LpVariable("x", 0, None , LpContinuous)
y = pulp.LpVariable("y", 0, None , LpContinuous)
problem = pulp.LpProblem("A simple max problem", pulp.LpMinimize)
problem += x + y, "The objective function"
problem += x + 2*y == 2, "1st constraint"
problem += 2*x + 3*y == 20, "2nd constraint"
problem += x >= 0, "3rd constraint"
problem += y >= 0, "4th constraint"
problem += x + y == 1, "5th constraint"

problem.writeLP("WhiskasModel.lp")
problem.solve()

for variable in problem.variables():
    print variable.name, "=", variable.varValue

print value(problem.objective)

the ouput is

x = 34.0
y = -16.0
18.0

i.e. the 4th constraint is now "dropped".

Anyone having any idea as how to solve this?

Body:
Your program will just try to solve itself, starting from the first constraint down.

Think of it from a linear algebra perspective, the augmented matrix is:

[ 1 2 | 2
  2 3 | 20
  1 1 | 1 ]

with further constraints that both variables should be >=0.
Directly subtracting twice the first row from the second you will end up with:

[ 1 2  | 2
  0 -1 | 16
  .........]

In other words, to satisfy your first constraint, you FORCE your y variable to become -16, only possible solution. The x variable becomes 34 as consequence to solve the first line. All further constraints and the objective function do not matter anymore. This was the only possible solution.

What you want is for the system to warn you if the problem does not have a solution which satisfies all constraints. Currently this is not implemented in the package and seeing the Git, they do not plan to change this behavior, so if you want to be warned about infeasible problems, change packages.

If you don't want to change packages, you can see your problem was infeasible from the solution violating your constraints. You can write a block of code to throw a warning/exception yourself.


问:
What's the difference between Array<T> and [T]?
Title says it all.  I'm expecting an array to be handed to me via an Any? parameter (don't ask! I hate they implemented it like that!), and I want to test if that's what I actually got.  Not sure if I should be testing for Array<T> or [T] or if there's even a difference.

答:
As others already explained in the comments there is no difference.

Both Array<T> and [T] definitions means: A generic array of type T.

Defining a type

Swift provides 4 main syntactic sugars to define a type, here's the list.

1. An Optional Int

```<code>let optionalInt: Optional<Int>
</code>```

is equivalent to

```<code>let optionalInt: Int?
</code>```

2. An Implicitly Unwrapped Optional Int

```<code>let implicitlyUnwrappedInt: ImplicitlyUnwrappedOptional<Int>
</code>```

is equivalent to

```<code>let implicitlyUnwrappedInt: Int!
</code>```

3. An Array of Int(s)

```<code>let nums: [Int]
</code>```

is equivalent to

```<code>let nums: Array<Int>
</code>```

4. A Dictionary where the Key is String and the Value is Int

```<code>let dict: [String:Int]
</code>```

is equivalent to

```<code>let dict: Dictionary<String:Int>
</code>```

Conclusion

You can find more info on this page of The Swift Programming Language.

Finally, if you are wondering How to make your own syntactic sugar, you can't

Body:
As others already explained in the comments there is no difference.

Both Array<T> and [T] definitions means: A generic array of type T.

Defining a type

Swift provides 4 main syntactic sugars to define a type, here's the list.

1. An Optional Int

let optionalInt: Optional<Int>

is equivalent to

let optionalInt: Int?

2. An Implicitly Unwrapped Optional Int

let implicitlyUnwrappedInt: ImplicitlyUnwrappedOptional<Int>

is equivalent to

let implicitlyUnwrappedInt: Int!

3. An Array of Int(s)

let nums: [Int]

is equivalent to

let nums: Array<Int>

4. A Dictionary where the Key is String and the Value is Int

let dict: [String:Int]

is equivalent to

let dict: Dictionary<String:Int>

Conclusion

You can find more info on this page of The Swift Programming Language.

Finally, if you are wondering How to make your own syntactic sugar, you can't


问:
fire .net event from jquery
I have an image on my page than can be changed from a fileupload asp.net control on the page, i want to provide and alternative to clicking the button by allowing the user to click their image. i gave the fileupload a class 'jqueryPhotoUploadTrigger' and it renders like this:

```<code><input type="file" name="ctl00$ctl00$ctl00$ContentPlaceHolderDefault$C2kMasterPlaceholder$ucEditDetails_20$photoupload" id="ctl00_ctl00_ctl00_ContentPlaceHolderDefault_C2kMasterPlaceholder_ucEditDetails_20_photoupload" class="jqueryPhotoUploadTrigger" />
</code>```

i then have jquery script at the bottom:

```<code> $(document).ready(function() {
        $("#clickMyColl").click(function () {

            alert("image has been clicked");
            $('.jqueryPhotoUploadTrigger').click();
        });
 });
</code>```

the alert does show so i know the script is firing when i click the image. i was just hoping the .click would fire the event on the button but it didnt. can i do it this way or must i find an alternative?

答:
You are using the ID of your image as "#clickMyColl", but instead use the ID as it is rendered (jQuery does not know the asp ID): "ctl00_ctl00_ctl00_ContentPlaceHolderDefault_C2kMasterPlaceholder_ucEditDetails_20_photoupload"

Alternatively, you could use the class to select:
$(".jqueryPhotoUploadTrigger").click(function ...

Title: fire .net event from jquery

Body:
I have an image on my page than can be changed from a fileupload asp.net control on the page, i want to provide and alternative to clicking the button by allowing the user to click their image. i gave the fileupload a class 'jqueryPhotoUploadTrigger' and it renders like this:

<input type="file" name="ctl00$ctl00$ctl00$ContentPlaceHolderDefault$C2kMasterPlaceholder$ucEditDetails_20$photoupload" id="ctl00_ctl00_ctl00_ContentPlaceHolderDefault_C2kMasterPlaceholder_ucEditDetails_20_photoupload" class="jqueryPhotoUploadTrigger" />

i then have jquery script at the bottom:

 $(document).ready(function() {
        $("#clickMyColl").click(function () {

            alert("image has been clicked");
            $('.jqueryPhotoUploadTrigger').click();
        });
 });

the alert does show so i know the script is firing when i click the image. i was just hoping the .click would fire the event on the button but it didnt. can i do it this way or must i find an alternative?


问:
Passing a struct to a process through shared memory in C
For a uni assignment I am trying to create a structure in shared memory, write some data in it, and then let the child read it. I've come up with something but, since I am new to C, I am getting some errors that I can't quite understand, here is the code:

```<code>typedef struct file
{
    int pid;
    char tipo[2];
    char nome[20];
    unsigned long genoma;
    char shmPtr[];
} file_entry;

int main (void)
{

int shmid;
int n;
file_entry *entries;

if (fork() == 0) {
    if ((shmid = shmget(20441, sizeof(file_entry) + 256, IPC_CREAT | 0666)) == -1) {
        printf("shmget");
        exit(2);
    }

    entries = (file_entry*) shmat(shmid, 0, 0);
    if (entries->shmPtr == (char *) -1) {
        printf("problem2");
        exit(2);
    }

    printf("\nChild Reading ....\n\n");
    printf("%c\n", entries->shmPtr[0]);
    printf("%c\n", entries->shmPtr[1]);
    printf("%c\n", entries->shmPtr[2]);
    printf("%c\n", entries->shmPtr[3]);
    putchar('\n');
    printf("\nDone\n\n");
} else {
    if ((shmid = shmget(20441, sizeof(file_entry) + 256, IPC_CREAT | 0666)) == -1) {
        printf("problem3");
        exit(2);
    }

    entries = (file_entry *) shmat(shmid, 0, 0);
    if (entries->shmPtr == (char *) -1) {
        printf("problem4");
        exit(2);
    }
    printf("done attachment");

    int pidD = 1234;
    char tipoD[2] = "A";
    char nomeD[20] = "NOMEINDIVIDUO";
    unsigned long genomaD = 10000;

    entries->shmPtr[0]= pidD;
    entries->shmPtr[1]=tipoD;
    entries->shmPtr[2]=nomeD;
    entries->shmPtr[3]= genomaD;

    wait(NULL);
    shmdt(&shmid);
}
exit(0);
</code>```

}

The errors I'm getting are those:

```<code>shared memory example 2.c:74:27: warning: incompatible pointer to integer conversion assigning to 'char' from 'char [2]' [-Wint-conversion]
    entries->shmPtr[1]=tipoD;
                      ^~~~~~
shared memory example 2.c:75:27: warning: incompatible pointer to integer conversion assigning to 'char' from 'char [20]' [-Wint-conversion]
    entries->shmPtr[2]=nomeD;
</code>```

I tried to declare the dimension of the variables in the struct and the variables on the father to be the same thinking that it would help, but it didn't. Does anyone know how to solve this? If you also have some example code that would be appreciated.

答:
I tried with this test application and it works:</p>

```<code>#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct file
{
    int pid;
    char tipo[2];
    char nome[20];
    unsigned long genoma;
} file_entry;

int main (void)
{

    int shmid;
    int n;
    file_entry *entries;

    if (fork() == 0) {
        if ((shmid = shmget(20441, sizeof(file_entry) + 256, IPC_CREAT | 0666)) == -1) {
            printf("shmget");
            exit(2);
        }

        entries = (file_entry*) shmat(shmid, 0, 0);
        if (entries == NULL) {
            printf("problem2");
            exit(2);
        }

        printf("\nChild Reading ....\n\n");
        printf("%d\n", entries->pid);
        printf("%s\n", entries->tipo);
        printf("%s\n", entries->nome);
        printf("%lu\n", entries->genoma);
        putchar('\n');
        printf("\nDone\n\n");
    } else {
        if ((shmid = shmget(20441, sizeof(file_entry) + 256, IPC_CREAT | 0666)) == -1) {
            printf("problem3");
            exit(2);
        }

        entries = (file_entry *) shmat(shmid, 0, 0);
        if (entries == NULL ) {
            printf("problem4");
            exit(2);
        }
        printf("done attachment");

        int pidD = 4001;
        char tipoD[2] = "A";
        char nomeD[20] = "sfds";
        unsigned long genomaD = 10000;

        entries->pid  = pidD;
        sprintf(entries->tipo,"%s",tipoD);
        sprintf(entries->nome,"%s",nomeD);
        entries->genoma= genomaD;

        wait(NULL);
        shmdt(&shmid);
    }
    exit(0);
}
</code>```

Body:
For a uni assignment I am trying to create a structure in shared memory, write some data in it, and then let the child read it. I've come up with something but, since I am new to C, I am getting some errors that I can't quite understand, here is the code:

typedef struct file
{
    int pid;
    char tipo[2];
    char nome[20];
    unsigned long genoma;
    char shmPtr[];
} file_entry;

int main (void)
{

int shmid;
int n;
file_entry *entries;

if (fork() == 0) {
    if ((shmid = shmget(20441, sizeof(file_entry) + 256, IPC_CREAT | 0666)) == -1) {
        printf("shmget");
        exit(2);
    }

    entries = (file_entry*) shmat(shmid, 0, 0);
    if (entries->shmPtr == (char *) -1) {
        printf("problem2");
        exit(2);
    }

    printf("\nChild Reading ....\n\n");
    printf("%c\n", entries->shmPtr[0]);
    printf("%c\n", entries->shmPtr[1]);
    printf("%c\n", entries->shmPtr[2]);
    printf("%c\n", entries->shmPtr[3]);
    putchar('\n');
    printf("\nDone\n\n");
} else {
    if ((shmid = shmget(20441, sizeof(file_entry) + 256, IPC_CREAT | 0666)) == -1) {
        printf("problem3");
        exit(2);
    }

    entries = (file_entry *) shmat(shmid, 0, 0);
    if (entries->shmPtr == (char *) -1) {
        printf("problem4");
        exit(2);
    }
    printf("done attachment");

    int pidD = 1234;
    char tipoD[2] = "A";
    char nomeD[20] = "NOMEINDIVIDUO";
    unsigned long genomaD = 10000;

    entries->shmPtr[0]= pidD;
    entries->shmPtr[1]=tipoD;
    entries->shmPtr[2]=nomeD;
    entries->shmPtr[3]= genomaD;

    wait(NULL);
    shmdt(&shmid);
}
exit(0);

}

The errors I'm getting are those:

shared memory example 2.c:74:27: warning: incompatible pointer to integer conversion assigning to 'char' from 'char [2]' [-Wint-conversion]
    entries->shmPtr[1]=tipoD;
                      ^~~~~~
shared memory example 2.c:75:27: warning: incompatible pointer to integer conversion assigning to 'char' from 'char [20]' [-Wint-conversion]
    entries->shmPtr[2]=nomeD;

I tried to declare the dimension of the variables in the struct and the variables on the father to be the same thinking that it would help, but it didn't. Does anyone know how to solve this? If you also have some example code that would be appreciated.

Body:
I tried with this test application and it works:

#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct file
{
    int pid;
    char tipo[2];
    char nome[20];
    unsigned long genoma;
} file_entry;

int main (void)
{

    int shmid;
    int n;
    file_entry *entries;

    if (fork() == 0) {
        if ((shmid = shmget(20441, sizeof(file_entry) + 256, IPC_CREAT | 0666)) == -1) {
            printf("shmget");
            exit(2);
        }

        entries = (file_entry*) shmat(shmid, 0, 0);
        if (entries == NULL) {
            printf("problem2");
            exit(2);
        }

        printf("\nChild Reading ....\n\n");
        printf("%d\n", entries->pid);
        printf("%s\n", entries->tipo);
        printf("%s\n", entries->nome);
        printf("%lu\n", entries->genoma);
        putchar('\n');
        printf("\nDone\n\n");
    } else {
        if ((shmid = shmget(20441, sizeof(file_entry) + 256, IPC_CREAT | 0666)) == -1) {
            printf("problem3");
            exit(2);
        }

        entries = (file_entry *) shmat(shmid, 0, 0);
        if (entries == NULL ) {
            printf("problem4");
            exit(2);
        }
        printf("done attachment");

        int pidD = 4001;
        char tipoD[2] = "A";
        char nomeD[20] = "sfds";
        unsigned long genomaD = 10000;

        entries->pid  = pidD;
        sprintf(entries->tipo,"%s",tipoD);
        sprintf(entries->nome,"%s",nomeD);
        entries->genoma= genomaD;

        wait(NULL);
        shmdt(&shmid);
    }
    exit(0);
}


问:
get min value from php array depend on column value
I am trying to get the min value of a two dimentional array where another column value is grouped.

```<code>array(3) {
  [0]=>
  array(3) {
    ["cid"]=>
    int(53)
    ["cpr"]=>
    int(243)
    ["cty"]=>
    string(1) "1"
  }
  [1]=>
  array(3) {
    ["cid"]=>
    int(55)
    ["cpr"]=>
    float(270)
    ["cty"]=>
    string(1) "1"
  }
  [2]=>
  array(3) {
    ["cid"]=>
    int(54)
    ["cpr"]=>
    float(367.65)
    ["cty"]=>
    string(1) "2"
  }
}
</code>```

I want for example to get the min of all where cty=1 then cty=2 ....

答:
sorry, to make it clear I want the minimum cpr from cells with same cty.
I need for example to get the min cpr for all records with cty=1, then with cty=2 ....</p>

Body:
I am trying to get the min value of a two dimentional array where another column value is grouped.

array(3) {
  [0]=>
  array(3) {
    ["cid"]=>
    int(53)
    ["cpr"]=>
    int(243)
    ["cty"]=>
    string(1) "1"
  }
  [1]=>
  array(3) {
    ["cid"]=>
    int(55)
    ["cpr"]=>
    float(270)
    ["cty"]=>
    string(1) "1"
  }
  [2]=>
  array(3) {
    ["cid"]=>
    int(54)
    ["cpr"]=>
    float(367.65)
    ["cty"]=>
    string(1) "2"
  }
}

I want for example to get the min of all where cty=1 then cty=2 ....


问:
How to catch TCPDF Exception TCPDF ERROR: [Image] Unable to get the size of the image
I want to generate a PDF out of a Product.
But when some images are missing, I get an TCPF ERROR.

```<code>TCPDF ERROR: [Image] Unable to get the size of the image...
</code>```

Is there a usecase to go on without aborting?
Already tried to catch it with the classic Exception Handler, bute doesnt work:

```<code>try {
      $pdf->writeHTML($renderedView, true, 0, true, 0);
    } catch (\Exception $e) {
       return $e->getMessage();
     }
</code>```

THANKS for any help!

答:
You can catch the exception only if you define('K_TCPDF_THROW_EXCEPTION_ERROR', true)
There is a constant K_TCPDF_THROW_EXCEPTION_ERROR that determines what  TCPDF does in case of error.

define('K_TCPDF_THROW_EXCEPTION_ERROR', true) will throw exceptions in case of errors

define('K_TCPDF_THROW_EXCEPTION_ERROR', false) will echo the error and exit script execution.

Handled by method Error in tcpdf:2921

Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.

Body:
I want to generate a PDF out of a Product.
But when some images are missing, I get an TCPF ERROR.

TCPDF ERROR: [Image] Unable to get the size of the image...

Is there a usecase to go on without aborting?
Already tried to catch it with the classic Exception Handler, bute doesnt work:

try {
      $pdf->writeHTML($renderedView, true, 0, true, 0);
    } catch (\Exception $e) {
       return $e->getMessage();
     }

THANKS for any help!


问:
Creating scatterplot per df column in Pandas/Python, when number of columns is unknown
I am new to Python and Stackoverflow. I am trying to create a combined/merged plot of scatterplots for a pd.dataframe per column.

My data looks like this;

I would like to create a combined scatterplot where the first x-value is Assignment 1 (string/header) and the correponding y-values  are the values found in column 'Assignment1'. I want to do this for each assignment and combine the scatterplots in one plot.

The problem revolves around the fact that I don't know how many columns I will have to deal with so I have to create a general code that takes this into account. I do however know that the first two columns consist of Ids and Names i.e ([2:]) I added the header for the dataframe manually to give you an example of the data, so I would also like to ask how one names headers when one doesn't know the total amount of columns..?

Any thoughts would be greatly appreciated.

Python 3.6.1 64bits, Qt 5.6.2, PyQt5 5.6 on Darwin

答:
Welcome to stackoverflow!

Want you want to do is iterate over your data to and append your data points to lists which you can then plot.

```<code>def plotXY(gradeMatrix):
#First two empty lists are defined
pointsx = []
pointsy = []

#The grades of the Matrix, of the valid data, is now made in to
#x and y coordinates, with a random small number added.
for grades in gradeMatrix:
    for g in range(len(grades)):

        #(note :I added small random values  to differentiate the data
        # points for viewing)

        # append values found via the loop in the data to your created lists
        # for x and y
        pointsx.append(g + random()*0.2 - 0.1)
        pointsy.append(float(grades[g]) + random()*0.2 - 0.1)

#The possible grades going op the y-axis are stored in a list
gradesy = [12,10,7,4,2,0,-3]

# Create data ticks, x values and y values for the plot.
plt.yticks(gradesy, [str(x) for x in gradesy])
plt.xticks(np.arange(10),np.arange(10))

# set range for the Y axis
plt.ylim(-4,13)

# create bar plot
plt.plot(pointsx,pointsy,'bs')

# Legend - labels
plt.title("Occurance of grades given for different assignments")
plt.ylabel("Grade")
plt.xlabel("Assignement number")

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

Body:
Welcome to stackoverflow!

Want you want to do is iterate over your data to and append your data points to lists which you can then plot.

def plotXY(gradeMatrix):
#First two empty lists are defined
pointsx = []
pointsy = []

#The grades of the Matrix, of the valid data, is now made in to
#x and y coordinates, with a random small number added.
for grades in gradeMatrix:
    for g in range(len(grades)):

        #(note :I added small random values  to differentiate the data
        # points for viewing)

        # append values found via the loop in the data to your created lists
        # for x and y
        pointsx.append(g + random()*0.2 - 0.1)
        pointsy.append(float(grades[g]) + random()*0.2 - 0.1)

#The possible grades going op the y-axis are stored in a list
gradesy = [12,10,7,4,2,0,-3]

# Create data ticks, x values and y values for the plot.
plt.yticks(gradesy, [str(x) for x in gradesy])
plt.xticks(np.arange(10),np.arange(10))

# set range for the Y axis
plt.ylim(-4,13)

# create bar plot
plt.plot(pointsx,pointsy,'bs')

# Legend - labels
plt.title("Occurance of grades given for different assignments")
plt.ylabel("Grade")
plt.xlabel("Assignement number")

# show plot
plt.show()


问:
R - Modifying data frame column names from values in another data frame
Lets say I have a data frame called df1 similar to the following:

```<code>  Year S4 S1 S2 S3
1 2001  2  5  4  4
2 2002  5  2  2  0
3 2003  7  9  3  6
4 2004  9  6  8  7
5 2005  2  2  6  4
6 2006 10  5  7  5
</code>```

and another data frame df2 like this:

```<code>  ID    Name
1 S1    John
2 S2   Sarah
3 S3    Kate
4 S4 Michael
</code>```

and I want to change the relevant column names (i.e. not the year) of df1 to the corresponding names in df2, so that df 1 would look like this:

```<code>  Year Michael John Sarah Kate
1 2001       2    5     4    4
2 2002       5    2     2    0
3 2003       7    9     3    6
4 2004       9    6     8    7
5 2005       2    2     6    4
6 2006      10    5     7    5
</code>```

I've tried the following:

```<code>cols <- names(df1)
cols <- cols[2:length(cols)]
newCols = df2[cols == df2$ID, "Name"]
names(df1) <- c("Year", newCols)
</code>```

But the third line only seems to work if the columns in df1 and rows in df2 are in the same order, which they are not. Is there a simple way to do this in R?

答:
We can use match

```<code>names(df1)[-1] <-  df2$Name[match(names(df1)[-1], df2$ID)]
</code>```

Body:
Lets say I have a data frame called df1 similar to the following:

  Year S4 S1 S2 S3
1 2001  2  5  4  4
2 2002  5  2  2  0
3 2003  7  9  3  6
4 2004  9  6  8  7
5 2005  2  2  6  4
6 2006 10  5  7  5

and another data frame df2 like this:

  ID    Name
1 S1    John
2 S2   Sarah
3 S3    Kate
4 S4 Michael

and I want to change the relevant column names (i.e. not the year) of df1 to the corresponding names in df2, so that df 1 would look like this:

  Year Michael John Sarah Kate
1 2001       2    5     4    4
2 2002       5    2     2    0
3 2003       7    9     3    6
4 2004       9    6     8    7
5 2005       2    2     6    4
6 2006      10    5     7    5

I've tried the following:

cols <- names(df1)
cols <- cols[2:length(cols)]
newCols = df2[cols == df2$ID, "Name"]
names(df1) <- c("Year", newCols)

But the third line only seems to work if the columns in df1 and rows in df2 are in the same order, which they are not. Is there a simple way to do this in R?

Body:
We can use match

names(df1)[-1] <-  df2$Name[match(names(df1)[-1], df2$ID)]