问:
How to get values from JSON webservice with 2 objects in Angular 2
I'm new in Angular 2 and I'm quite lost. I have a JSON web service responding to /rest/alertsDashboard. It returns something like:

```<code>{
  "total": {
    "totalOperations": 2573,
    "totalOperationsAlert": 254,
    "totalOperationsRisk": 34
  },
  "alerts": [
      {
        codAlert: "L1",
        description: "Alert 1",
        value: 1
      },
      {
        codAlert: "L2",
        description: "Alert 2",
        value: 2
      },
      ...
  ]
}
</code>```

So I defined a DashboardComponent component and a AlertDashboardService service. I would like, for example, to display totalOperations and totalOperationsAlert. I don't know if I'm doing it in a correct way.

In dashboard.component.ts I have:

```<code>...
@Component({
  selector: 'app-dashboard',
  template: `
    <p>{{totalAlertsDashboard.totalOperations}}</p>
    <p>{{totalAlertsDashboard.totalOperationsAlert}}</p>
    ...
  `
})
export class DashboardComponent implements OnInit {
  totalAlertsDashboard: TotalAlertsDashboard;
  alertsDashboard: AlertDashboard[];

  constructor(private alertsDashboardService: AlertsDashboardService) { }

  ngOnInit() {
    this.alertsDashboardService.get().then(
      response => {
        this.totalAlertsDashboard = response.totalAlertsDashboard;
        this.alertsDashboard = response.alertsDashboard;
      }
    );
  }
}
</code>```

In alerts-dashboard.service.ts I have:

```<code>...
export class AlertsDashboard {
    totalAlertsDashboard: TotalAlertsDashboard;
    alertsDashboard: AlertDashboard[];
}

export class TotalAlertsDashboard {
    totalOperations: number;
    totalOperationsAlert: number;
    totalOperationsRisk: number;
}

export class AlertDashboard {
    codAlert: string;
    description: string;
    value: number;
}

@Injectable()
export class AlertsDashboardService {
    private headers = new Headers({ 'Content-Type': 'application/json' });
    private url = environment.urlAPI + '/rest/alertsDashboard';

    constructor(private http: Http) { }

    get(): Promise<AlertsDashboard> {
        var vm = this;

        let params = new URLSearchParams();

        return vm.http.get(vm.url, { search: params })
        .toPromise()
        .then(response => {
            var responseJson: AlertsDashboard = response.json() ;
            console.log(responseJson); // it prints the JSON correctly
            return responseJson;
        });
  }
}
</code>```

I hope you can help me with that.

答:
try this :

```<code>ngOnInit() {
    this.alertsDashboardService.get().then(
      response => {
        this.totalAlertsDashboard = response.total;
        this.alertsDashboard = response.alerts;
      }
    );
  }
</code>```

In alerts-dashboard.service.ts

```<code>export class AlertsDashboard {
    total: TotalAlertsDashboard;
    alerts: AlertDashboard[];
}
</code>```

template :

```<code><p>{{totalAlertsDashboard?.totalOperations}}</p>
</code>```

Body:
I'm new in Angular 2 and I'm quite lost. I have a JSON web service responding to /rest/alertsDashboard. It returns something like:

{
  "total": {
    "totalOperations": 2573,
    "totalOperationsAlert": 254,
    "totalOperationsRisk": 34
  },
  "alerts": [
      {
        codAlert: "L1",
        description: "Alert 1",
        value: 1
      },
      {
        codAlert: "L2",
        description: "Alert 2",
        value: 2
      },
      ...
  ]
}

So I defined a DashboardComponent component and a AlertDashboardService service. I would like, for example, to display totalOperations and totalOperationsAlert. I don't know if I'm doing it in a correct way.

In dashboard.component.ts I have:

...
@Component({
  selector: 'app-dashboard',
  template: `

{{totalAlertsDashboard.totalOperations}}

{{totalAlertsDashboard.totalOperationsAlert}}

    ...
  `
})
export class DashboardComponent implements OnInit {
  totalAlertsDashboard: TotalAlertsDashboard;
  alertsDashboard: AlertDashboard[];

  constructor(private alertsDashboardService: AlertsDashboardService) { }

  ngOnInit() {
    this.alertsDashboardService.get().then(
      response => {
        this.totalAlertsDashboard = response.totalAlertsDashboard;
        this.alertsDashboard = response.alertsDashboard;
      }
    );
  }
}

In alerts-dashboard.service.ts I have:

...
export class AlertsDashboard {
    totalAlertsDashboard: TotalAlertsDashboard;
    alertsDashboard: AlertDashboard[];
}

export class TotalAlertsDashboard {
    totalOperations: number;
    totalOperationsAlert: number;
    totalOperationsRisk: number;
}

export class AlertDashboard {
    codAlert: string;
    description: string;
    value: number;
}

@Injectable()
export class AlertsDashboardService {
    private headers = new Headers({ 'Content-Type': 'application/json' });
    private url = environment.urlAPI + '/rest/alertsDashboard';

    constructor(private http: Http) { }

    get(): Promise<AlertsDashboard> {
        var vm = this;

        let params = new URLSearchParams();

        return vm.http.get(vm.url, { search: params })
        .toPromise()
        .then(response => {
            var responseJson: AlertsDashboard = response.json() ;
            console.log(responseJson); // it prints the JSON correctly
            return responseJson;
        });
  }
}

I hope you can help me with that.

Body:
try this :

ngOnInit() {
    this.alertsDashboardService.get().then(
      response => {
        this.totalAlertsDashboard = response.total;
        this.alertsDashboard = response.alerts;
      }
    );
  }

In alerts-dashboard.service.ts

export class AlertsDashboard {
    total: TotalAlertsDashboard;
    alerts: AlertDashboard[];
}

template :

<p>{{totalAlertsDashboard?.totalOperations}}</p>


来源: stackexchange

问:
How to close all opened drivers in Selenium?
I need to close all open Chrome drivers in Selenium. All my methods are closing only one of them. The reason why I need to close all drivers at the same time - in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle.

How I opened these drivers:

```<code>WebDriver driver = new ChromeDriver();
driver.get(firstURL);

driver = new ChromeDriver();
driver.get(secondURL);
</code>```

How I tried to close both drivers:

First try:

```<code>driver.close();
</code>```

Second try:

```<code>driver.quit();
</code>```

Third try:

```<code>driver.close();
driver.close();
</code>```

Fourth try:

```<code>driver.quit();
driver.quit();
</code>```

答:
There is only a single WebDriver driver in your Code, even though you are assigning it multiple ChromeDriver() objects. So You can just close the driver once either by using driver.close() or driver.quit();

and only the latest window will be closed all the previous windows will still remain (now which can't be contacted anymore) as the only driver was closed.

ContentLicense: CC BY-SA 3.0

Body:
I need to close all open Chrome drivers in Selenium. All my methods are closing only one of them. The reason why I need to close all drivers at the same time - in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle.

How I opened these drivers:

WebDriver driver = new ChromeDriver();
driver.get(firstURL);

driver = new ChromeDriver();
driver.get(secondURL);

How I tried to close both drivers:

First try:

driver.close();

Second try:

driver.quit();

Third try:

driver.close();
driver.close();

Fourth try:

driver.quit();
driver.quit();


问:
Symfony 3: Passing variables into forms
I'm building using the Symfony 3 Forms, and need to retrieve a collection which is dependant on the current user, within the form to render in a dropdown.

Using the EntityType I can retrieve a list of all entities, but I want to be able to run a custom query which only retrieves those which have a relationship with the current user object.

I've read the documentation on forms and the EntityType, and it explains custom queries and mentions passing in a collection as an argument. But I cannot find instructions on how this is achieved anywhere.

Ideally, I'd like to either pass in a collection I've curated in the Controller, pass in the User object to run the query inside the Form, or otherwise access the user id in the form to run the query on.

Has anyone found a solution to anything similar?

答:
You should try with

pass in the User object to run the query inside the Form

Define required parameter user in options resolver:

```<code>public function configureOptions(OptionsResolver $resolver)
{
    // ...
    $resolver->setRequired('user');
    // type validation - User instance or int, you can also pick just one.
    $resolver->setAllowedTypes('user', array(User::class, 'int'));
}
</code>```

It will force you to pass user option so you won't forget about it.

Pass user instance or user ID as an option into the form.

In controller it could look like this:

```<code>$this->createForm(SomeFormType::class, $underlyingObjectOrNull, array(
    'user' => $this->getUser(),
));
</code>```

Build a custom query for EntityType field:

```<code>$user = $options['user'];
$builder->add('someField', EntityType::class, array(
    'class' => 'AppBundle:SomeEntity',
    'query_builder' => function (EntityRepository $er) use($user) {
        return $er->createQueryBuilder('u')
           //.. -> some method building the query builder
    },
));
</code>```

Please note use($user) part which gives you access to this variable inside anonymous function.

Title: Symfony 3: Passing variables into forms

Body:
You should try with

pass in the User object to run the query inside the Form

Define required parameter user in options resolver:

public function configureOptions(OptionsResolver $resolver)
{
    // ...
    $resolver->setRequired('user');
    // type validation - User instance or int, you can also pick just one.
    $resolver->setAllowedTypes('user', array(User::class, 'int'));
}

It will force you to pass user option so you won't forget about it.

Pass user instance or user ID as an option into the form.

In controller it could look like this:

$this->createForm(SomeFormType::class, $underlyingObjectOrNull, array(
    'user' => $this->getUser(),
));

Build a custom query for EntityType field:

$user = $options['user'];
$builder->add('someField', EntityType::class, array(
    'class' => 'AppBundle:SomeEntity',
    'query_builder' => function (EntityRepository $er) use($user) {
        return $er->createQueryBuilder('u')
           //.. -> some method building the query builder
    },
));

Please note use($user) part which gives you access to this variable inside anonymous function.


问:
Xamarin and native libs
I'm considering trying Xamarin instead of writing my apps in both Swift and Java. One big thing I wondering about though is third party libraries and open source libraries. Do I generally need to find C# libraries for this, or can I use native libraries for stuff I'm used to working with or can't find a similar C# library.

Like, could I use a Gradle dependency in a Xamarin Android app or a Cocoapod dependency in a Xamarin iOS app?

答:
You can create binding project for iOS and Android libraries by yourself
But it has some limitation as well

such as Swift based project is not directly supported for binding in xamarin and there are some workarounds for that

Always check if the library that you are looking for is already available in monotouch bindings and then think about creating your own binding

Title: Xamarin and native libs


问:
How to Publish war to Glassfish in Eclipse
I am trying to make use of the ability to hot-deploy/publish web apps to Glassfish via Eclipse.  I am using Helios distribution of Eclipse with Glassfish v3.  I have set up the Glassfish server in Eclipse.  I have a servlet app (war) that I have been deploying manually via the Glassfish admin console, but would like to make changes and have them hot-deployed to the server.

I set the project to use facets and made it a dynamic web module. It's now available to add as a resource to my server.  I have confirmed that when I add/remove the resource from the server it is added/removed in Glassfish in the list of applications in the admin console.  I've set my server to "Automatically publish when resources change".

However, when I try to access the app I get a 404 error.  This is even when I choose to "launch" from the admin console.

Could somebody tell me what step I'm missing?  Is there a good, straight-forward resource that explains how to do this?

Thanks!

答: Check the glassfish server log.  It's possible the application did deploy but some exception is preventing it from working.  You can always deploy it manually using asadmin or the admin web page to make sure it's deployed and then try it.  If that works then look at eclipse related problems.</p>

ContentLicense: CC BY-SA 2.5


问:
JUnit assertions within in Java 8 stream
Say I have three objects that I save to the database and set the db generated ID into. I don't know the order of the objects returned from the method saveToDb. But I want to junit test that those generated IDs are there. How do I do that within in stream? I want to do something like this:

```<code>List<MyObject> myObjects = getObjects();
numRecords = saveToDb(myObjects); // numRecords=3
List<Integer> intArray = Arrays.asList(1, 2, 3);
intArray.stream()
  .forEach(it -> myObjects.stream()
    .filter(it2 -> it2.getId().equals(it))
    .????
</code>```

But I'm not sure where my assertEquals() would go in a statement like this. Or is my approach all wrong? I know I could use a simple for-loop, but I like the elegance of streams. Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

答:
So you basically want to check whether a MyObject instance was assigned an ID?
Is the equalness to the IDs in the array from any importance?

If not:

```<code>List<MyObject> objects = getObjects();
saveToDb(objects);
objects.stream().map(MyObject::getId).forEach(Assert::assertNotNull);
</code>```

Assuming there is a "getId" Method on MyObject of course.

Body:
Say I have three objects that I save to the database and set the db generated ID into. I don't know the order of the objects returned from the method saveToDb. But I want to junit test that those generated IDs are there. How do I do that within in stream? I want to do something like this:

List<MyObject> myObjects = getObjects();
numRecords = saveToDb(myObjects); // numRecords=3
List<Integer> intArray = Arrays.asList(1, 2, 3);
intArray.stream()
  .forEach(it -> myObjects.stream()
    .filter(it2 -> it2.getId().equals(it))
    .????

But I'm not sure where my assertEquals() would go in a statement like this. Or is my approach all wrong? I know I could use a simple for-loop, but I like the elegance of streams. Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

Body:
So you basically want to check whether a MyObject instance was assigned an ID?
Is the equalness to the IDs in the array from any importance?

If not:

List<MyObject> objects = getObjects();
saveToDb(objects);
objects.stream().map(MyObject::getId).forEach(Assert::assertNotNull);

Assuming there is a "getId" Method on MyObject of course.


问:
undefined method `to_date' for nil:NilClass on Heroku App
I have error undefined method `to_date' for nil:NilClass on my heroku server but everything work in local, i dont know how i can fix it

my helper where i call "to_date"

module BiensHelper

```<code>def sell_time(sell_date)
    time = Time.now.to_s
    time = time.to_date
    delai = time - sell_date.to_date
    delai.round
end
</code>```

end

The view where i call my helper

```<code>    <% @biens.each do |bien| %>
    <h3>
    <%= bien[:name] %> <br>
    <%= bien[:adress] %> <br>
    <%= bien[:bien_type] %> <br>
    <%= bien[:url] %> <br>
    <%= bien[:latitude] %> <br>
    <%= bien[:longitude] %> <br>
    Vendu il y a <%= sell_time(bien.sell_date) %> jours<br>
    <%= link_to "Modifier", edit_bien_path(bien), class: "btn btn-warning" %> <br>
    <%= link_to "X", bien_path(bien), method: :delete, class: "btn btn-danger" %> <br>
</h3>
<% end %>
</code>```

答:
Your error is showing that sell_date is passing nil value at line delai = time - sell_date.to_date

You can ignore this kind of error like

```<code>def sell_time(sell_date)
  if sell_date.present?
    delai = Date.today - sell_date.to_date
    delai.round
  end
end
</code>```

And

```<code>time = Time.now.to_s
time = time.to_date
</code>```

Here you are taking Time.now and then converting this to to_date instead this you can directly use Date.today.

Body:
I have error undefined method `to_date' for nil:NilClass on my heroku server but everything work in local, i dont know how i can fix it

my helper where i call "to_date"

module BiensHelper

def sell_time(sell_date)
    time = Time.now.to_s
    time = time.to_date
    delai = time - sell_date.to_date
    delai.round
end

end

The view where i call my helper

    <% @biens.each do |bien| %>

    <%= bien[:name] %>

    <%= bien[:adress] %>

    <%= bien[:bien_type] %>

    <%= bien[:url] %>

    <%= bien[:latitude] %>

    <%= bien[:longitude] %>

    Vendu il y a <%= sell_time(bien.sell_date) %> jours

    <%= link_to "Modifier", edit_bien_path(bien), class: "btn btn-warning" %>

    <%= link_to "X", bien_path(bien), method: :delete, class: "btn btn-danger" %>

<% end %>

Body:
Your error is showing that sell_date is passing nil value at line delai = time - sell_date.to_date

You can ignore this kind of error like

def sell_time(sell_date)
  if sell_date.present?
    delai = Date.today - sell_date.to_date
    delai.round
  end
end

And

time = Time.now.to_s
time = time.to_date

Here you are taking Time.now and then converting this to to_date instead this you can directly use Date.today.


问:
What is local variable and objects in memory model?
I have a class given below. In this class what are the variable going to store in heap and what are the variable going to store in Thread stack of java memory model. I know that local variable is stored in stack and objects stored in heap. but I need explanation from given class.

```<code>class School {

     public int id =1;

     public Student student=new Student();;

     public void method(Student st, int f ){

        Student stud = new Student();
        int fees = 100;
    }

}
</code>```

thanks

答:
Student stud is a reference to an object, not an object.  The reference is on the stack, the object is on the heap.

```<code>Student stud = new Student();
        ^            ^
reference on stack   object on heap
</code>```

NOTE: With Escape Analysis, an object can be placed on the stack as well, though this is an optimisation you generally don't need to know is happening.

Body:
I have a class given below. In this class what are the variable going to store in heap and what are the variable going to store in Thread stack of java memory model. I know that local variable is stored in stack and objects stored in heap. but I need explanation from given class.

class School {

     public int id =1;

     public Student student=new Student();;

     public void method(Student st, int f ){

        Student stud = new Student();
        int fees = 100;
    }

}

thanks

Body:
Student stud is a reference to an object, not an object.  The reference is on the stack, the object is on the heap.

Student stud = new Student();
        ^            ^
reference on stack   object on heap

NOTE: With Escape Analysis, an object can be placed on the stack as well, though this is an optimisation you generally don't need to know is happening.


问:
Bootstrap 4: switch between cols on mobile
I've built a standard layout with a sidebar using Bootstrap's grid system (EDIT: I'm using Bootstrap 4 but could still switch). It looks like this:

```<code><div class="row">
  <div class="col-md-3">
    ...
  </div>
  <div class="col-md-9">
    <div class="row">
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
    </div>
  </div>
</div>
</code>```

On mobile, the red area would be above the green one. I need to be able to switch between them in a way that is more convenient than scrolling, for example a switch button:

Also note the different oder of elements in the green area.

Is there a smart way to do this? Or do I have to alter the dom with JavaScript? Thanks in advance :)

答:
You can use jQuery to toggle one of the BS4 flexbox utility classes. For example, apply the flex-last on the first (col-md-3) column.

To switch the order on mobile using a button, toggle the flex-last class...

```<code>$('#btnToggle').click(function(){
    $('.col-md-3').toggleClass('flex-last');
})
</code>```

EDIT: To show only one at a time (switch the visibility of the 2 divs using a button) toggle the hidden-sm-down class instead...

```<code>$('#btnToggle').click(function(){
    $('.col-md-3, .col-md-9').toggleClass('hidden-sm-down');
})
</code>```

Demo

In Bootstrap 4, column order can be toggled using CSS only, but this switches the cols based on screen width, and therefore is not triggered by the button.

```<code><div class="row">
  <div class="col-md-3 flex-last flex-md-unordered">
    ...
  </div>
  <div class="col-md-9">
    <div class="row">
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
    </div>
  </div>
</div>
</code>```

Update

As of Bootstrap 4 Beta 3, the ordering classes are named order-*, such as order-1, order-md-2, etc..

Body:
I've built a standard layout with a sidebar using Bootstrap's grid system (EDIT: I'm using Bootstrap 4 but could still switch). It looks like this:

    ...

...

...

...

On mobile, the red area would be above the green one. I need to be able to switch between them in a way that is more convenient than scrolling, for example a switch button:

Also note the different oder of elements in the green area.

Is there a smart way to do this? Or do I have to alter the dom with JavaScript? Thanks in advance :)

Body:
You can use jQuery to toggle one of the BS4 flexbox utility classes. For example, apply the flex-last on the first (col-md-3) column.

To switch the order on mobile using a button, toggle the flex-last class...

$('#btnToggle').click(function(){
    $('.col-md-3').toggleClass('flex-last');
})

EDIT: To show only one at a time (switch the visibility of the 2 divs using a button) toggle the hidden-sm-down class instead...

$('#btnToggle').click(function(){
    $('.col-md-3, .col-md-9').toggleClass('hidden-sm-down');
})

Demo

In Bootstrap 4, column order can be toggled using CSS only, but this switches the cols based on screen width, and therefore is not triggered by the button.

<div class="row">
  <div class="col-md-3 flex-last flex-md-unordered">
    ...
  </div>
  <div class="col-md-9">
    <div class="row">
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
    </div>
  </div>
</div>

Update

As of Bootstrap 4 Beta 3, the ordering classes are named order-*, such as order-1, order-md-2, etc..


问:
where to add the line break

make a 0

```<code>def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = ("*   *")
    result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom
    return result

result = number0(5, 5, "*")
print (result)
</code>```

here's what happens when I run the program:

```<code>*****
*   **   **   **   **   *
*****
</code>```

I want to add line break in between middle and height to make it look like a 0 shape with a height of 5.

答: Try changing middle = ("*   *") to middle = "*   *\n". And don't use the last "\n" in building result.

Title: where to add the line break

Body:
make a 0

def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = ("*   *")
    result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom
    return result

result = number0(5, 5, "*")
print (result)

here's what happens when I run the program:

*****
*   **   **   **   **   *
*****

I want to add line break in between middle and height to make it look like a 0 shape with a height of 5.


问:
MySQL: Very slow update/insert/delete queries hanging on "query end" step
I have a large and heavy loaded mysql database which performs quite fast at times, but some times get terribly slow. All tables are InnoDB, server has 32GB of RAM and database size is about 40GB.

Top 20 queries in my slow_query_log are update, insert and delete queries and I cannot understand why they are so slow (up to 120 seconds sometimes!)

Here is the most frequent query:

```<code>UPDATE comment_fallows set comment_cnt_new = 0 WHERE user_id = 1;
</code>```

Profiling results:

```<code>mysql> set profiling = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> update comment_fallows set comment_cnt_new = 0 where user_id = 1;
Query OK, 0 rows affected (2.77 sec)
Rows matched: 18  Changed: 0  Warnings: 0

mysql> show profile for query 1;
+---------------------------+----------+
| Status                    | Duration |
+---------------------------+----------+
| starting                  | 0.000021 |
| checking permissions      | 0.000004 |
| Opening tables            | 0.000010 |
| System lock               | 0.000004 |
| init                      | 0.000041 |
| Searching rows for update | 0.000084 |
| Updating                  | 0.000055 |
| end                       | 0.000010 |
| query end                 | 2.766245 |
| closing tables            | 0.000007 |
| freeing items             | 0.000013 |
| logging slow query        | 0.000003 |
| cleaning up               | 0.000002 |
+---------------------------+----------+
13 rows in set (0.00 sec)
</code>```

I am using master/server replication, so the binary log is enabled. I've fallowed one advice I've found on the internet and set flush_log_at_trx_commit to 0 but it did not make any difference:

```<code>mysql> show variables like '%trx%';
+-------------------------------------------+-------+
| Variable_name                             | Value |
+-------------------------------------------+-------+
| innodb_flush_log_at_trx_commit            | 0     |
| innodb_use_global_flush_log_at_trx_commit | ON    |
+-------------------------------------------+-------+
</code>```

The table structure:

```<code>CREATE TABLE `comment_fallows` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `part_id` int(11) DEFAULT NULL,
  `article_id` int(11) DEFAULT NULL,
  `request_id` int(11) DEFAULT NULL,
  `comment_cnt` int(10) unsigned NOT NULL,
  `comment_cnt_new` int(10) unsigned NOT NULL DEFAULT '0',
  `last_comment_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`,`last_comment_date`),
  KEY `part_id` (`part_id`),
  KEY `last_comment_date` (`last_comment_date`),
  KEY `request_id` (`request_id`),
  CONSTRAINT `comment_fallows_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `comment_fallows_ibfk_2` FOREIGN KEY (`part_id`) REFERENCES `fanfic_parts` (`id`) ON DELETE CASCADE,
  CONSTRAINT `comment_fallows_ibfk_3` FOREIGN KEY (`request_id`) REFERENCES `requests` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2239419 DEFAULT CHARSET=utf8
</code>```

And all the innodb settings (server has 32 GB of RAM):

```<code>mysql> show variables like '%innodb%';
+-------------------------------------------+------------------------+
| Variable_name                             | Value                  |
+-------------------------------------------+------------------------+
| have_innodb                               | YES                    |
| ignore_builtin_innodb                     | OFF                    |
| innodb_adaptive_flushing                  | ON                     |
| innodb_adaptive_flushing_method           | estimate               |
| innodb_adaptive_hash_index                | ON                     |
| innodb_adaptive_hash_index_partitions     | 1                      |
| innodb_additional_mem_pool_size           | 16777216               |
| innodb_autoextend_increment               | 8                      |
| innodb_autoinc_lock_mode                  | 1                      |
| innodb_blocking_buffer_pool_restore       | OFF                    |
| innodb_buffer_pool_instances              | 1                      |
| innodb_buffer_pool_restore_at_startup     | 0                      |
| innodb_buffer_pool_shm_checksum           | ON                     |
| innodb_buffer_pool_shm_key                | 0                      |
| innodb_buffer_pool_size                   | 21474836480            |
| innodb_change_buffering                   | all                    |
| innodb_checkpoint_age_target              | 0                      |
| innodb_checksums                          | ON                     |
| innodb_commit_concurrency                 | 0                      |
| innodb_concurrency_tickets                | 500                    |
| innodb_corrupt_table_action               | assert                 |
| innodb_data_file_path                     | ibdata1:10M:autoextend |
| innodb_data_home_dir                      |                        |
| innodb_dict_size_limit                    | 0                      |
| innodb_doublewrite                        | ON                     |
| innodb_doublewrite_file                   |                        |
| innodb_fake_changes                       | OFF                    |
| innodb_fast_checksum                      | OFF                    |
| innodb_fast_shutdown                      | 1                      |
| innodb_file_format                        | Antelope               |
| innodb_file_format_check                  | ON                     |
| innodb_file_format_max                    | Antelope               |
| innodb_file_per_table                     | ON                     |
| innodb_flush_log_at_trx_commit            | 0                      |
| innodb_flush_method                       |                        |
| innodb_flush_neighbor_pages               | area                   |
| innodb_force_load_corrupted               | OFF                    |
| innodb_force_recovery                     | 0                      |
| innodb_ibuf_accel_rate                    | 100                    |
| innodb_ibuf_active_contract               | 1                      |
| innodb_ibuf_max_size                      | 10737401856            |
| innodb_import_table_from_xtrabackup       | 0                      |
| innodb_io_capacity                        | 10000                  |
| innodb_kill_idle_transaction              | 0                      |
| innodb_large_prefix                       | OFF                    |
| innodb_lazy_drop_table                    | 0                      |
| innodb_lock_wait_timeout                  | 120                    |
| innodb_locks_unsafe_for_binlog            | OFF                    |
| innodb_log_block_size                     | 512                    |
| innodb_log_buffer_size                    | 8388608                |
| innodb_log_file_size                      | 268435456              |
| innodb_log_files_in_group                 | 3                      |
| innodb_log_group_home_dir                 | ./                     |
| innodb_max_dirty_pages_pct                | 90                     |
| innodb_max_purge_lag                      | 0                      |
| innodb_mirrored_log_groups                | 1                      |
| innodb_old_blocks_pct                     | 37                     |
| innodb_old_blocks_time                    | 0                      |
| innodb_open_files                         | 300                    |
| innodb_page_size                          | 16384                  |
| innodb_purge_batch_size                   | 20                     |
| innodb_purge_threads                      | 1                      |
| innodb_random_read_ahead                  | OFF                    |
| innodb_read_ahead                         | linear                 |
| innodb_read_ahead_threshold               | 56                     |
| innodb_read_io_threads                    | 8                      |
| innodb_recovery_stats                     | OFF                    |
| innodb_recovery_update_relay_log          | OFF                    |
| innodb_replication_delay                  | 0                      |
| innodb_rollback_on_timeout                | OFF                    |
| innodb_rollback_segments                  | 128                    |
| innodb_show_locks_held                    | 10                     |
| innodb_show_verbose_locks                 | 0                      |
| innodb_spin_wait_delay                    | 6                      |
| innodb_stats_auto_update                  | 1                      |
| innodb_stats_method                       | nulls_equal            |
| innodb_stats_on_metadata                  | ON                     |
| innodb_stats_sample_pages                 | 8                      |
| innodb_stats_update_need_lock             | 1                      |
| innodb_strict_mode                        | OFF                    |
| innodb_support_xa                         | ON                     |
| innodb_sync_spin_loops                    | 30                     |
| innodb_table_locks                        | ON                     |
| innodb_thread_concurrency                 | 16                     |
| innodb_thread_concurrency_timer_based     | OFF                    |
| innodb_thread_sleep_delay                 | 10000                  |
| innodb_use_global_flush_log_at_trx_commit | ON                     |
| innodb_use_native_aio                     | ON                     |
| innodb_use_sys_malloc                     | ON                     |
| innodb_use_sys_stats_table                | OFF                    |
| innodb_version                            | 1.1.8-rel25.1          |
| innodb_write_io_threads                   | 8                      |
+-------------------------------------------+------------------------+
92 rows in set (0.00 sec)
</code>```

I've been struggling with this problem for weeks and would be very greatfull for any advice on how to solve this problem.

Why could my update, insert and delete queries be so slow on query end step?

update

I have disabled query cache, but update, insert and delete queries are still very very slow (nothing changed)

```<code>show variables like '%cache%';
+------------------------------+----------------------+
| Variable_name                | Value                |
+------------------------------+----------------------+
| binlog_cache_size            | 4194304              |
| binlog_stmt_cache_size       | 32768                |
| have_query_cache             | YES                  |
| key_cache_age_threshold      | 300                  |
| key_cache_block_size         | 1024                 |
| key_cache_division_limit     | 100                  |
| max_binlog_cache_size        | 18446744073709547520 |
| max_binlog_stmt_cache_size   | 18446744073709547520 |
| metadata_locks_cache_size    | 1024                 |
| query_cache_limit            | 16777216             |
| query_cache_min_res_unit     | 4096                 |
| query_cache_size             | 0                    |
| query_cache_strip_comments   | OFF                  |
| query_cache_type             | ON                   |
| query_cache_wlock_invalidate | OFF                  |
| stored_program_cache         | 256                  |
| table_definition_cache       | 400                  |
| table_open_cache             | 2048                 |
| thread_cache_size            | 8                    |
+------------------------------+----------------------+
</code>```

答:
It is probably due to slow disk writes.

In our case it was because Debian GNU/Linux running mysqld was virtualised in Hyper-V, and even if it was given SSD storage hdparm -t was giving terrible results (10-20MB/s instead of 600MB/s that it gets on raw hardware)

Body:
I have a large and heavy loaded mysql database which performs quite fast at times, but some times get terribly slow. All tables are InnoDB, server has 32GB of RAM and database size is about 40GB.

Top 20 queries in my slow_query_log are update, insert and delete queries and I cannot understand why they are so slow (up to 120 seconds sometimes!)

Here is the most frequent query:

UPDATE comment_fallows set comment_cnt_new = 0 WHERE user_id = 1;

Profiling results:

mysql> set profiling = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> update comment_fallows set comment_cnt_new = 0 where user_id = 1;
Query OK, 0 rows affected (2.77 sec)
Rows matched: 18  Changed: 0  Warnings: 0

mysql> show profile for query 1;
+---------------------------+----------+
| Status                    | Duration |
+---------------------------+----------+
| starting                  | 0.000021 |
| checking permissions      | 0.000004 |
| Opening tables            | 0.000010 |
| System lock               | 0.000004 |
| init                      | 0.000041 |
| Searching rows for update | 0.000084 |
| Updating                  | 0.000055 |
| end                       | 0.000010 |
| query end                 | 2.766245 |
| closing tables            | 0.000007 |
| freeing items             | 0.000013 |
| logging slow query        | 0.000003 |
| cleaning up               | 0.000002 |
+---------------------------+----------+
13 rows in set (0.00 sec)

I am using master/server replication, so the binary log is enabled. I've fallowed one advice I've found on the internet and set flush_log_at_trx_commit to 0 but it did not make any difference:

mysql> show variables like '%trx%';
+-------------------------------------------+-------+
| Variable_name                             | Value |
+-------------------------------------------+-------+
| innodb_flush_log_at_trx_commit            | 0     |
| innodb_use_global_flush_log_at_trx_commit | ON    |
+-------------------------------------------+-------+

The table structure:

CREATE TABLE `comment_fallows` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `part_id` int(11) DEFAULT NULL,
  `article_id` int(11) DEFAULT NULL,
  `request_id` int(11) DEFAULT NULL,
  `comment_cnt` int(10) unsigned NOT NULL,
  `comment_cnt_new` int(10) unsigned NOT NULL DEFAULT '0',
  `last_comment_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`,`last_comment_date`),
  KEY `part_id` (`part_id`),
  KEY `last_comment_date` (`last_comment_date`),
  KEY `request_id` (`request_id`),
  CONSTRAINT `comment_fallows_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `comment_fallows_ibfk_2` FOREIGN KEY (`part_id`) REFERENCES `fanfic_parts` (`id`) ON DELETE CASCADE,
  CONSTRAINT `comment_fallows_ibfk_3` FOREIGN KEY (`request_id`) REFERENCES `requests` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2239419 DEFAULT CHARSET=utf8

And all the innodb settings (server has 32 GB of RAM):

mysql> show variables like '%innodb%';
+-------------------------------------------+------------------------+
| Variable_name                             | Value                  |
+-------------------------------------------+------------------------+
| have_innodb                               | YES                    |
| ignore_builtin_innodb                     | OFF                    |
| innodb_adaptive_flushing                  | ON                     |
| innodb_adaptive_flushing_method           | estimate               |
| innodb_adaptive_hash_index                | ON                     |
| innodb_adaptive_hash_index_partitions     | 1                      |
| innodb_additional_mem_pool_size           | 16777216               |
| innodb_autoextend_increment               | 8                      |
| innodb_autoinc_lock_mode                  | 1                      |
| innodb_blocking_buffer_pool_restore       | OFF                    |
| innodb_buffer_pool_instances              | 1                      |
| innodb_buffer_pool_restore_at_startup     | 0                      |
| innodb_buffer_pool_shm_checksum           | ON                     |
| innodb_buffer_pool_shm_key                | 0                      |
| innodb_buffer_pool_size                   | 21474836480            |
| innodb_change_buffering                   | all                    |
| innodb_checkpoint_age_target              | 0                      |
| innodb_checksums                          | ON                     |
| innodb_commit_concurrency                 | 0                      |
| innodb_concurrency_tickets                | 500                    |
| innodb_corrupt_table_action               | assert                 |
| innodb_data_file_path                     | ibdata1:10M:autoextend |
| innodb_data_home_dir                      |                        |
| innodb_dict_size_limit                    | 0                      |
| innodb_doublewrite                        | ON                     |
| innodb_doublewrite_file                   |                        |
| innodb_fake_changes                       | OFF                    |
| innodb_fast_checksum                      | OFF                    |
| innodb_fast_shutdown                      | 1                      |
| innodb_file_format                        | Antelope               |
| innodb_file_format_check                  | ON                     |
| innodb_file_format_max                    | Antelope               |
| innodb_file_per_table                     | ON                     |
| innodb_flush_log_at_trx_commit            | 0                      |
| innodb_flush_method                       |                        |
| innodb_flush_neighbor_pages               | area                   |
| innodb_force_load_corrupted               | OFF                    |
| innodb_force_recovery                     | 0                      |
| innodb_ibuf_accel_rate                    | 100                    |
| innodb_ibuf_active_contract               | 1                      |
| innodb_ibuf_max_size                      | 10737401856            |
| innodb_import_table_from_xtrabackup       | 0                      |
| innodb_io_capacity                        | 10000                  |
| innodb_kill_idle_transaction              | 0                      |
| innodb_large_prefix                       | OFF                    |
| innodb_lazy_drop_table                    | 0                      |
| innodb_lock_wait_timeout                  | 120                    |
| innodb_locks_unsafe_for_binlog            | OFF                    |
| innodb_log_block_size                     | 512                    |
| innodb_log_buffer_size                    | 8388608                |
| innodb_log_file_size                      | 268435456              |
| innodb_log_files_in_group                 | 3                      |
| innodb_log_group_home_dir                 | ./                     |
| innodb_max_dirty_pages_pct                | 90                     |
| innodb_max_purge_lag                      | 0                      |
| innodb_mirrored_log_groups                | 1                      |
| innodb_old_blocks_pct                     | 37                     |
| innodb_old_blocks_time                    | 0                      |
| innodb_open_files                         | 300                    |
| innodb_page_size                          | 16384                  |
| innodb_purge_batch_size                   | 20                     |
| innodb_purge_threads                      | 1                      |
| innodb_random_read_ahead                  | OFF                    |
| innodb_read_ahead                         | linear                 |
| innodb_read_ahead_threshold               | 56                     |
| innodb_read_io_threads                    | 8                      |
| innodb_recovery_stats                     | OFF                    |
| innodb_recovery_update_relay_log          | OFF                    |
| innodb_replication_delay                  | 0                      |
| innodb_rollback_on_timeout                | OFF                    |
| innodb_rollback_segments                  | 128                    |
| innodb_show_locks_held                    | 10                     |
| innodb_show_verbose_locks                 | 0                      |
| innodb_spin_wait_delay                    | 6                      |
| innodb_stats_auto_update                  | 1                      |
| innodb_stats_method                       | nulls_equal            |
| innodb_stats_on_metadata                  | ON                     |
| innodb_stats_sample_pages                 | 8                      |
| innodb_stats_update_need_lock             | 1                      |
| innodb_strict_mode                        | OFF                    |
| innodb_support_xa                         | ON                     |
| innodb_sync_spin_loops                    | 30                     |
| innodb_table_locks                        | ON                     |
| innodb_thread_concurrency                 | 16                     |
| innodb_thread_concurrency_timer_based     | OFF                    |
| innodb_thread_sleep_delay                 | 10000                  |
| innodb_use_global_flush_log_at_trx_commit | ON                     |
| innodb_use_native_aio                     | ON                     |
| innodb_use_sys_malloc                     | ON                     |
| innodb_use_sys_stats_table                | OFF                    |
| innodb_version                            | 1.1.8-rel25.1          |
| innodb_write_io_threads                   | 8                      |
+-------------------------------------------+------------------------+
92 rows in set (0.00 sec)

I've been struggling with this problem for weeks and would be very greatfull for any advice on how to solve this problem.

Why could my update, insert and delete queries be so slow on query end step?

update

I have disabled query cache, but update, insert and delete queries are still very very slow (nothing changed)

show variables like '%cache%';
+------------------------------+----------------------+
| Variable_name                | Value                |
+------------------------------+----------------------+
| binlog_cache_size            | 4194304              |
| binlog_stmt_cache_size       | 32768                |
| have_query_cache             | YES                  |
| key_cache_age_threshold      | 300                  |
| key_cache_block_size         | 1024                 |
| key_cache_division_limit     | 100                  |
| max_binlog_cache_size        | 18446744073709547520 |
| max_binlog_stmt_cache_size   | 18446744073709547520 |
| metadata_locks_cache_size    | 1024                 |
| query_cache_limit            | 16777216             |
| query_cache_min_res_unit     | 4096                 |
| query_cache_size             | 0                    |
| query_cache_strip_comments   | OFF                  |
| query_cache_type             | ON                   |
| query_cache_wlock_invalidate | OFF                  |
| stored_program_cache         | 256                  |
| table_definition_cache       | 400                  |
| table_open_cache             | 2048                 |
| thread_cache_size            | 8                    |
+------------------------------+----------------------+


问:
How to update table2 from table1, into corresponding entry in table2?
I want to count the occurrences of banks in different tables, and update in corresponding columns of FinalTable.

BankTable:

```<code>  BankName  ErrorCode
    SBI         200
    ICICI       200
    SBI         400
    SBI         500
    SBI         503
</code>```

ATMTable:

```<code>BankName    ErrorCode
ICICI       200
ICICI       400
ICICI       400
SBI         500
SBI         503
</code>```

MitraTable:

```<code>BankName    ErrorCode
ICICI        200
ICICI        200
SBI          400
SBI          500
SBI          503
PNB          501
</code>```

FinalTable:

```<code>BankName    BankCount   ATMCount    MitraCount  TotalCount
ICICI            1         3           2          6
SBI              4         2           3          9
PNB              0         0           1          1
</code>```

I want to count the occurances of different banks and set the values in FinalTable.

答:
Try this: </p>

```<code>SELECT BankName,
       SUM(BankCount) AS BankCount,
       SUM(ATMCount) AS ATMCount,
       SUM(MitraCount) AS MitraCount,
       SUM(BankCount + ATMCount + MitraCount) AS TotalCount
FROM (SELECT BankName,
             COUNT(ErrorCode) AS BankCount,
             0 AS ATMCount,
             0 AS MitraCount
      FROM BankTable
      GROUP BY BankName
     UNION
      SELECT BankName,
             0 AS BankCount,
             COUNT(ErrorCode) AS ATMCount,
             0 AS MitraCount
      FROM ATMTable
      GROUP BY BankName
     UNION
      SELECT BankName,
             0 AS BankCount,
             0 AS ATMCount,
             COUNT(ErrorCode) AS MitraCount
      FROM MitraTable
      GROUP BY BankName
    ) AS A
GROUP BY BankName;
</code>```

Body:
I want to count the occurrences of banks in different tables, and update in corresponding columns of FinalTable.

BankTable:

  BankName  ErrorCode
    SBI         200
    ICICI       200
    SBI         400
    SBI         500
    SBI         503

ATMTable:

BankName    ErrorCode
ICICI       200
ICICI       400
ICICI       400
SBI         500
SBI         503

MitraTable:

BankName    ErrorCode
ICICI        200
ICICI        200
SBI          400
SBI          500
SBI          503
PNB          501

FinalTable:

BankName    BankCount   ATMCount    MitraCount  TotalCount
ICICI            1         3           2          6
SBI              4         2           3          9
PNB              0         0           1          1

I want to count the occurances of different banks and set the values in FinalTable.

Body:
Try this:

SELECT BankName,
       SUM(BankCount) AS BankCount,
       SUM(ATMCount) AS ATMCount,
       SUM(MitraCount) AS MitraCount,
       SUM(BankCount + ATMCount + MitraCount) AS TotalCount
FROM (SELECT BankName,
             COUNT(ErrorCode) AS BankCount,
             0 AS ATMCount,
             0 AS MitraCount
      FROM BankTable
      GROUP BY BankName
     UNION
      SELECT BankName,
             0 AS BankCount,
             COUNT(ErrorCode) AS ATMCount,
             0 AS MitraCount
      FROM ATMTable
      GROUP BY BankName
     UNION
      SELECT BankName,
             0 AS BankCount,
             0 AS ATMCount,
             COUNT(ErrorCode) AS MitraCount
      FROM MitraTable
      GROUP BY BankName
    ) AS A
GROUP BY BankName;


问:
Calling Tabs inside a Tab? Jquerymobile
I just ran into a Problem. I have a page that has the Tabs widget embeded. The Tabs are working fine. But when I try linking a tab in one Tab the link won't work.

```<code><div data-role="tabs">
  <div data-role="navbar">
<li><a href="#tab1">Link 1</a></li>
<li><a href="#tab2">Link 2</a></li>
<li><a href="#tab3">Link 3</a></li>
</div>
<div id="tab1">
  <div data-role="tabs">
  <div data-role="listview" data-inset="true">
  <li><a href="#tab1">Link 1</a></li>
  <li><a href="#tab2">Link 2</a></li>
  <li><a href="#tab3">Link 3</a></li>
  </div>
  </div>
  </div>
<div id="tab2">
 <p>Content</p>
  </div>
<div id="tab3">
 <p>Content</p>
  </div>
</div>
</div>
</code>```

This is roughly my idea. The Tabs work but the Links inside the first tab don't. Is it possible to do this? For extra Reference:

http://demos.jquerymobile.com/1.4.5/tabs/

答:
So I did some research. According to my Javascript Console there is an Error which makes the links not work inside any of the Tabs. So then I had an Idea of a Workaround. Instead of Linking directly to the Tabs, I binded the Buttons to the Tab links like so:

```<code><a OnClick="document.getElementById('#IdOfTab').click()">Link</a>
</code>```

This works perfectly. It was as simple as calling the tab instead of trying to link to the page itself. I apologize for not being precise enough in my question.

Title: Calling Tabs inside a Tab? Jquerymobile

Body:
I just ran into a Problem. I have a page that has the Tabs widget embeded. The Tabs are working fine. But when I try linking a tab in one Tab the link won't work.

Link 1

Link 2

Link 3

Link 1

Link 2

Link 3

Content

Content

This is roughly my idea. The Tabs work but the Links inside the first tab don't. Is it possible to do this? For extra Reference:

http://demos.jquerymobile.com/1.4.5/tabs/

Body:
So I did some research. According to my Javascript Console there is an Error which makes the links not work inside any of the Tabs. So then I had an Idea of a Workaround. Instead of Linking directly to the Tabs, I binded the Buttons to the Tab links like so:

<a OnClick="document.getElementById('#IdOfTab').click()">Link</a>

This works perfectly. It was as simple as calling the tab instead of trying to link to the page itself. I apologize for not being precise enough in my question.


问:
how to count number of click on google map marker in android
How to get the number of click/tap on a marker in google maps.</p>

```<code>@Override
public boolean onMarkerClick(Marker point) {
    Toast.makeText(MapsActivity.this, point.getTitle(), Toast.LENGTH_SHORT).show();
    Integer clickCount = (Integer) point.getTag();

    // Check if a click count was set, then display the click count.
    if (clickCount != null) {
        clickCount = clickCount + 1;
        point.setTag(clickCount);
        Toast.makeText(this, point.getTitle() + " has been clicked " + clickCount + " times.", Toast.LENGTH_SHORT).show();
    }

    return true;
}
</code>```

答:
You almost had it working:</p>

```<code>@Override
public boolean onMarkerClick(Marker point) {
    Toast.makeText(MapsActivity.this, point.getTitle(), Toast.LENGTH_SHORT).show();
    Integer clickCount = (Integer) point.getTag();

    if (clickCount == null) {
        clickCount = 0;
    }

    clickCount = clickCount + 1;
    point.setTag(clickCount);
    Toast.makeText(this, point.getTitle() + " has been clicked " + clickCount + " times.", Toast.LENGTH_SHORT).show();

    return true;
}
</code>```

Body:
How to get the number of click/tap on a marker in google maps.

@Override
public boolean onMarkerClick(Marker point) {
    Toast.makeText(MapsActivity.this, point.getTitle(), Toast.LENGTH_SHORT).show();
    Integer clickCount = (Integer) point.getTag();

    // Check if a click count was set, then display the click count.
    if (clickCount != null) {
        clickCount = clickCount + 1;
        point.setTag(clickCount);
        Toast.makeText(this, point.getTitle() + " has been clicked " + clickCount + " times.", Toast.LENGTH_SHORT).show();
    }

    return true;
}

Body:
You almost had it working:

@Override
public boolean onMarkerClick(Marker point) {
    Toast.makeText(MapsActivity.this, point.getTitle(), Toast.LENGTH_SHORT).show();
    Integer clickCount = (Integer) point.getTag();

    if (clickCount == null) {
        clickCount = 0;
    }

    clickCount = clickCount + 1;
    point.setTag(clickCount);
    Toast.makeText(this, point.getTitle() + " has been clicked " + clickCount + " times.", Toast.LENGTH_SHORT).show();

    return true;
}


问:
SQL Finding maximum average time for distinct cell
I have a table with large number of records for which i am trying to find only 10 numbers with the largest average time per number.

So the table may look like so:

```<code>number  |   time
012345  |  10s
012345  |  20s
055555  |  50s
055555  |  30s
068976  |  11s
etc...
</code>```

and the output should look like so:

```<code>number  |  time
012345  |  15s
055555  |  40s
068976  |  11s
</code>```

tried this but to no avail

```<code>select distinct(destination), avg(totalqueuetime)
from call
group by destination, totalqueuetime
order by totalqueue time desc limit 10;
</code>```

it does not seem to group the numbers.

答:
Your group by has two keys.  It should only have one:

```<code>select destination, avg(totalqueuetime)
from call
group by destination
order by totalqueue time desc
limit 10;
</code>```

Notes on the use of distinct.  select distinct is almost never needed with group by.  In fact, in almost all cases, you don't need select distinct at all -- because you can use group by.

In addition, distinct is not a function.  It applies to the entire entire row.  So, don't use parentheses around the first column, unless you want to confuse yourself.

Body:
I have a table with large number of records for which i am trying to find only 10 numbers with the largest average time per number.

So the table may look like so:

number  |   time
012345  |  10s
012345  |  20s
055555  |  50s
055555  |  30s
068976  |  11s
etc...

and the output should look like so:

number  |  time
012345  |  15s
055555  |  40s
068976  |  11s

tried this but to no avail

select distinct(destination), avg(totalqueuetime)
from call
group by destination, totalqueuetime
order by totalqueue time desc limit 10;

it does not seem to group the numbers.

Body:
Your group by has two keys.  It should only have one:

select destination, avg(totalqueuetime)
from call
group by destination
order by totalqueue time desc
limit 10;

Notes on the use of distinct.  select distinct is almost never needed with group by.  In fact, in almost all cases, you don't need select distinct at all -- because you can use group by.

In addition, distinct is not a function.  It applies to the entire entire row.  So, don't use parentheses around the first column, unless you want to confuse yourself.


问:
how to create a list of lists using list comprehension
I want to create a list of lists using list comprehension.
ex
[range(3),range(3),range(3)]
i.e all possible coordinates of a 3d system from 0 to 3
How to do this using only list comprehension and nothing else

I tried doing

```<code>coordinates=[x for x in range(3)[y for y in range(3)[z for z in range(3)]]]
</code>```

Body:
I want to create a list of lists using list comprehension.
ex
[range(3),range(3),range(3)]
i.e all possible coordinates of a 3d system from 0 to 3
How to do this using only list comprehension and nothing else

I tried doing

coordinates=[x for x in range(3)[y for y in range(3)[z for z in range(3)]]]

Body:
[[n,d,e] for e in [0,1,1] for d in [0,0,0] for n in [1,1,1]]

Output:

[[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
<..>

Change/add variables and source lists as needed.


问:
RobotFramework: How to set random number as a constant in resources file
I want to do generate a random number for the value, but the resources file doesn't allow to use keywords as far as I am aware. Is there a way to do this? As I need a random value every time I run the cod. The value is then used by 2 scripts.</p>

```<code>*** Settings ***
Resource        resources/resources.txt
Library         RequestsLibrary
Library         Collections
Library         DatabaseLibrary

*** Variables ***
${ENVIRONMENT_TO_RUN_AGAINST}       https://sw3-test.site.com
${auth_key}                         1111122
</code>```

答:
You can create a keyword that generates a random key, and then use that in a suite setup in your test case files.

I'm not sure what you mean by "used by 2 scripts". I if you mean "2 test cases in a suite" you can set a suite-level variable. If you mean "2 different suites" you can set a global variable.

```<code>*** Keywords ***
Generate random auth key
    ${auth}=  blah blah blah
    set suite variable    ${auth}

*** Settings ***
Suite Setup    generate random auth key
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to do generate a random number for the value, but the resources file doesn't allow to use keywords as far as I am aware. Is there a way to do this? As I need a random value every time I run the cod. The value is then used by 2 scripts.

*** Settings ***
Resource        resources/resources.txt
Library         RequestsLibrary
Library         Collections
Library         DatabaseLibrary

*** Variables ***
${ENVIRONMENT_TO_RUN_AGAINST}       https://sw3-test.site.com
${auth_key}                         1111122

Body:
You can create a keyword that generates a random key, and then use that in a suite setup in your test case files.

I'm not sure what you mean by "used by 2 scripts". I if you mean "2 test cases in a suite" you can set a suite-level variable. If you mean "2 different suites" you can set a global variable.

*** Keywords ***
Generate random auth key
    ${auth}=  blah blah blah
    set suite variable    ${auth}

*** Settings ***
Suite Setup    generate random auth key


问:
phpMyAdmin Replace Query
I recently encountered an error when running a query in phpMyAdmin to replace the values copied over from my main site's database, with the values of my staging site's database.

I have run this query in the past and it was able to replace the values for the staging site's database and found it strange that it doesn't work now? Would you know why this is occurring?

You can see the query that I ran in phpMyAdmin below:

```<code>UPDATE wp2_options SET option_value = REPLACE(option_value, ‘example.org’, ‘dev.example.org’);
UPDATE wp2_postmeta SET meta_value = REPLACE(meta_value, ‘example.org’, ‘dev.example.org’);
UPDATE wp2_posts SET guid = REPLACE(guid, ‘example.org’, ‘dev.example.org’);
UPDATE wp2_posts SET post_content = REPLACE(post_content, ‘example.org’, ‘dev.example.org’);
</code>```

You can see the error that followed from running the query in phpMyAdmin below:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '://example.orgâ€™, â€˜http://dev.example.orgâ€™)' at line 1

Thanks,

Josh Gomes

答:
You are using apostrophes ‘ and ’ instead of single (or double) quotes.

Both of the following queries should work :

```<code>UPDATE wp2_options SET option_value = REPLACE(option_value, 'example.org', 'dev.example.org');
</code>```

And

```<code>UPDATE wp2_options SET option_value = REPLACE(option_value, "example.org", "dev.example.org");
</code>```

Title: phpMyAdmin Replace Query

Body:
I recently encountered an error when running a query in phpMyAdmin to replace the values copied over from my main site's database, with the values of my staging site's database.

I have run this query in the past and it was able to replace the values for the staging site's database and found it strange that it doesn't work now? Would you know why this is occurring?

You can see the query that I ran in phpMyAdmin below:

UPDATE wp2_options SET option_value = REPLACE(option_value, ‘example.org’, ‘dev.example.org’);
UPDATE wp2_postmeta SET meta_value = REPLACE(meta_value, ‘example.org’, ‘dev.example.org’);
UPDATE wp2_posts SET guid = REPLACE(guid, ‘example.org’, ‘dev.example.org’);
UPDATE wp2_posts SET post_content = REPLACE(post_content, ‘example.org’, ‘dev.example.org’);

You can see the error that followed from running the query in phpMyAdmin below:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '://example.orgâ€™, â€˜http://dev.example.orgâ€™)' at line 1

Thanks,

Josh Gomes

Body:
You are using apostrophes ‘ and ’ instead of single (or double) quotes.

Both of the following queries should work :

UPDATE wp2_options SET option_value = REPLACE(option_value, 'example.org', 'dev.example.org');

And

UPDATE wp2_options SET option_value = REPLACE(option_value, "example.org", "dev.example.org");


问:
Improving performance of loops in python
I can't think another way to optimize my code. I used a nested for loop and my computer simply crashes. So I think the problem is my code. I'd like some help.

I need to check if a list of strings(basically words) is in the rows of a column of my df. It needs to go through each row and check if the word is in there. I thought it wouldn't be so difficult. Well I was terribly wrong. I imported the excel files. There are 3 in total.

```<code>filename='XXXX'
df = pd.read_excel(filename, sheetname='Data',index_col=0)`

df.columns:[['text', 'date', 'books', 'price']]

list_1 = ['apple', 'orange' , 'lime', 'pear']
list_2 = ['#loveapple', '#hateorange', '#likepear']

a = []
for word in df.text:
    for fruit in list_1:
        for tag in list_2:
            if fruit in word:
                fruit_list =fruit,word
            elif tag in word:
                tag_list = tag, word
                all_data = [fruit_list,tag_list]
                a.append(all_data)
</code>```

TypeError: 'in ' requires string as left operand, not numpy.int64

(I run in the past, but now it says TypeError)

I've been reading some of the posts but I can't find a case where you pass a whole list. The examples I found show a string only and it didn't work with a list. I also tried other tools like xxx.str.contains, but it didn't work.

I put the word twice so I can merge the 2 tables on word. However, it iterates with more than 35k rows so it's not working at all. I need to 'filter' the data first so I can analyze later on.

Thanks in advance.

答:
You can use the apply method on the pandas column.  Write a function that performs the comparison you wish to do, then apply that function to the appropriate column e.g.:

```<code>def compare_string(s):
    s = str(s)  # This is necessary in case there are empty values in your Excel file.
    list_1 = ['apple', 'orange' , 'lime', 'pear']
    for fruit in list_1:
        if fruit in s:
            ...
</code>```

Then you just call:

```<code>a = df.text.apply(compare_string)
</code>```

If you have any empty values in your Excel file, they will be read as numpy.nan which is type numpy.int64.  That's probably why you're getting the type error.  Using the apply method and converting each element in the column to a string should take care of the TypeError and also improve the clarity/performance of your code.

Body:
I can't think another way to optimize my code. I used a nested for loop and my computer simply crashes. So I think the problem is my code. I'd like some help.

I need to check if a list of strings(basically words) is in the rows of a column of my df. It needs to go through each row and check if the word is in there. I thought it wouldn't be so difficult. Well I was terribly wrong. I imported the excel files. There are 3 in total.

filename='XXXX'
df = pd.read_excel(filename, sheetname='Data',index_col=0)`

df.columns:[['text', 'date', 'books', 'price']]

list_1 = ['apple', 'orange' , 'lime', 'pear']
list_2 = ['#loveapple', '#hateorange', '#likepear']

a = []
for word in df.text:
    for fruit in list_1:
        for tag in list_2:
            if fruit in word:
                fruit_list =fruit,word
            elif tag in word:
                tag_list = tag, word
                all_data = [fruit_list,tag_list]
                a.append(all_data)

TypeError: 'in ' requires string as left operand, not numpy.int64

(I run in the past, but now it says TypeError)

I've been reading some of the posts but I can't find a case where you pass a whole list. The examples I found show a string only and it didn't work with a list. I also tried other tools like xxx.str.contains, but it didn't work.

I put the word twice so I can merge the 2 tables on word. However, it iterates with more than 35k rows so it's not working at all. I need to 'filter' the data first so I can analyze later on.

Thanks in advance.

Body:
You can use the apply method on the pandas column.  Write a function that performs the comparison you wish to do, then apply that function to the appropriate column e.g.:

def compare_string(s):
    s = str(s)  # This is necessary in case there are empty values in your Excel file.
    list_1 = ['apple', 'orange' , 'lime', 'pear']
    for fruit in list_1:
        if fruit in s:
            ...

Then you just call:

a = df.text.apply(compare_string)

If you have any empty values in your Excel file, they will be read as numpy.nan which is type numpy.int64.  That's probably why you're getting the type error.  Using the apply method and converting each element in the column to a string should take care of the TypeError and also improve the clarity/performance of your code.


答: maybe:  result = toporbottom + "\n" + (middle + "\n") * height + toporbottom</p>

Title: where to add the line break

Body:
make a 0

def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = ("*   *")
    result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom
    return result

result = number0(5, 5, "*")
print (result)

here's what happens when I run the program:

*****
*   **   **   **   **   *
*****

I want to add line break in between middle and height to make it look like a 0 shape with a height of 5.


答:
It seems (if i understood correctly), how about something like this:</p>

```<code> boolean result = Arrays.asList(1, 2, 3).stream()
            .allMatch(i -> objects
                .stream()
                .map(MyObject::getId)
                .filter(j -> j == i).findAny().isPresent());
    Assert.assertTrue(result);
</code>```

Title: JUnit assertions within in Java 8 stream

Body:
Say I have three objects that I save to the database and set the db generated ID into. I don't know the order of the objects returned from the method saveToDb. But I want to junit test that those generated IDs are there. How do I do that within in stream? I want to do something like this:

List<MyObject> myObjects = getObjects();
numRecords = saveToDb(myObjects); // numRecords=3
List<Integer> intArray = Arrays.asList(1, 2, 3);
intArray.stream()
  .forEach(it -> myObjects.stream()
    .filter(it2 -> it2.getId().equals(it))
    .????

But I'm not sure where my assertEquals() would go in a statement like this. Or is my approach all wrong? I know I could use a simple for-loop, but I like the elegance of streams. Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

Body:
It seems (if i understood correctly), how about something like this:

 boolean result = Arrays.asList(1, 2, 3).stream()
            .allMatch(i -> objects
                .stream()
                .map(MyObject::getId)
                .filter(j -> j == i).findAny().isPresent());
    Assert.assertTrue(result);


问:
How to resolve conflicts in EGit
I am using EGit on Eclipse v4.3 (Kepler). I want to commit and push my changes. I do a pull first and one file is conflicting. After manually resolving the conflict (local and remote are the same now), I am still running into problems.

Here are the error messages for each action:

Push to upstream

master: master [rejected - non-fast-forward]

Pull

Cannot pull into a repository with state: MERGING_RESOLVED

Mark as merged

Failed to add resource to index Failed to add resource to index Exception caught during execution of add command

Hard reset

An internal error occurred during: "Resetting to refs/heads/master".
  Exception caught during execution of reset command. {0}

How can I remove the conflict and push my changes? What am I doing wrong?

答:
This guide was helpful for me
http://wiki.eclipse.org/EGit/User_Guide#Resolving_a_merge_conflict.

UPDATED
Just a note on that about my procedure, this is how I proceed:

Commit My change

Fetch (Syncrhonize workspace)

Pull

Manage Conflicts with Merge Tool (Team->Merge Tool) and Save

Add each file to stage (Team -> Add to index)

Now the Commit Message in the Stage window is prefilled with "Merged XXX". You can leave as it is or change the commit message

Commit and Push

It is dangerous in some cases but it is very usefull to avoid to use external tool like Git Extension or Source Tree

Title: How to resolve conflicts in EGit


问:
Tracking History in HP QC(Quality Center)
Is there a way to tracking a bug's history in QC? What I am trying to get is how many bugs are being reopened over a release and how many times it got reopened. From the QC, I can only see the "status" as "closed" but it won't give me the information about have many times it changed from "closed" to "reopen" then "fixed" then "reopen" then "closed".

Thanks in advance!

答:
The history table does not automatically track everything so make sure first that wherever possible to mark it in the customization field module to track history.
If you are using QC via Saas and have no access to Sql Server, you can always do it via the OTA (QC Api) and use sql there.
Other alternative, use the workflow and write in a file, maybe a xml one (using vbscript) on the onchanged event or rather onsaved event of the relevant QC module.</p>


问:
set back button title text in iOS Xamarin
I want to set the BackButton Title text to ""(means empty). I am using below code to set the Title but it is not working.

Try 1 :

```<code>this.NavigationItem.BackBarButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null);
</code>```

Try 2 :

```<code>this.NavigationItem.BackBarButtonItem.Title = "";
</code>```

it is give the object is not set to instance.

Is there any way to set the Back button title null in iOS.

Any Help Will be Appreciated.

答:
Back button by default use title from previous view controller. So you need to change title of previous of veiw controller to change back button title.

To hide title, you can use  SetBackButtonTitlePositionAdjustment to set offset of Title and move title to invisible area of button by passing (-80,-80) in offset.

Body:
I want to set the BackButton Title text to ""(means empty). I am using below code to set the Title but it is not working.

Try 1 :

this.NavigationItem.BackBarButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null);

Try 2 :

this.NavigationItem.BackBarButtonItem.Title = "";

it is give the object is not set to instance.

Is there any way to set the Back button title null in iOS.

Any Help Will be Appreciated.


问:
SQL type specifier
Hello guys we have problem, not knowing how to add type specifier for date type? We tried to use %% but this doesn't seem to work.</p>

```<code>    public class OrderDB implements OrderDBIF {
@Override
public Order create(Date date, int totalAmount, String deliveryStatus, Date deliveryDate, int invoiceId, int customerId) throws SQLException {
    String sql = String.format("INSERT INTO Order (date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId) VALUES "
            + "('%%', '%d', '%s', '%%', '%d', '%d')", date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId);
    try (Connection conn = DBConnection.getInstance().getDBcon();
         Statement stmt = conn.createStatement()) {
        stmt.executeUpdate(sql);
    } catch(SQLException e) {
        e.printStackTrace();
        throw e;
    }
</code>```

答:
Use a prepared statement:

```<code>String sql = "INSERT INTO Order "
    + "(date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId) VALUES "
    + "(?,?,?,?,?,?)";
try (Connection conn = DBConnection.getInstance().getDBcon();
    PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setDate(1, date);
    ps.setInt(2, totalAmount);
    ps.setString(3, deliveryStatus);
    ps.setDate(4, deliveryDate);
    ps.setInt(5, invoiceId);
    ps.setInt(6, customerId);
    ps.executeUpdate();
} catch(SQLException e) {
    e.printStackTrace();
    throw e;
}
</code>```

In addition to taking care of proper escaping for all values in the INSERT, a prepared statement also protects you against SQL injection.

Title: SQL type specifier

Body:
Hello guys we have problem, not knowing how to add type specifier for date type? We tried to use %% but this doesn't seem to work.

    public class OrderDB implements OrderDBIF {
@Override
public Order create(Date date, int totalAmount, String deliveryStatus, Date deliveryDate, int invoiceId, int customerId) throws SQLException {
    String sql = String.format("INSERT INTO Order (date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId) VALUES "
            + "('%%', '%d', '%s', '%%', '%d', '%d')", date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId);
    try (Connection conn = DBConnection.getInstance().getDBcon();
         Statement stmt = conn.createStatement()) {
        stmt.executeUpdate(sql);
    } catch(SQLException e) {
        e.printStackTrace();
        throw e;
    }

Body:
Use a prepared statement:

String sql = "INSERT INTO Order "
    + "(date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId) VALUES "
    + "(?,?,?,?,?,?)";
try (Connection conn = DBConnection.getInstance().getDBcon();
    PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setDate(1, date);
    ps.setInt(2, totalAmount);
    ps.setString(3, deliveryStatus);
    ps.setDate(4, deliveryDate);
    ps.setInt(5, invoiceId);
    ps.setInt(6, customerId);
    ps.executeUpdate();
} catch(SQLException e) {
    e.printStackTrace();
    throw e;
}

In addition to taking care of proper escaping for all values in the INSERT, a prepared statement also protects you against SQL injection.


问:
Accessing a siblings children, not the first instance of a class
I have the following code:

```<code>$(document).on( 'click', '.chevronright', function( event ) {
for (var i=0; i<2; i++){
            var $next =  $(this).siblings('.postlink').find('.post-title').eq(i+1).html();
            $('.row').find('.post-title').eq(i).html($next);
}
</code>```

I have three instances of row, and 3 instances of postlink inside each row, and there is also a chevron in each row. I want it so that when the chevron is clicked, the title from the middle one changes to the left one and the rightmost one changes to the middle one.

What happens is that when i click a chevron in row 2 or row 3, the first row is the one that the actions happen to. It gets the title of the chevron that is the next in line, in the row that I click on but it always happens to the first post-title in the page.  How would I need to refer to the children of the chevrons parent row?

答:
You can try</p>

```<code>Whatever.find('.post-title:eq('+(i+1)+')').html()
</code>```

Body:
I have the following code:

$(document).on( 'click', '.chevronright', function( event ) {
for (var i=0; i<2; i++){
            var $next =  $(this).siblings('.postlink').find('.post-title').eq(i+1).html();
            $('.row').find('.post-title').eq(i).html($next);
}

I have three instances of row, and 3 instances of postlink inside each row, and there is also a chevron in each row. I want it so that when the chevron is clicked, the title from the middle one changes to the left one and the rightmost one changes to the middle one.

What happens is that when i click a chevron in row 2 or row 3, the first row is the one that the actions happen to. It gets the title of the chevron that is the next in line, in the row that I click on but it always happens to the first post-title in the page.  How would I need to refer to the children of the chevrons parent row?

Body:
You can try

Whatever.find('.post-title:eq('+(i+1)+')').html()


问:
Can't Call Method of Custom Class Object Excel VBA
I'm in the middle of writing some code for scheduling automation. I am relatively new to VBA programming but have been programming in other languages for years. For my project I've created a class called OpsFloor which is supposed to simulate the operations floor. I'm parsing user information into an array and trying to pass that array (I've tried both passing the whole array and by individual values) into an instance of the OpsFloor object. I'm worried I have some fundamental misunderstanding about how classes work in VBA. Below is the sub from within the Class

```<code>Public Sub SetProcessMatrixValue(x As Integer, y As Integer, value As Integer)
    ProcessMatrix(x, y) = value
End Sub
</code>```

Here is the call from within the worksheet object sub in Excel:

```<code>Option Explicit
Private OperationMatrix(18, 8) As Integer
Private dailyWF As New OpsFloor
Public Sub StartingWorksheet()
...
dailyWF.SetProcessMatrixValue 0, 0, 30
End Sub
</code>```

When I try to run the sub to assign those values to the class instance through the SetProcessMatrixValue method I get Run-time Error '438' Object Doesn't Support this property or method.

答:
So I had a couple issues which I managed to uncover after piecing together a lot of different posts.

Firstly the way I originally declared my class variable:

```<code>Private dailyWF As New OpsFloor
</code>```

This didn't properly instantiate the class object. When I tried to change it to the following:

```<code>Private dailyWF As New OpsFloor
Set dailyWf = New Operations_Floor
</code>```

I got an error which pointed me to the class constructor. It ended up being an issue with how I was assigning objects to a collection.

```<code>newCollection.Add(new Object) //WRONG!
newCollection.Add new Object //Right!
</code>```

For other newbs like me I found a post that recommended turning on "Break in Class Modules" by going to Tools>Options>General>Break in Class Modules. This showed me the error was inside the class constructor and not actually an issue with the way I was making my call.

Body:
I'm in the middle of writing some code for scheduling automation. I am relatively new to VBA programming but have been programming in other languages for years. For my project I've created a class called OpsFloor which is supposed to simulate the operations floor. I'm parsing user information into an array and trying to pass that array (I've tried both passing the whole array and by individual values) into an instance of the OpsFloor object. I'm worried I have some fundamental misunderstanding about how classes work in VBA. Below is the sub from within the Class

Public Sub SetProcessMatrixValue(x As Integer, y As Integer, value As Integer)
    ProcessMatrix(x, y) = value
End Sub

Here is the call from within the worksheet object sub in Excel:

Option Explicit
Private OperationMatrix(18, 8) As Integer
Private dailyWF As New OpsFloor
Public Sub StartingWorksheet()
...
dailyWF.SetProcessMatrixValue 0, 0, 30
End Sub

When I try to run the sub to assign those values to the class instance through the SetProcessMatrixValue method I get Run-time Error '438' Object Doesn't Support this property or method.

Body:
So I had a couple issues which I managed to uncover after piecing together a lot of different posts.

Firstly the way I originally declared my class variable:

Private dailyWF As New OpsFloor

This didn't properly instantiate the class object. When I tried to change it to the following:

Private dailyWF As New OpsFloor
Set dailyWf = New Operations_Floor

I got an error which pointed me to the class constructor. It ended up being an issue with how I was assigning objects to a collection.

newCollection.Add(new Object) //WRONG!
newCollection.Add new Object //Right!

For other newbs like me I found a post that recommended turning on "Break in Class Modules" by going to Tools>Options>General>Break in Class Modules. This showed me the error was inside the class constructor and not actually an issue with the way I was making my call.


问:
Django snippets. How to use?
explain me please how to use it in my Admin?

You can just create a custom ModelForm for your model, with the following:

```<code>remove_the_file = forms.BooleanField(required=False)

def save(self, *args, **kwargs):
    object = super(self.__class__, self).save(*args, **kwargs)
    if self.cleaned_data.get('remove_the_file'):
        object.the_file = ''
    return object
</code>```

Use that form in your ModelAdmin, and there's no need to change the database.

there is what i created in forms.py:

```<code>class MediaForm(forms.ModelForm):

    remove_the_file = forms.BooleanField(required=False)

    def save(self, *args, **kwargs):
        object = super(self.__class__, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_the_file'):
            object.the_file = ''
        return object
</code>```

And there is my admin.py:

```<code>class MediaAdmin(admin.ModelAdmin):
    raw_id_fields = ('parent',)
</code>```

how should i change MediaAdmin class to apply it?

答:
```<code>class MediaAdmin(admin.ModelAdmin):
    raw_id_fields = ('parent',)
    form = MediaForm
</code>```

Title: Django snippets. How to use?

Body:
explain me please how to use it in my Admin?

You can just create a custom ModelForm for your model, with the following:

remove_the_file = forms.BooleanField(required=False)

def save(self, *args, **kwargs):
    object = super(self.__class__, self).save(*args, **kwargs)
    if self.cleaned_data.get('remove_the_file'):
        object.the_file = ''
    return object

Use that form in your ModelAdmin, and there's no need to change the database.

there is what i created in forms.py:

class MediaForm(forms.ModelForm):

    remove_the_file = forms.BooleanField(required=False)

    def save(self, *args, **kwargs):
        object = super(self.__class__, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_the_file'):
            object.the_file = ''
        return object

And there is my admin.py:

class MediaAdmin(admin.ModelAdmin):
    raw_id_fields = ('parent',)

how should i change MediaAdmin class to apply it?


问:
where to add the line break

make a 0

```<code>def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = ("*   *")
    result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom
    return result

result = number0(5, 5, "*")
print (result)
</code>```

here's what happens when I run the program:

```<code>*****
*   **   **   **   **   *
*****
</code>```

I want to add line break in between middle and height to make it look like a 0 shape with a height of 5.

答:
You just have to change:

middle = ("*   *")

middle = ("*   *\n")

and

result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom

result = toporbottom + "\n" + (middle) * height + toporbottom.

Code:

```<code>def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = ("*   *\n")
    result = toporbottom + "\n" + (middle) * height + toporbottom
    return result

result = number0(5, 5, "*")
print (result)
</code>```

Output:

```<code>*****
*   *
*   *
*   *
*   *
*   *
*****
</code>```

p.s.: now you should change the hard coded symbol "*" in middle and toporbottom to the function parameter symbol.

Title: where to add the line break

Body:
You just have to change:

middle = ("*   *")

middle = ("*   *\n")

and

result = toporbottom + "\n" + (middle) * height + "\n" + toporbottom

result = toporbottom + "\n" + (middle) * height + toporbottom.

Code:

def number0(width, height, symbol):
    toporbottom  = ("*"*5)
    middle = ("*   *\n")
    result = toporbottom + "\n" + (middle) * height + toporbottom
    return result

result = number0(5, 5, "*")
print (result)

Output:

*****
*   *
*   *
*   *
*   *
*   *
*****

p.s.: now you should change the hard coded symbol "*" in middle and toporbottom to the function parameter symbol.


问:
Count how many numbers appears in a string
I was wondering if there's a combo of functions or a direct function that can count how many numbers appears in a string, without use a long-way as str_split and check every character in a loop.

From a string like:

```<code>fdsji2092mds1039m
</code>```

It returns that there's 8 numbers inside.

答:
You can use filter_var() with the FILTER_SANITIZE_NUMBER_INT constant, then check the length of the new string. The new string will contain only numbers from that string, and all other characters are filtered away.

```<code>$string = "j3987snmj3j";
$numbers = filter_var($string , FILTER_SANITIZE_NUMBER_INT);
$length = strlen($numbers); // 5
echo "There are ".$length." numbers in that string";
</code>```

Note that each number will be counted individually, so 137 would return 3, as would 1m3j7.

Live demo

Body:
I was wondering if there's a combo of functions or a direct function that can count how many numbers appears in a string, without use a long-way as str_split and check every character in a loop.

From a string like:

fdsji2092mds1039m

It returns that there's 8 numbers inside.

Body:
You can use filter_var() with the FILTER_SANITIZE_NUMBER_INT constant, then check the length of the new string. The new string will contain only numbers from that string, and all other characters are filtered away.

$string = "j3987snmj3j";
$numbers = filter_var($string , FILTER_SANITIZE_NUMBER_INT);
$length = strlen($numbers); // 5
echo "There are ".$length." numbers in that string";

Note that each number will be counted individually, so 137 would return 3, as would 1m3j7.

Live demo


问:
How would I use the `...` C operator to get a function to print out all it's args?
Here's what I tried... but failed:</p>

```<code>void testfunc(...){
    printf(...);
}
</code>```

答:
You must use va_start(), va_end(), va_arg() and (not always) va_list and you must have at least one constant defined argument! For example:

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

void PrintFloats ( int amount, ...)
{
  int i;
  double val;
  printf ("Floats passed: ");
  va_list vl;
  va_start(vl,amount);
  for (i=0;i<amount;i++)
  {
    val=va_arg(vl,double);
    printf ("\t%.2f",val);
  }
  va_end(vl);
  printf ("\n");
}

int main ()
{
  PrintFloats (3,3.14159,2.71828,1.41421);
  return 0;
}
</code>```

Body:
Here's what I tried... but failed:

void testfunc(...){
    printf(...);
}

Body:
You must use va_start(), va_end(), va_arg() and (not always) va_list and you must have at least one constant defined argument! For example:

#include <stdio.h>
#include <stdarg.h>

void PrintFloats ( int amount, ...)
{
  int i;
  double val;
  printf ("Floats passed: ");
  va_list vl;
  va_start(vl,amount);
  for (i=0;i<amount;i++)
  {
    val=va_arg(vl,double);
    printf ("\t%.2f",val);
  }
  va_end(vl);
  printf ("\n");
}

int main ()
{
  PrintFloats (3,3.14159,2.71828,1.41421);
  return 0;
}


问:
Disable add to cart if in quantity box is 0
I'm looking for solution for my problem. I have category list with add to cart button and quantity box. I need to disable add to cart when is in quantity box 0 and allow it when is 1 and more.
I need default value 0.
Now, when I click to add to cart button is added one product to the cart.

This problem is just in category list, not on product page.

My code from /app/design/frontend/theme/theme/template/catalog/product/list.phtml

```<code><?php  if ( !($product->getTypeInstance(true)->hasOptions($product)/*$_product->getData('has_options')*/ || $product->isGrouped()) ) :  ?>

                                <div class="qty-holder">
                                    <input type="text" name="qty" id="qty_<?php echo $_product->getId(); ?>" maxlength="12" value="<?php echo $product->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
                                    <div class="qty-changer">
                                        <a href="javascript:void(0)" class="qty_inc" style="height:34px; line-height:34px;"><i class="icon-up-dir"></i></a>
                                        <a href="javascript:void(0)" class="qty_dec" style="height:34px; line-height:34px;"><i class="icon-down-dir"></i></a>
                                    </div>
                                </div>
                            </form>
                            <?php $_productid == $_product->getId(); ?>

                            <a href="<?php if(!Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code) && !Mage::getStoreConfig("porto_settings/category/qty_field", $code)): ?><?php echo $this->getAddToCartUrl($_product) ?><?php else: ?>javascript:void(0)<?php endif; ?>" class="addtocart" title="<?php echo $this->__('Add to Cart') ?>" <?php if(Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code)):?>onclick="setLocationAjax(this,'<?php echo $this->getAddToCartUrl($_product) ?>','<?php echo $_product->getId(); ?>')"<?php elseif(Mage::getStoreConfig("porto_settings/category/qty_field", $code)): ?>onclick="document.getElementById('addtocart_form_<?php echo $_product->getId(); ?>').submit()"<?php endif; ?>><i class="icon-cart"></i><span> <?php echo $this->__('Add to Cart') ?></span></a>

                        <?php else : ?>
                            <a href="<?php if(Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code)):?>javascript:showOptions('<?php echo $_product->getId()?>')<?php else: ?><?php echo $this->getAddToCartUrl($_product) ?><?php endif; ?>" class="addtocart" title="<?php echo $this->__('Add to Cart') ?>"><i class="icon-cart"></i><span> <?php echo $this->__('Add to Cart') ?></span></a>
                            <a href='<?php echo $this->getUrl('ajaxcart/index/options',array('product_id'=>$_product->getId()));?>' class='fancybox' id='fancybox<?php echo $_product->getId()?>' style='display:none'>Options</a>
                        <?php endif;?>
</code>```

Any ideas?

Thanks!

答:
Put this condition to disable addtocart and add disabled="disbled" in anchor tag of add to cart</p>

```<code>if($product->getProductDefaultQty() * 1 == 0){
   <a disabled = "disabled"></a>
}
else{
  // your normal code here for add to cart
}
</code>```

Body:
I'm looking for solution for my problem. I have category list with add to cart button and quantity box. I need to disable add to cart when is in quantity box 0 and allow it when is 1 and more.
I need default value 0.
Now, when I click to add to cart button is added one product to the cart.

This problem is just in category list, not on product page.

My code from /app/design/frontend/theme/theme/template/catalog/product/list.phtml

<?php  if ( !($product->getTypeInstance(true)->hasOptions($product)/*$_product->getData('has_options')*/ || $product->isGrouped()) ) :  ?>

                                    <input type="text" name="qty" id="qty_<?php echo $_product->getId(); ?>" maxlength="12" value="<?php echo $product->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />

                            </form>
                            <?php $_productid == $_product->getId(); ?>

                            <a href="<?php if(!Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code) && !Mage::getStoreConfig("porto_settings/category/qty_field", $code)): ?><?php echo $this->getAddToCartUrl($_product) ?><?php else: ?>javascript:void(0)<?php endif; ?>" class="addtocart" title="<?php echo $this->__('Add to Cart') ?>" <?php if(Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code)):?>onclick="setLocationAjax(this,'<?php echo $this->getAddToCartUrl($_product) ?>','<?php echo $_product->getId(); ?>')"<?php elseif(Mage::getStoreConfig("porto_settings/category/qty_field", $code)): ?>onclick="document.getElementById('addtocart_form_<?php echo $_product->getId(); ?>').submit()"<?php endif; ?>> <?php echo $this->__('Add to Cart') ?>

                        <?php else : ?>
                            <a href="<?php if(Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code)):?>javascript:showOptions('<?php echo $_product->getId()?>')<?php else: ?><?php echo $this->getAddToCartUrl($_product) ?><?php endif; ?>" class="addtocart" title="<?php echo $this->__('Add to Cart') ?>"> <?php echo $this->__('Add to Cart') ?>
                            <a href='<?php echo $this->getUrl('ajaxcart/index/options',array('product_id'=>$_product->getId()));?>' class='fancybox' id='fancybox<?php echo $_product->getId()?>' style='display:none'>Options
                        <?php endif;?>

Any ideas?

Thanks!

Body:
Put this condition to disable addtocart and add disabled="disbled" in anchor tag of add to cart

if($product->getProductDefaultQty() * 1 == 0){
   <a disabled = "disabled"></a>
}
else{
  // your normal code here for add to cart
}