问:
THREAD 1: EXC_BREAKPOINT CALayer removeAllAnimations message sent to deallocated
There are a lot of question with the same title but somehow I felt that every case is different as my problem is still not resolved and I've no clue why and also there are not enough solutions for Swift. So here is my scenerio:

I've used CarbonKit to show 4 view controllers in a single view controller. The FourthViewController sends a get call using AlamoFire. It successfully loads the data and reload tableView. However when I drag this table view my app crashes and I get EXC_BREAKPOINT and sometimes EXC_BAD_ACCESS for the same thing.

Here is what I've tried:

Upon searching I came to know about zombies. So I enabled it and when the app gives me EXC I get this:

-[CALayer removeAllAnimations]: message sent to deallocated instance

So as I checked there was no animation I might have been using in this class. But considering it's inside CarbonKit they might have something to do with it but I'm unable to figure it out.

I run Product > Analyze from xCode and the most of the blue icons are on FBSDK which have nothing to do with this class so it was not useful to debug at all.

Here are the screenshots:
 and
and here is what Instruments 9.0 zombies message gave me:
 and

I get this in console of xCode:

If you need more information I'll update my questions.

UPDATE

Here is my code when I'm getting the data from web using Alamofire. Now this call runs successfully and I can scroll down to view all the data that is loaded in the table. But when i scroll up then it crashes with the above errors.

```<code>let headers = [
            "security-token": "MY_SECURITY_CODE_HERE",
            "Content-Type": "application/x-www-form-urlencoded"
        ]

        let url = "URL_GOES_HERE"
        //print(url)
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if let result = response.result.value as? [String: AnyObject] {

                switch response.result {
                case .success:
                    if result["status"] as! Int == 0
                    {
                        self.clearAllNotice()
                        let alert = UIAlertController(title: "Error",
                                                      message: "\(result["msg"] ?? "Our Server is not responding at the moment. Try again later!" as AnyObject)",
                            preferredStyle: UIAlertControllerStyle.alert)

                        let cancelAction = UIAlertAction(title: "OK",
                                                         style: .cancel, handler: nil)

                        alert.addAction(cancelAction)
                        self.present(alert, animated: true)
                    }
                    else
                    {
                        self.clearAllNotice()

                        for docReviewDict in (result["data"] as! [AnyObject]) {

                            let docReview = DoctorReview(dict: docReviewDict as! [String : AnyObject])
                            self.mainDoctorReviewsArray.append(docReview)
                        }

                        self.tableView.reloadData()
                    }
                case .failure(let error):
                    self.clearAllNotice()
                    let alert = UIAlertController(title: "Something is wrong",
                                                  message: error.localizedDescription,
                                                  preferredStyle: UIAlertControllerStyle.alert)

                    let cancelAction = UIAlertAction(title: "OK",
                                                     style: .cancel, handler: nil)

                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                }
            } else {
              print("Somethins is wrong with the URL")
            }
        }
</code>```

Just in case here is the cell which is loaded in the tableview.

Latest:

Based on the comment I've done this:

```<code>DispatchQueue.main.async {
                        self.tableView.reloadData()
                        }
</code>```

but still the same result I'am getting

Thread 1: EXC_BAD_ACCESS (code=1, address=0xb4c4beb8)

on let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell line when I drag down on table view.

IMPLEMENTATION OF CELL

The class name is ReviewsViewController which has a @IBOutlet fileprivate var tableView: UITableView!.

Then in viewDidLoad():

```<code>tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
</code>```

Then I've table view delegate and datasource:

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainDoctorReviewsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell //WHEN THE APP IS CRASHED AS I DRAG THE TABLE VIEW IT CRASH ON THIS LINE. As this line is highlighted in red with message "Thread 1: EXC_BREAKPOINT (code=1, subcode=0x186ddd61c)"

        cell.userPhoto.layer.cornerRadius = cell.userPhoto.frame.width / 2;
        cell.userPhoto.layer.masksToBounds = true

        cell.userName.text = mainDoctorReviewsArray[indexPath.row].name

        cell.starRating.settings.fillMode = .precise

        if let rate = mainDoctorReviewsArray[indexPath.row].rating
        {
            cell.starRating.rating = Double(rate)!
        }
        else {
            cell.starRating.rating = 0
        }

        cell.desc.text = mainDoctorReviewsArray[indexPath.row].feedback
        cell.dateOfReview.text = mainDoctorReviewsArray[indexPath.row].dates
        cell.timeOfReview.text = mainDoctorReviewsArray[indexPath.row].times

        return cell
    }
</code>```

and in the cell class there is just:

```<code>import UIKit
import Cosmos

class ReviewsTableViewCell: UITableViewCell {

    @IBOutlet var timeOfReview: UILabel!
    @IBOutlet var dateOfReview: UILabel!
    @IBOutlet var desc: UITextView!
    @IBOutlet var starRating: CosmosView!
    @IBOutlet var userName: UILabel!
    @IBOutlet var userPhoto: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
</code>```

The screenshot of tableView is above in this question.

This is the parent class under which 4 ViewControllers loads: dropbox.com/s/d5sh4ej1ssv6873/… And this is the class which has the tableview is and on scroll it crashed the app: dropbox.com/s/3kiju9hn3uewzar/ReviewsViewController.swift?dl=0

答:
As someone mentioned above it probably is related with working with ui objects not from main thread.
If your using xCode 9 you should see as a runtime warning. (You can set checkmark in EditScheme->Diagnostics->MainThreadChecker->pause on issues).

Also you can override dealloc method of you ReviewsTableViewCell and add some logs\asserts to check if it's called from main thread.

Usually it happens if you pass your view\cell to some block, and you will have this crash on releasing this object when exiting from block.

Body:
There are a lot of question with the same title but somehow I felt that every case is different as my problem is still not resolved and I've no clue why and also there are not enough solutions for Swift. So here is my scenerio:

I've used CarbonKit to show 4 view controllers in a single view controller. The FourthViewController sends a get call using AlamoFire. It successfully loads the data and reload tableView. However when I drag this table view my app crashes and I get EXC_BREAKPOINT and sometimes EXC_BAD_ACCESS for the same thing.

Here is what I've tried:

Upon searching I came to know about zombies. So I enabled it and when the app gives me EXC I get this:

-[CALayer removeAllAnimations]: message sent to deallocated instance

So as I checked there was no animation I might have been using in this class. But considering it's inside CarbonKit they might have something to do with it but I'm unable to figure it out.

I run Product > Analyze from xCode and the most of the blue icons are on FBSDK which have nothing to do with this class so it was not useful to debug at all.

Here are the screenshots:
 and
and here is what Instruments 9.0 zombies message gave me:
 and

I get this in console of xCode:

If you need more information I'll update my questions.

UPDATE

Here is my code when I'm getting the data from web using Alamofire. Now this call runs successfully and I can scroll down to view all the data that is loaded in the table. But when i scroll up then it crashes with the above errors.

let headers = [
            "security-token": "MY_SECURITY_CODE_HERE",
            "Content-Type": "application/x-www-form-urlencoded"
        ]

        let url = "URL_GOES_HERE"
        //print(url)
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if let result = response.result.value as? [String: AnyObject] {

                switch response.result {
                case .success:
                    if result["status"] as! Int == 0
                    {
                        self.clearAllNotice()
                        let alert = UIAlertController(title: "Error",
                                                      message: "\(result["msg"] ?? "Our Server is not responding at the moment. Try again later!" as AnyObject)",
                            preferredStyle: UIAlertControllerStyle.alert)

                        let cancelAction = UIAlertAction(title: "OK",
                                                         style: .cancel, handler: nil)

                        alert.addAction(cancelAction)
                        self.present(alert, animated: true)
                    }
                    else
                    {
                        self.clearAllNotice()

                        for docReviewDict in (result["data"] as! [AnyObject]) {

                            let docReview = DoctorReview(dict: docReviewDict as! [String : AnyObject])
                            self.mainDoctorReviewsArray.append(docReview)
                        }

                        self.tableView.reloadData()
                    }
                case .failure(let error):
                    self.clearAllNotice()
                    let alert = UIAlertController(title: "Something is wrong",
                                                  message: error.localizedDescription,
                                                  preferredStyle: UIAlertControllerStyle.alert)

                    let cancelAction = UIAlertAction(title: "OK",
                                                     style: .cancel, handler: nil)

                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                }
            } else {
              print("Somethins is wrong with the URL")
            }
        }

Just in case here is the cell which is loaded in the tableview.

Latest:

Based on the comment I've done this:

DispatchQueue.main.async {
                        self.tableView.reloadData()
                        }

but still the same result I'am getting

Thread 1: EXC_BAD_ACCESS (code=1, address=0xb4c4beb8)

on let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell line when I drag down on table view.

IMPLEMENTATION OF CELL

The class name is ReviewsViewController which has a @IBOutlet fileprivate var tableView: UITableView!.

Then in viewDidLoad():

tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()

Then I've table view delegate and datasource:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainDoctorReviewsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell //WHEN THE APP IS CRASHED AS I DRAG THE TABLE VIEW IT CRASH ON THIS LINE. As this line is highlighted in red with message "Thread 1: EXC_BREAKPOINT (code=1, subcode=0x186ddd61c)"

        cell.userPhoto.layer.cornerRadius = cell.userPhoto.frame.width / 2;
        cell.userPhoto.layer.masksToBounds = true

        cell.userName.text = mainDoctorReviewsArray[indexPath.row].name

        cell.starRating.settings.fillMode = .precise

        if let rate = mainDoctorReviewsArray[indexPath.row].rating
        {
            cell.starRating.rating = Double(rate)!
        }
        else {
            cell.starRating.rating = 0
        }

        cell.desc.text = mainDoctorReviewsArray[indexPath.row].feedback
        cell.dateOfReview.text = mainDoctorReviewsArray[indexPath.row].dates
        cell.timeOfReview.text = mainDoctorReviewsArray[indexPath.row].times

        return cell
    }

and in the cell class there is just:

import UIKit
import Cosmos

class ReviewsTableViewCell: UITableViewCell {

    @IBOutlet var timeOfReview: UILabel!
    @IBOutlet var dateOfReview: UILabel!
    @IBOutlet var desc: UITextView!
    @IBOutlet var starRating: CosmosView!
    @IBOutlet var userName: UILabel!
    @IBOutlet var userPhoto: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

The screenshot of tableView is above in this question.

This is the parent class under which 4 ViewControllers loads: dropbox.com/s/d5sh4ej1ssv6873/… And this is the class which has the tableview is and on scroll it crashed the app: dropbox.com/s/3kiju9hn3uewzar/ReviewsViewController.swift?dl=0


来源: stackexchange

问:
sh: gnuplot: command not found in Gnuplot + Xcode
There was a similar question to mine however the answers were not quite solutions so if I could get some help with this it would be greatly appreciated.

The problem is that when I compile, Xcode gives the aforementioned error of sh: gnuplot: command not found.

I checked which gnuplot in terminal and as expected from macports it is in /opt/local/bin/gnuplot. Also printf("PATH=%s\n", getenv("PATH")); shows the path PATH=/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin I suspect therein lies the problem but I am not sure how to fix it.

Thanks in advance!

答:
The key issue to prevent Xcode from running is indeed related to PATH of gnuplot. Depending on which package management system you use in mac, the directory of gnuplot can vary.

Typing which gnuplot in terminal will show the exact location of gnuplot.

In the case of macport, gnuplot is located in /opt/local/bin, which is not included in the default path setting of Xcode.

To check your PATH, typing

```<code>std::cout << "PATH=" << getenv("PATH") << std::endl; // #include<iostream>
</code>```

or

```<code>printf( "PATH=%s\n", getenv("PATH") ); // #include<cstdio>
</code>```

can show you a likewise path as

/usr/bin:/bin:/usr/sbin:/sbin:/usr/bin

Here is my solution.

The easiest way is to use a soft link to combine the real directory (/opt/local/bin) of gnuplot with the acceptable direction, such as ( /usr/bin ) that shows from getenv("PATH") in Xcode, like
ln -s /opt/local/bin/gnuplot /usr/bin/gnuplot

If your .bash_profile setting resists the previous method, then the safer and more stable method is to adding an external path in Xcode project directly,
which is original from here. In brief, add PATH in Product>Scheme>Edit Scheme... as shown below before closing this window.

Try this code to generate your first ever gnuplot in Xcode

```<code>#include <iostream>

#include "gnuplot-iostream.h"

int main( ) {
    Gnuplot gp;
    gp << "plot [-10:10] sin(x),atan(x),cos(atan(x))\n";
    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The key issue to prevent Xcode from running is indeed related to PATH of gnuplot. Depending on which package management system you use in mac, the directory of gnuplot can vary.

Typing which gnuplot in terminal will show the exact location of gnuplot.

In the case of macport, gnuplot is located in /opt/local/bin, which is not included in the default path setting of Xcode.

To check your PATH, typing

std::cout << "PATH=" << getenv("PATH") << std::endl; // #include<iostream>

or

printf( "PATH=%s\n", getenv("PATH") ); // #include<cstdio>

can show you a likewise path as

/usr/bin:/bin:/usr/sbin:/sbin:/usr/bin

Here is my solution.

The easiest way is to use a soft link to combine the real directory (/opt/local/bin) of gnuplot with the acceptable direction, such as ( /usr/bin ) that shows from getenv("PATH") in Xcode, like
ln -s /opt/local/bin/gnuplot /usr/bin/gnuplot

If your .bash_profile setting resists the previous method, then the safer and more stable method is to adding an external path in Xcode project directly,
which is original from here. In brief, add PATH in Product>Scheme>Edit Scheme... as shown below before closing this window.

Try this code to generate your first ever gnuplot in Xcode

#include <iostream>

#include "gnuplot-iostream.h"

int main( ) {
    Gnuplot gp;
    gp << "plot [-10:10] sin(x),atan(x),cos(atan(x))\n";
    return 0;
}


问:
Angular's link function vs Angular 2's constructor
Being new to Angular2, and its component architecture, I could understand that, Components are enhanced version of Angular's directives.

And when I look at the constructor which pertains to a particular I component that I tend to write, It more or less does the same work which the link function use to perform in Angular 1.x since the link function gets executed for each instance of directive so that each instance gets it’s own business-logic without affecting others.

Is my understanding correct?

答:
The contructor is called for each instance.

So constructorcan be used, but it is better to use ngOnInit because it hooks into the Angular lifecycle


问:
How to publish Json using rabbitmqadmin command
I want to publish Json message using rabbitmqadmin command line. How can we do that as i was reading we can send only string message in payload like below
rabbitmqadmin publish exchange=default routing_key=test payload="hello, world".

But I wanted to send something like this:
rabbitmqadmin publish exchange=default routing_key=test payload=file.json

How can we do this in command line?

答:
this may depend on the library you're using at the other end, but to get the msg processed correctly (it was a string otherwise), I needed more:

```<code>./rabbitmqadmin publish exchange=foo routing_key=foo.bar.baz \
    properties='{"content_type":"application/json"}' \
    payload='{}' payload_encoding='string'
</code>```

Note content_type with an underscore.

Body:
this may depend on the library you're using at the other end, but to get the msg processed correctly (it was a string otherwise), I needed more:

./rabbitmqadmin publish exchange=foo routing_key=foo.bar.baz \
    properties='{"content_type":"application/json"}' \
    payload='{}' payload_encoding='string'

Note content_type with an underscore.

ContentLicense: CC BY-SA 4.0


问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
When I run

```<code>null >= null
</code>```

I get a warning saying:

Comparing with null of type 'int?'
  always produces 'false'

I wonder why it is casted to an int though.

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

Body:
When I run

null >= null

I get a warning saying:

Comparing with null of type 'int?'
  always produces 'false'

I wonder why it is casted to an int though.

ContentLicense: CC BY-SA 2.5


问:
SSIS reading from Record set instead of Database
I'm doing some data migration of a large amount of data in which I need to perform some data matching in order to identify the operation that needs to be done on the record. For that What I'm currently doing is to read the data from the source and then match the records using a SQL Command - so that I need to hit the Database twice for each record. So Will it improve the performance if I read the data to a recordset and then match the values inside that ?

I'm reading from SQL Server 2008 R2

答:
1) using Look up transformation is one efficient way of merging records

ex:

2) Use merge procedures

ex:

```<code>MERGE [dbo].[Value] AS TARGET
         USING [dbo].[view_Value] AS SOURCE
        ON (
            TARGET.[Col1] = SOURCE.[col1]

            )

     WHEN MATCHED
     THEN
     UPDATE SET
     TARGET.[col3] = SOURCE.[col3]
     TARGET.[col2] = SOURCE.[col2]

    WHEN NOT MATCHED BY TARGET THEN
    INSERT ([col1], [col2], [col3]  )
    VALUES (SOURCE.[col1], SOURCE.[col2], SOURCE.[col3]  )
</code>```

Body:
1) using Look up transformation is one efficient way of merging records

ex:

2) Use merge procedures

ex:

MERGE [dbo].[Value] AS TARGET
         USING [dbo].[view_Value] AS SOURCE
        ON (
            TARGET.[Col1] = SOURCE.[col1]

            )

     WHEN MATCHED
     THEN
     UPDATE SET
     TARGET.[col3] = SOURCE.[col3]
     TARGET.[col2] = SOURCE.[col2]

    WHEN NOT MATCHED BY TARGET THEN
    INSERT ([col1], [col2], [col3]  )
    VALUES (SOURCE.[col1], SOURCE.[col2], SOURCE.[col3]  )


问:
filter two dropdown list with jQuery
I have two lists who looks like this.

```<code><select class="form-control" id="arrondissement" required="required" aria-invalid="false" name="arrondissement">
  <option value="1">1er arrondissement</option>
  <option value="2"><span>2ème arrondissement</span></option>
  <option value="3"><span>3ème arrondissement</span></option>
  <option value="4"><span>4ème arrondissement</span></option>
  <option value="5"><span>5ème arrondissement</span></option>
</select>

<select class="form-control classeNomIgh" id="nomIGH" required="required" aria-invalid="false" name="nomIGH">
  <!-- remplacer les valeurs "précodées" ('eiffel', 'montparnasse', 'tgi') par la liste des valeurs renvoyées par l'appel au WebService -->
  <option value="" label="---">---</option>
  <option data-arrondissement="1" value="IGH1">IGH1</option>
  <option data-arrondissement="2" value="IGH2">IGH2</option>
  <option data-arrondissement="3" value="IGH3">IGH3</option>
  <option data-arrondissement="4" value="IGH4">IGH4</option>
  <option data-arrondissement="5" value="IGH5">IGH5</option>
</select>
</code>```

How can i do so that when i select an 'arrondissement' in the first drowdown list, the second will display only those with data-arrondissement with the same value.

答:
I think This Will help You

$(function(){
    $('#groups').on('change', function(){
        var val = $(this).val();
        var sub = $('#sub_groups');
        $('option', sub).filter(function(){
            if (
                 $(this).attr('data-group') === val
              || $(this).attr('data-group') === 'SHOW'
            ) {
              if ($(this).parent('span').length) {
                $(this).unwrap();
              }
            } else {
              if (!$(this).parent('span').length) {
                $(this).wrap( "" ).parent().hide();
              }
            }
        });
    });
    $('#groups').trigger('change');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="groups">
    <option value='1'>1er arrondissement</option>
    <option value='2'>2ème arrondissement</option>
    <option value='3'>3ème arrondissement</option>
    <option value='4'>4ème arrondissement</option>
    <option value='5'>5ème arrondissement</option>
<select>

<select id="sub_groups">
    <option data-group='SHOW' value='0'>-- Select --</option>
    <option data-group='1' value='IGH1'>IGH1</option>
    <option data-group='2' value='IGH2'>IGH2</option>
    <option data-group='3' value='IGH3'>IGH3</option>
    <option data-group='4' value='IGH4'>IGH4</option>
    <option data-group='5' value='IGH5'>IGH5</option>
    <select></code>```

Title: filter two dropdown list with jQuery

Body:
I have two lists who looks like this.

<select class="form-control" id="arrondissement" required="required" aria-invalid="false" name="arrondissement">
  <option value="1">1er arrondissement</option>
  <option value="2">2ème arrondissement</option>
  <option value="3">3ème arrondissement</option>
  <option value="4">4ème arrondissement</option>
  <option value="5">5ème arrondissement</option>
</select>

<select class="form-control classeNomIgh" id="nomIGH" required="required" aria-invalid="false" name="nomIGH">

  <option value="" label="---">---</option>
  <option data-arrondissement="1" value="IGH1">IGH1</option>
  <option data-arrondissement="2" value="IGH2">IGH2</option>
  <option data-arrondissement="3" value="IGH3">IGH3</option>
  <option data-arrondissement="4" value="IGH4">IGH4</option>
  <option data-arrondissement="5" value="IGH5">IGH5</option>
</select>

How can i do so that when i select an 'arrondissement' in the first drowdown list, the second will display only those with data-arrondissement with the same value.

Body:
I think This Will help You

$(function(){
    $('#groups').on('change', function(){
        var val = $(this).val();
        var sub = $('#sub_groups');
        $('option', sub).filter(function(){
            if (
                 $(this).attr('data-group') === val
              || $(this).attr('data-group') === 'SHOW'
            ) {
              if ($(this).parent('span').length) {
                $(this).unwrap();
              }
            } else {
              if (!$(this).parent('span').length) {
                $(this).wrap( "<span>" ).parent().hide();
              }
            }
        });
    });
    $('#groups').trigger('change');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="groups">
    <option value='1'>1er arrondissement</option>
    <option value='2'>2ème arrondissement</option>
    <option value='3'>3ème arrondissement</option>
    <option value='4'>4ème arrondissement</option>
    <option value='5'>5ème arrondissement</option>
<select>

<select id="sub_groups">
    <option data-group='SHOW' value='0'>-- Select --</option>
    <option data-group='1' value='IGH1'>IGH1</option>
    <option data-group='2' value='IGH2'>IGH2</option>
    <option data-group='3' value='IGH3'>IGH3</option>
    <option data-group='4' value='IGH4'>IGH4</option>
    <option data-group='5' value='IGH5'>IGH5</option>
    <select>


问:
Local Notification in WatchOS 3
I'm using the WatchOS 3 beta and trying to initiate a local notification on the watch.  The interface is just one button which calls the "buttonPushed" method in the code below.  The app runs fine but I never get a notification.  The app structure is the default from Xcode 8 for a WatchKit app.

This code is in the InterfaceController.swift file of the WatchKit extension

Am I missing something totally obvious?

```<code>@IBAction func buttonPushed() {
        sendMyNotification()
    }

    func sendMyNotification(){
        if #available(watchOSApplicationExtension 3.0, *) {

            let center = UNUserNotificationCenter.current()

            center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
                // Enable or disable features based on authorization.
            }

            let content = UNMutableNotificationContent()
            content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
            content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
            content.sound = UNNotificationSound.default()
            content.categoryIdentifier = "REMINDER_CATEGORY"
            // Deliver the notification in five seconds.
            let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
            let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)

            // Schedule the notification.

            center.add(request ,withCompletionHandler: nil)

        } else {
            // Fallback on earlier versions
        }

    }
</code>```

答:
Swift 4 simple code </p>

```<code>    let content = UNMutableNotificationContent()
    content.title = "How many days are there in one year"
    content.subtitle = "Do you know?"
    content.body = "Do you really know?"
    content.badge = 1

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
</code>```

Title: Local Notification in WatchOS 3

Body:
I'm using the WatchOS 3 beta and trying to initiate a local notification on the watch.  The interface is just one button which calls the "buttonPushed" method in the code below.  The app runs fine but I never get a notification.  The app structure is the default from Xcode 8 for a WatchKit app.

This code is in the InterfaceController.swift file of the WatchKit extension

Am I missing something totally obvious?

@IBAction func buttonPushed() {
        sendMyNotification()
    }

    func sendMyNotification(){
        if #available(watchOSApplicationExtension 3.0, *) {

            let center = UNUserNotificationCenter.current()

            center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
                // Enable or disable features based on authorization.
            }

            let content = UNMutableNotificationContent()
            content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
            content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
            content.sound = UNNotificationSound.default()
            content.categoryIdentifier = "REMINDER_CATEGORY"
            // Deliver the notification in five seconds.
            let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
            let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)

            // Schedule the notification.

            center.add(request ,withCompletionHandler: nil)

        } else {
            // Fallback on earlier versions
        }

    }

Body:
Swift 4 simple code

    let content = UNMutableNotificationContent()
    content.title = "How many days are there in one year"
    content.subtitle = "Do you know?"
    content.body = "Do you really know?"
    content.badge = 1

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)


问:
JMeter - submit JMeter function inside a script (JSR223 element)
Functions are very useful for writing a functional script and also helpful without writing real code.

Currently I can execute functions in most of Test Plan except in Script of JSR223 Sampler for example.

Is there a way to enable JMeter function inside JSR223/Beanshell script?
For example ${__log(Message)} or ${__Random(0,10)}

If the call for variable as ${..} is an issue, is there a workaround for calling a function?

Maybe there will be a problem calling groovy function inside groovy script, But can other functions be executed?

答:
You should not be inlining JMeter functions and/or Variables into scripts as :

They might resolve into something causing compilation failure or unexpected behavior

In case of Groovy they will conflict with GStringTemplate, moreover compiled scripts caching will not be possible

So you have 2 options:

Use "Parameters" section of the JSR223 Test Elements like:

Go for code-based equivalents, i.e. using RandomUtils class:

More information: Apache Groovy - Why and How You Should Use It


问:
Manipulating Javascript with Java
I have a complex, generated Javascript file (it's generated by the GWT compiler), and I need to be able to programmatically make changes to this and output a 'cleaned' version of the file. In particular, I have:

```<code>function bookmark(){
    // lots-o-javascript
    var M=Vb+s+I+Wb;n.write(Xb+Yb+Zb+$b+_b+ac+bc+$b+_b+cc+dc+ec+M+fc+gc+hc+ic)
}
bookmark();
</code>```

Un-obfuscated, the inside of the function looks like:

```<code>var compiledScriptTag = '"<script src=\\"' + base + strongName + '.cache.js\\"><\/scr" + "ipt>"';
$doc_0.write('<scr' + 'ipt><!-' + '-\n' + 'blah blah blah' + 'document.write(' + compiledScriptTag + ');' + '\n-' + '-><\/scr' + 'ipt>');
</code>```

So what I need to do is in a Java servlet, transform the above two lines into the equivalent of:

```<code>eval('blah blah blah');
document.body.appendChild(document.createElement('script')).src=base + strongName + ".cache.js";
</code>```

What are my best options to parse and re-arrange this Javascript file? Should I look into Rhino, would it be able to give handles to these (as well as the nested Javascript which is being written using $doc.write)? Any ideas would be appreciated.

答: Perhaps the more elegant and less brute force option would be to modify the iframe linker to change what you need to, or I think you can create a secondary linker and change the lines before the loader gets obfuscated. Linkers are the one thing I have yet to play around with, but I know they are probably the best place for doing what you want to do.</p>

Title: Manipulating Javascript with Java

Body:
I have a complex, generated Javascript file (it's generated by the GWT compiler), and I need to be able to programmatically make changes to this and output a 'cleaned' version of the file. In particular, I have:

function bookmark(){
    // lots-o-javascript
    var M=Vb+s+I+Wb;n.write(Xb+Yb+Zb+$b+_b+ac+bc+$b+_b+cc+dc+ec+M+fc+gc+hc+ic)
}
bookmark();

Un-obfuscated, the inside of the function looks like:

var compiledScriptTag = '"


问:
Blurring a SKShapeNode incrementally using SKEffectNode
I'm trying to blur a SKShapenode in my program. However, I want the shapenode to blur progressively, with a duration of about 1 second. How do I achieve that? The current code blurs it instantly.</p>

```<code>func generateAnimation() {

var blurAction : SKAction = SKAction.runBlock{
   //the method below returns a shapeNode
    var circle = self.generateImage()
    var effect : SKEffectNode = SKEffectNode()
    var filter : CIFilter = CIFilter(name:"CIGaussianBlur")
    filter.setValue(10, forKey: "inputRadius")
    effect.filter = filter
    effect.addChild(circle)
    self.addChild(effect)
}
</code>```

答:
Here you go mate, Swift4 SpriteKit:</p>

```<code>let ITEM_MAX_BLUR_AMOUNT: CGFloat = 20
let ITEM_MIN_BLUR_AMOUNT: CGFloat = 0
let ITEM_FOCUS_DURATION: TimeInterval = 0.2

let effectNode: SKEffectNode = SKEffectNode()

effectNode.filter = CIFilter = CIFilter(name: "CIGaussianBlur")
effectNode.shouldEnableEffects = true
addChild(effectNode)

let focusAction = SKAction.customAction(withDuration: ITEM_FOCUS_DURATION, actionBlock: { (node : SKNode!, elapsedTime : CGFloat) -> Void in

    let fraction = CGFloat(elapsedTime / CGFloat(ITEM_FOCUS_DURATION))
    let deltaBlur: CGFloat = ITEM_MAX_BLUR_AMOUNT-ITEM_MIN_BLUR_AMOUNT
    let blurAmount = ITEM_MAX_BLUR_AMOUNT-deltaBlur*fraction
    (node as! SKEffectNode).filter!.setValue(blurAmount, forKey: kCIInputRadiusKey)

})

focusAction.timingMode = .easeIn
effectNode.run(focusAction)
</code>```

Body:
I'm trying to blur a SKShapenode in my program. However, I want the shapenode to blur progressively, with a duration of about 1 second. How do I achieve that? The current code blurs it instantly.

func generateAnimation() {

var blurAction : SKAction = SKAction.runBlock{
   //the method below returns a shapeNode
    var circle = self.generateImage()
    var effect : SKEffectNode = SKEffectNode()
    var filter : CIFilter = CIFilter(name:"CIGaussianBlur")
    filter.setValue(10, forKey: "inputRadius")
    effect.filter = filter
    effect.addChild(circle)
    self.addChild(effect)
}

Body:
Here you go mate, Swift4 SpriteKit:

let ITEM_MAX_BLUR_AMOUNT: CGFloat = 20
let ITEM_MIN_BLUR_AMOUNT: CGFloat = 0
let ITEM_FOCUS_DURATION: TimeInterval = 0.2

let effectNode: SKEffectNode = SKEffectNode()

effectNode.filter = CIFilter = CIFilter(name: "CIGaussianBlur")
effectNode.shouldEnableEffects = true
addChild(effectNode)

let focusAction = SKAction.customAction(withDuration: ITEM_FOCUS_DURATION, actionBlock: { (node : SKNode!, elapsedTime : CGFloat) -> Void in

    let fraction = CGFloat(elapsedTime / CGFloat(ITEM_FOCUS_DURATION))
    let deltaBlur: CGFloat = ITEM_MAX_BLUR_AMOUNT-ITEM_MIN_BLUR_AMOUNT
    let blurAmount = ITEM_MAX_BLUR_AMOUNT-deltaBlur*fraction
    (node as! SKEffectNode).filter!.setValue(blurAmount, forKey: kCIInputRadiusKey)

})

focusAction.timingMode = .easeIn
effectNode.run(focusAction)


问:
How to transpose this table in SQL Server 2012

I want to transpose this table which has only 1 row with client id and the response columns as response1, response2 and so on.

I tried with pivot but not able to apply correctly

答:
Try this : this can be achieve by using STUFF

```<code>SELECT
  CLientID
, STUFF((
    SELECT N', ' + CAST(Response AS VARCHAR(4000))
    FROM TableName t2
    WHERE t1.CLientID= t2.CLientID
    FOR XML PATH ('')), 1, 2, '') AS Response
FROM TableName t1
</code>```

Body:
Try this : this can be achieve by using STUFF

SELECT
  CLientID
, STUFF((
    SELECT N', ' + CAST(Response AS VARCHAR(4000))
    FROM TableName t2
    WHERE t1.CLientID= t2.CLientID
    FOR XML PATH ('')), 1, 2, '') AS Response
FROM TableName t1


问:
Where does Console.WriteLine go in Debug?
I found this question, but what I want to know is different - does the output from Console.WriteLine go anywhere when debugging? I know that for it to go to the output window I should should Debug.WriteLine() or other methods, but where does the standard Console.WriteLine() go?

Edit
When debugging, you don't see the black console window / test log - so the real question is how can I access/view this output during debugging?

答:
Visual Studio launches Windows programs (/target:winexe) with the stdin/stdout/stderr redirected to Named Pipes. The other end of each pipe is owned by the VS debugger and anything read on stderr/stdout is displayed in the Debug Output Window. Hence, Console.Write auto-magically appears in the VS Debug output. Note that this does not happen if you attach to an already started process (since the redirect trick can only be done at process launch time).

When launching console programs (/target:exe) this redirect does not occur so the Console.Write goes tothe actual console (or wherever the stdout is redirected).

I couldn't find anything that documents this behavior, is just my conclusion from investigating how VS launches and debugs apps.


问:
Symfony 3 : Swiftmailer won't send email from website while working with the swiftmailer:email:send command
I face a problem I don't understand.

I use SwiftMailer to send emails (ex : registration confirmation) from a website using the Mailjet SMTP. Mails are not sent.

The Symfony profiler says that 1 mail is spooled when I create a user account, but it is never sent.
php bin/console swiftmailer:spool:send returns 0 emails sent. I tried memory and file spools.

When using the php bin/console swiftmailer:email :send, mails are correctly sent (mails have the mailjet headers and they are in the mailjet sent mails interface).

When I'm trying the OVH SMTP, mails are correcly sent both from the application and cli command, so the problem seems to be a SwiftMailer misconfiguration.

Here is my setup :

app/config/config.yml

```<code>swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host_prod%"
    port:      "%mailer_port_prod%"
    encryption:"%mailer_encryption_prod%"
    username:  "%mailer_user_prod%"
    password:  "%mailer_password_prod%"
    spool:     { type: memory }
</code>```

app/config/parameters.yml

```<code>mailer_transport: smtp

mailer_host_prod: in-v3.mailjet.com
mailer_port_prod: 587
mailer_encryption_prod: tls
mailer_user_prod: api_key
mailer_password_prod: api_secret

mailer_host_ovh: ssl0.ovh.net
mailer_port_ovh: 465
mailer_encryption_ovh: ssl
mailer_user_ovh: email
mailer_password_ovh: password
</code>```

答:
Finally, it was the sender's email who was wrong. I forgot to update it after going prod.
At this moment, Mailjet successfuly receive the email but put it in queue and don't send it. On Symfony side, it is a success.</p>

Body:
I face a problem I don't understand.

I use SwiftMailer to send emails (ex : registration confirmation) from a website using the Mailjet SMTP. Mails are not sent.

The Symfony profiler says that 1 mail is spooled when I create a user account, but it is never sent.
php bin/console swiftmailer:spool:send returns 0 emails sent. I tried memory and file spools.

When using the php bin/console swiftmailer:email :send, mails are correctly sent (mails have the mailjet headers and they are in the mailjet sent mails interface).

When I'm trying the OVH SMTP, mails are correcly sent both from the application and cli command, so the problem seems to be a SwiftMailer misconfiguration.

Here is my setup :

app/config/config.yml

swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host_prod%"
    port:      "%mailer_port_prod%"
    encryption:"%mailer_encryption_prod%"
    username:  "%mailer_user_prod%"
    password:  "%mailer_password_prod%"
    spool:     { type: memory }

app/config/parameters.yml

mailer_transport: smtp

mailer_host_prod: in-v3.mailjet.com
mailer_port_prod: 587
mailer_encryption_prod: tls
mailer_user_prod: api_key
mailer_password_prod: api_secret

mailer_host_ovh: ssl0.ovh.net
mailer_port_ovh: 465
mailer_encryption_ovh: ssl
mailer_user_ovh: email
mailer_password_ovh: password


问:
XPATH Multiple Element Filters
I have the following sample XML structure:

```<code><SavingAccounts>
    <SavingAccount>
       <ServiceOnline>yes</ServiceOnline>
       <ServiceViaPhone>no</ServiceViaPhone>
    </SavingAccount>
    <SavingAccount>
       <ServiceOnline>no</ServiceOnline>
       <ServiceViaPhone>yes</ServiceViaPhone>
    </SavingAccount>
</SavingAccounts>
</code>```

What I need to do is filter the 'SavingAccount' nodes using XPATH where the value of 'ServiceOnline' is 'yes' or the value of 'ServiceViaPhone' is yes.

The XPATH should return me two rows!! I can filter 'SavingAccount' nodes where both of the element values are yes like the following XPATH sample, but what I want to do is an or element value comparison???

```<code>/SavingAccounts/SavingAccount/ServiceOnline[text()='yes']/../ServiceViaPhone[text()='yes']/..
</code>```

答:
This is a very fundamental XPath feature: composing a number of conditions with the logical operators and, or, and the function not().

and has a higher priority than or and both operators have lower priority than the relational and equality operators (=, !=, >, >=, < and <=).

So, it is safe to write: A = B and C = D

Some most frequent mistakes made:

People write AND and/or OR. Remember, XPath is case-sensitive.

People use the | (union) operator instead of or

Lastly, here is my solution:

```
/SavingAccounts/SavingAccount
           [ServiceOnLine='yes' or ServiceViaPhone='yes']
```

OwnerDisplayName: CroweMan

LastEditorDisplayName: Dimitre Novatchev

Title: XPATH Multiple Element Filters

Body:
I have the following sample XML structure:

<SavingAccounts>
    <SavingAccount>
       <ServiceOnline>yes</ServiceOnline>
       <ServiceViaPhone>no</ServiceViaPhone>
    </SavingAccount>
    <SavingAccount>
       <ServiceOnline>no</ServiceOnline>
       <ServiceViaPhone>yes</ServiceViaPhone>
    </SavingAccount>
</SavingAccounts>

What I need to do is filter the 'SavingAccount' nodes using XPATH where the value of 'ServiceOnline' is 'yes' or the value of 'ServiceViaPhone' is yes.

The XPATH should return me two rows!! I can filter 'SavingAccount' nodes where both of the element values are yes like the following XPATH sample, but what I want to do is an or element value comparison???

/SavingAccounts/SavingAccount/ServiceOnline[text()='yes']/../ServiceViaPhone[text()='yes']/..

Body:
This is a very fundamental XPath feature: composing a number of conditions with the logical operators and, or, and the function not().

and has a higher priority than or and both operators have lower priority than the relational and equality operators (=, !=, >, >=, &lt; and &lt;=).

So, it is safe to write: A = B and C = D

Some most frequent mistakes made:

People write AND and/or OR. Remember, XPath is case-sensitive.

People use the | (union) operator instead of or

Lastly, here is my solution:

/SavingAccounts/SavingAccount
           [ServiceOnLine='yes' or ServiceViaPhone='yes']

OwnerDisplayName: Dimitre Novatchev


问:
Code Golf: Countdown Number Game

Challenge

Here is the task, inspired by the well-known British TV game show Countdown. The challenge should be pretty clear even without any knowledge of the game, but feel free to ask for clarifications.

And if you fancy seeing a clip of this game in action, check out this YouTube clip. It features the wonderful late Richard Whitely in 1997.

You are given 6 numbers, chosen at random from the set {1, 2, 3, 4, 5, 6, 8, 9, 10, 25, 50, 75, 100}, and a random target number between 100 and 999. The aim is to use the six given numbers and the four common arithmetic operations (addition, subtraction, multiplication, division; all over the rational numbers) to generate the target - or as close as possible either side. Each number may only be used once at most, while each arithmetic operator may be used any number of times (including zero.) Note that it does not matter how many numbers are used.

Write a function that takes the target number and set of 6 numbers (can be represented as list/collection/array/sequence) and returns the solution in any standard numerical notation (e.g. infix, prefix, postfix). The function must always return the closest-possible result to the target, and must run in at most 1 minute on a standard PC. Note that in the case where more than one solution exists, any single solution is sufficient.

Examples:

{50, 100, 4, 2, 2, 4}, target 203

e.g. 100 * 2 + 2 + (4 / 4) (exact)

e.g. (100 + 50) * 4 * 2 / (4 + 2) (exact)

{25, 4, 9, 2, 3, 10}, target 465

e.g. (25 + 10 - 4) * (9 * 2 - 3) (exact)

{9, 8, 10, 5, 9, 7}, target 241

e.g. ((10 + 9) * 9 * 7) + 8) / 5 (exact)

{3, 7, 6, 2, 1, 7}, target 824

e.g. ((7 * 3) - 1) * 6 - 2) * 7 (= 826; off by 2)

Rules

Other than mentioned in the problem statement, there are no further restrictions. You may write the function in any standard language (standard I/O is not necessary). The aim as always is to solve the task with the smallest number of characters of code.

Saying that, I may not simply accept the answer with the shortest code. I'll also be looking at elegance of the code and time complexity of the algorithm!

My Solution

I'm attempting an F# solution when I find the free time - will post it here when I have something!

Format

Please post all answers in the following format for the purpose of easy comparison:

Language

Number of characters: ???

Fully obfuscated function:

```<code>(code here)
</code>```

Clear (ideally commented) function:

```<code>(code here)
</code>```

Any notes on the algorithm/clever shortcuts it takes.

Title: Code Golf: Countdown Number Game

Body:
Challenge

Here is the task, inspired by the well-known British TV game show Countdown. The challenge should be pretty clear even without any knowledge of the game, but feel free to ask for clarifications.

And if you fancy seeing a clip of this game in action, check out this YouTube clip. It features the wonderful late Richard Whitely in 1997.

You are given 6 numbers, chosen at random from the set {1, 2, 3, 4, 5, 6, 8, 9, 10, 25, 50, 75, 100}, and a random target number between 100 and 999. The aim is to use the six given numbers and the four common arithmetic operations (addition, subtraction, multiplication, division; all over the rational numbers) to generate the target - or as close as possible either side. Each number may only be used once at most, while each arithmetic operator may be used any number of times (including zero.) Note that it does not matter how many numbers are used.

Write a function that takes the target number and set of 6 numbers (can be represented as list/collection/array/sequence) and returns the solution in any standard numerical notation (e.g. infix, prefix, postfix). The function must always return the closest-possible result to the target, and must run in at most 1 minute on a standard PC. Note that in the case where more than one solution exists, any single solution is sufficient.

Examples:

{50, 100, 4, 2, 2, 4}, target 203

e.g. 100 * 2 + 2 + (4 / 4) (exact)

e.g. (100 + 50) * 4 * 2 / (4 + 2) (exact)

{25, 4, 9, 2, 3, 10}, target 465

e.g. (25 + 10 - 4) * (9 * 2 - 3) (exact)

{9, 8, 10, 5, 9, 7}, target 241

e.g. ((10 + 9) * 9 * 7) + 8) / 5 (exact)

{3, 7, 6, 2, 1, 7}, target 824

e.g. ((7 * 3) - 1) * 6 - 2) * 7 (= 826; off by 2)

Rules

Other than mentioned in the problem statement, there are no further restrictions. You may write the function in any standard language (standard I/O is not necessary). The aim as always is to solve the task with the smallest number of characters of code.

Saying that, I may not simply accept the answer with the shortest code. I'll also be looking at elegance of the code and time complexity of the algorithm!

My Solution

I'm attempting an F# solution when I find the free time - will post it here when I have something!

Format

Please post all answers in the following format for the purpose of easy comparison:

Language

Number of characters: ???

Fully obfuscated function:

(code here)

Clear (ideally commented) function:

(code here)

Any notes on the algorithm/clever shortcuts it takes.

Body:
Ruby 1.9.2

Number of characters: 404

I give up for now, it works as long as there is an exact answer.  If there isn't it takes way too long to enumerate all possibilities.

Fully Obfuscated

def b a,o,c,p,r
o+c==2*p ?r<<a :o<p ?b(a+['('],o+1,c,p,r):0;c<o ?b(a+[')'],o,c+1,p,r):0
end
w=a=%w{+ - * /}
4.times{w=w.product a}
b [],0,0,3,g=[]
*n,l=$<.read.split.map(&:to_f)
h={}
catch(0){w.product(g).each{|c,f|k=f.zip(c.flatten).each{|o|o.reverse! if o[0]=='('};n.permutation{|m|h[x=eval(d=m.zip(k)*'')]=d;throw 0 if x==l}}}
c=h[k=h.keys.min_by{|i|(i-l).abs}]
puts c.gsub(/(\d*)\.\d*/,'\1')+"=#{k}"

Decoded

Coming soon

Test script

#!/usr/bin/env ruby
[
  [[50,100,4,2,2,4],203],
  [[25,4,9,2,3,10],465],
  [[9,8,10,5,9,7],241],
  [[3,7,6,2,1,7],824]
].each do |b|
  start = Time.now
  puts "{[#{b[0]*', '}] #{b[1]}}  gives #{`echo "#{b[0]*' '} #{b[1]}" | ruby count-golf.rb`.strip} in #{Time.now-start}"
end

Output

→ ./test.rb
{[50, 100, 4, 2, 2, 4] 203}  gives 100+(4+(50-(2)/4)*2)=203.0 in 3.968534736
{[25, 4, 9, 2, 3, 10] 465}  gives 2+(3+(25+(9)*10)*4)=465.0 in 1.430715549
{[9, 8, 10, 5, 9, 7] 241}  gives 5+(9+(8)+10)*9-(7)=241.0 in 1.20045702
{[3, 7, 6, 2, 1, 7] 824}  gives 7*(6*(7*(3)-1)-2)=826.0 in 193.040054095

Details

The function used for generating the bracket pairs (b) is based off this one: Finding all combinations of well-formed brackets


问:
Unable to insert an Object into Database in Laravel
I'm a laravel beginner, didn't found a solution for my problem.

I created a form to enter the urlname into database - which works fine.
But for the pagespeed variable I always get this error:

This is part of my Controller:

```<code>//Create URL
$url = new URL;
$url->urlname= $request->input('urlname');
$url->pagespeed= $pspeed;

//Save url
$url->save();

//Return redirect
return redirect('/');
</code>```

I put this in my migration:

```<code>public function up()
{

}
</code>```

Maybe someone can help me with this.

答:
You need to save getResults() function result rather than whole object, try this way:

```<code>public function create(Request $request) {
    $pspeed = new \PageSpeed\Insights\Service();
    $pspeedResult = $pspeed->getResults('https://www.example.com');

    //Create URL
    $url = new URL;
    $url->urlname = $request->input('urlname');
    $url->pagespeed = json_encode($pspeedResult);

    //Save url
    $url->save();

    //Return redirect
    return redirect('/');
}
</code>```

When fetching data back from the database, remember about decoding data from json to array $data = json_decode($url->pagespeed, true);

You can also use mutators instead manual decoding/encoding your arrays.

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class URL extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'pagespeed' => 'array',
    ];
}
</code>```

Body:
I'm a laravel beginner, didn't found a solution for my problem.

I created a form to enter the urlname into database - which works fine.
But for the pagespeed variable I always get this error:

This is part of my Controller:

//Create URL
$url = new URL;
$url->urlname= $request->input('urlname');
$url->pagespeed= $pspeed;

//Save url
$url->save();

//Return redirect
return redirect('/');

I put this in my migration:

public function up()
{

}

Maybe someone can help me with this.

Body:
You need to save getResults() function result rather than whole object, try this way:

public function create(Request $request) {
    $pspeed = new \PageSpeed\Insights\Service();
    $pspeedResult = $pspeed->getResults('https://www.example.com');

    //Create URL
    $url = new URL;
    $url->urlname = $request->input('urlname');
    $url->pagespeed = json_encode($pspeedResult);

    //Save url
    $url->save();

    //Return redirect
    return redirect('/');
}

When fetching data back from the database, remember about decoding data from json to array $data = json_decode($url->pagespeed, true);

You can also use mutators instead manual decoding/encoding your arrays.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class URL extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'pagespeed' => 'array',
    ];
}


答:
```<code>// You are making a new PageSpeed object
$pspeed = new \PageSpeed\Insights\Service();

// Next you are getting the results for an url.
// You are not assigning the results to any variable
$pspeed->getResults('https://www.example.com');

...

// Now you are trying to fill the $url->pagespeed with
// the PageSpeed object instead of the results.
// This cause the error.
$url->pagespeed= $pspeed;
</code>```

Solution could be:

```<code>$pspeed = new \PageSpeed\Insights\Service();

// Assigning it to a variable:
$results = $pspeed->getResults('https://www.example.com');

...

// Storing the results, instead of the PageSpeed object
$url->pagespeed= $results;
</code>```

Attention that getResults(...) returns an array.

Title: Unable to insert an Object into Database in Laravel

Body:
// You are making a new PageSpeed object
$pspeed = new \PageSpeed\Insights\Service();

// Next you are getting the results for an url.
// You are not assigning the results to any variable
$pspeed->getResults('https://www.example.com');

...

// Now you are trying to fill the $url->pagespeed with
// the PageSpeed object instead of the results.
// This cause the error.
$url->pagespeed= $pspeed;

Solution could be:

$pspeed = new \PageSpeed\Insights\Service();

// Assigning it to a variable:
$results = $pspeed->getResults('https://www.example.com');

...

// Storing the results, instead of the PageSpeed object
$url->pagespeed= $results;

Attention that getResults(...) returns an array.


答:
You need to encode your object first in json so that you can store it in string type column.

So

```<code>$pspeed->getResults('https://www.example.com');
$url->pagespeed= $pspeed;
</code>```

Needs to be changed into

```<code>$results = $pspeed->getResults('https://www.example.com');
$url->pagespeed= json_encode($results );
</code>```

Body:
You need to encode your object first in json so that you can store it in string type column.

So

$pspeed->getResults('https://www.example.com');
$url->pagespeed= $pspeed;

Needs to be changed into

$results = $pspeed->getResults('https://www.example.com');
$url->pagespeed= json_encode($results );


问:
Why does UIView animation change View frame?
UPDATE: I added an explicit call to set the frame of the "to" view in the completion handler for the transition. This solves the "problem" but does not answer the question about WHY the frame changes on hide. Here is the new animation call. NOTE - I cleaned up the code a little by making a function for handling the spanSuperView() and animations, so this does not exactly match the original code. Gist is updated. I hope it helps someone, and perhaps someone else knows WHY.

This is the animation that works for multiple times:

```<code>func animateView(_ new: UIView) {
    UIView.transition(from: self.currentView, to: new, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: { finished in
            new.spanSuperView()
            new.isHidden = false
            self.currentView.isHidden = true
            self.currentView = new
            self.container.layoutIfNeeded()
    })
}
</code>```

The animation is now called in the button switch method rather than repeated:

```<code>@objc func viewChange(_ sender: UIButton) {
        print(sender.tag)
        switch sender.tag {
        case 1 :
            print("should look at view1")
            print(currentView)
            animateView(viewone)
        case 2 :
            print(currentView)
            animateView(viewtwo)
        case 3 :
            print(currentView)
            animateView(viewthree)
        case 4 :
            print(currentView)
            animateView(viewfour)
        default:
            animateView(viewone)
        }
    }
</code>```

Here is spanSuperView():

```<code>extension UIView {
    func spanSuperView() {
        guard superview != nil else { return }
        self.topAnchor.constraint(equalTo: superview!.topAnchor).isActive = true
        self.leadingAnchor.constraint(equalTo: superview!.leadingAnchor).isActive = true
        self.widthAnchor.constraint(equalTo: superview!.widthAnchor, multiplier: 1.0).isActive = true
        self.heightAnchor.constraint(equalTo: superview!.heightAnchor, multiplier: 1.0).isActive = true
        self.translatesAutoresizingMaskIntoConstraints = false
    }
}
</code>```

ANOTHER UPDATE:
If there is no UIView.transition (just show | hide), the issue does not come up at all:

```<code>func animateView(_ new: UIView) {
        if new == currentView { return }
        new.spanSuperView()
        new.isHidden = false
        self.currentView.isHidden = true
        self.currentView = new
}
</code>```

ORIGINAL QUESTION:
I'm trying to create a view with animated subviews, where the user can switch between them by clicking a button.
This works fine the first time that the view is shown, but the frame for the subviews changes after the first time, and then the view is animated without the subviews.

Here is the code for the playground. I also created a GIST

```<code>import UIKit
import PlaygroundSupport

class ButtonRow: UIView {
    var button1 = UIButton()
    var button2 = UIButton()
    var button3 = UIButton()
    var button4 = UIButton()
    var stackView = UIStackView()

    func updateButtonLabels(_ texts:[String]? = ["1", "2", "3", "4"]) {
        guard let texts = texts else { return }
        let buttons = [button1, button2, button3, button4]
        var i = 0
        for btn in buttons {
            btn.setTitle(texts[i], for: .normal)
            i += 1
        }
    }

    override init(frame: CGRect){
        super.init(frame: frame)
        makeStack()
        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(stackView)
        stackView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1.0).isActive = true
        stackView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1.0).isActive = true
        stackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    }

    func makeStack() {
        let buttons = [button1, button2, button3, button4]
        for btn in buttons {
            btn.backgroundColor = .gray
            btn.setTitleColor(.white, for: .normal)
            btn.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
            btn.translatesAutoresizingMaskIntoConstraints = false
        }
        stackView = UIStackView(arrangedSubviews: buttons)
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 10
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        stackView.frame = bounds
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MyViewController : UIViewController {

    // MARK: - Properties
    var viewone = UIView()
    var viewtwo = UIView()
    var viewthree = UIView()
    var viewfour = UIView()
    var container = UIView()
    var stackView = UIStackView()
    var buttonRow = ButtonRow()
    var currentView = UIView()

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        self.view = view
        setupStack()
    }

    override func viewWillLayoutSubviews() {
        print("will layout subviews")
        //autolayout the stack view
        let hSpacing: CGFloat = UIScreen.main.bounds.width/8
        let wSpacing: CGFloat = UIScreen.main.bounds.width/10
        if #available(iOS 11.0, *) {
            let guide = self.view.safeAreaLayoutGuide
            stackView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -wSpacing).isActive = true
            stackView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: wSpacing).isActive = true
            stackView.topAnchor.constraint(equalTo: guide.topAnchor, constant: hSpacing).isActive = true
            stackView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -hSpacing).isActive = true

        }
        else {
            let margins = view.layoutMarginsGuide
            stackView.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -wSpacing).isActive = true
            stackView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: wSpacing).isActive = true
            stackView.topAnchor.constraint(equalTo: margins.topAnchor, constant: hSpacing).isActive = true
            stackView.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -hSpacing).isActive = true
        }
    }

    func setupContainer() {
        container.backgroundColor = .yellow
        viewone.backgroundColor = .blue
        viewtwo.backgroundColor = .red
        viewthree.backgroundColor = .green
        viewfour.backgroundColor = .black
        for vl in [viewone, viewtwo, viewthree, viewfour] as [UIView]  {
            container.addSubview(vl)
            vl.isHidden = true
            vl.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
            vl.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
            vl.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 1.0).isActive = true
            vl.heightAnchor.constraint(equalTo: container.heightAnchor, multiplier: 1.0).isActive = true
            vl.translatesAutoresizingMaskIntoConstraints = false
        }

        currentView = viewone
        viewone.isHidden = false
    }

    func setupButtons() {
        buttonRow.updateButtonLabels()
        var i = 1
        for btn in [buttonRow.button1, buttonRow.button2, buttonRow.button3, buttonRow.button4] {
            btn.tag = i
            btn.addTarget(self, action: #selector(viewChange), for: .touchUpInside)
            i += 1
        }

    }

    func setupStack() {
        setupButtons()
        setupContainer()
        stackView = UIStackView(arrangedSubviews: [container, buttonRow])
        stackView.axis = .vertical
        stackView.distribution = .fill
        stackView.alignment = .fill
        stackView.spacing = 10
        stackView.translatesAutoresizingMaskIntoConstraints = false
        // add some component constraints
        let bHeight = buttonRow.heightAnchor.constraint(equalToConstant: 50)
        stackView.addConstraints([bHeight])

        view.addSubview(stackView)
    }

    // MARK: - Methods
    @objc func viewChange(_ sender: UIButton) {
        print(sender.tag)
        switch sender.tag {
        case 1 :
            print("should look at view1")
            print(currentView)
            UIView.transition(from: self.currentView, to: self.viewone, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)
            currentView = viewone
            viewone.isHidden = false
            viewtwo.isHidden = true
            viewthree.isHidden = true
            viewfour.isHidden = true
        case 2 :
            print(currentView)
            UIView.transition(from: self.currentView, to: self.viewtwo, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)
            currentView = viewtwo
            viewone.isHidden = true
            viewtwo.isHidden = false
            viewthree.isHidden = true
            viewfour.isHidden = true
        case 3 :
            print(currentView)
            UIView.transition(from: self.currentView, to: self.viewthree, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)
            currentView = viewthree
            viewone.isHidden = true
            viewtwo.isHidden = true
            viewthree.isHidden = false
            viewfour.isHidden = true
        case 4 :
            print(currentView)
            UIView.transition(from: self.currentView, to: self.viewfour, duration: 1, options: UIViewAnimationOptions.curveEaseInOut, completion: nil)
            currentView = viewfour
            viewone.isHidden = true
            viewtwo.isHidden = true
            viewthree.isHidden = true
            viewfour.isHidden = false
        default:
            currentView = viewone
            viewone.isHidden = false
            viewtwo.isHidden = true
            viewthree.isHidden = true
            viewfour.isHidden = true
        }
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
</code>```

The print statements show that there is still a currentview identified, but that it's frame changes from "frame = (0 0; 221 416)" to "frame = (-77 -96; 0 0)":

```<code>will layout subviews
will layout subviews
1
should look at view1
<UIView: 0x7f7f42100630; frame = (0 0; 221 416); layer = <CALayer: 0x600000221440>>
2
<UIView: 0x7f7f42100630; frame = (0 0; 221 416); layer = <CALayer: 0x600000221440>>
3
<UIView: 0x7f7f421031f0; frame = (0 0; 221 416); layer = <CALayer: 0x600000221340>>
4
<UIView: 0x7f7f421033d0; frame = (0 0; 221 416); layer = <CALayer: 0x600000220140>>
1
should look at view1
<UIView: 0x7f7f421035b0; frame = (0 0; 221 416); layer = <CALayer: 0x600000220de0>>
2
<UIView: 0x7f7f42100630; frame = (-77 -96; 0 0); layer = <CALayer: 0x600000221440>>
3
<UIView: 0x7f7f421031f0; frame = (-77 -96; 0 0); layer = <CALayer: 0x600000221340>>
4
<UIView: 0x7f7f421033d0; frame = (-77 -96; 0 0); layer = <CALayer: 0x600000220140>>
</code>```

NOTE: I created a video, but I cannot seem to upload it to SO or my Gist.

I don't understand why the frame changes. What gives?

答:
I think that every time you call constraint on a NSLayoutAnchor, you create a new constraint so I wouldn't be surprised that after 2 iterations, UIKit cannot solve the constraints any more.

You should try to add a symbolic breakpoint for UIViewAlertForUnsatisfiableConstraints and see if that's your issue.

Body:
UPDATE: I added an explicit call to set the frame of the "to" view in the completion handler for the transition. This solves the "problem" but does not answer the question about WHY the frame changes on hide. Here is the new animation call. NOTE - I cleaned up the code a little by making a function for handling the spanSuperView() and animations, so this does not exactly match the original code. Gist is updated. I hope it helps someone, and perhaps someone else knows WHY.

This is the animation that works for multiple times:

func animateView(_ new: UIView) {
    UIView.transition(from: self.currentView, to: new, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: { finished in
            new.spanSuperView()
            new.isHidden = false
            self.currentView.isHidden = true
            self.currentView = new
            self.container.layoutIfNeeded()
    })
}

The animation is now called in the button switch method rather than repeated:

@objc func viewChange(_ sender: UIButton) {
        print(sender.tag)
        switch sender.tag {
        case 1 :
            print("should look at view1")
            print(currentView)
            animateView(viewone)
        case 2 :
            print(currentView)
            animateView(viewtwo)
        case 3 :
            print(currentView)
            animateView(viewthree)
        case 4 :
            print(currentView)
            animateView(viewfour)
        default:
            animateView(viewone)
        }
    }

Here is spanSuperView():

extension UIView {
    func spanSuperView() {
        guard superview != nil else { return }
        self.topAnchor.constraint(equalTo: superview!.topAnchor).isActive = true
        self.leadingAnchor.constraint(equalTo: superview!.leadingAnchor).isActive = true
        self.widthAnchor.constraint(equalTo: superview!.widthAnchor, multiplier: 1.0).isActive = true
        self.heightAnchor.constraint(equalTo: superview!.heightAnchor, multiplier: 1.0).isActive = true
        self.translatesAutoresizingMaskIntoConstraints = false
    }
}

ANOTHER UPDATE:
If there is no UIView.transition (just show | hide), the issue does not come up at all:

func animateView(_ new: UIView) {
        if new == currentView { return }
        new.spanSuperView()
        new.isHidden = false
        self.currentView.isHidden = true
        self.currentView = new
}

ORIGINAL QUESTION:
I'm trying to create a view with animated subviews, where the user can switch between them by clicking a button.
This works fine the first time that the view is shown, but the frame for the subviews changes after the first time, and then the view is animated without the subviews.

Here is the code for the playground. I also created a GIST

import UIKit
import PlaygroundSupport

class ButtonRow: UIView {
    var button1 = UIButton()
    var button2 = UIButton()
    var button3 = UIButton()
    var button4 = UIButton()
    var stackView = UIStackView()

    func updateButtonLabels(_ texts:[String]? = ["1", "2", "3", "4"]) {
        guard let texts = texts else { return }
        let buttons = [button1, button2, button3, button4]
        var i = 0
        for btn in buttons {
            btn.setTitle(texts[i], for: .normal)
            i += 1
        }
    }

    override init(frame: CGRect){
        super.init(frame: frame)
        makeStack()
        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(stackView)
        stackView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1.0).isActive = true
        stackView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1.0).isActive = true
        stackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    }

    func makeStack() {
        let buttons = [button1, button2, button3, button4]
        for btn in buttons {
            btn.backgroundColor = .gray
            btn.setTitleColor(.white, for: .normal)
            btn.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
            btn.translatesAutoresizingMaskIntoConstraints = false
        }
        stackView = UIStackView(arrangedSubviews: buttons)
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 10
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        stackView.frame = bounds
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MyViewController : UIViewController {

    // MARK: - Properties
    var viewone = UIView()
    var viewtwo = UIView()
    var viewthree = UIView()
    var viewfour = UIView()
    var container = UIView()
    var stackView = UIStackView()
    var buttonRow = ButtonRow()
    var currentView = UIView()

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        self.view = view
        setupStack()
    }

    override func viewWillLayoutSubviews() {
        print("will layout subviews")
        //autolayout the stack view
        let hSpacing: CGFloat = UIScreen.main.bounds.width/8
        let wSpacing: CGFloat = UIScreen.main.bounds.width/10
        if #available(iOS 11.0, *) {
            let guide = self.view.safeAreaLayoutGuide
            stackView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -wSpacing).isActive = true
            stackView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: wSpacing).isActive = true
            stackView.topAnchor.constraint(equalTo: guide.topAnchor, constant: hSpacing).isActive = true
            stackView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -hSpacing).isActive = true

        }
        else {
            let margins = view.layoutMarginsGuide
            stackView.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -wSpacing).isActive = true
            stackView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: wSpacing).isActive = true
            stackView.topAnchor.constraint(equalTo: margins.topAnchor, constant: hSpacing).isActive = true
            stackView.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -hSpacing).isActive = true
        }
    }

    func setupContainer() {
        container.backgroundColor = .yellow
        viewone.backgroundColor = .blue
        viewtwo.backgroundColor = .red
        viewthree.backgroundColor = .green
        viewfour.backgroundColor = .black
        for vl in [viewone, viewtwo, viewthree, viewfour] as [UIView]  {
            container.addSubview(vl)
            vl.isHidden = true
            vl.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
            vl.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
            vl.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 1.0).isActive = true
            vl.heightAnchor.constraint(equalTo: container.heightAnchor, multiplier: 1.0).isActive = true
            vl.translatesAutoresizingMaskIntoConstraints = false
        }

        currentView = viewone
        viewone.isHidden = false
    }

    func setupButtons() {
        buttonRow.updateButtonLabels()
        var i = 1
        for btn in [buttonRow.button1, buttonRow.button2, buttonRow.button3, buttonRow.button4] {
            btn.tag = i
            btn.addTarget(self, action: #selector(viewChange), for: .touchUpInside)
            i += 1
        }

    }

    func setupStack() {
        setupButtons()
        setupContainer()
        stackView = UIStackView(arrangedSubviews: [container, buttonRow])
        stackView.axis = .vertical
        stackView.distribution = .fill
        stackView.alignment = .fill
        stackView.spacing = 10
        stackView.translatesAutoresizingMaskIntoConstraints = false
        // add some component constraints
        let bHeight = buttonRow.heightAnchor.constraint(equalToConstant: 50)
        stackView.addConstraints([bHeight])

        view.addSubview(stackView)
    }

    // MARK: - Methods
    @objc func viewChange(_ sender: UIButton) {
        print(sender.tag)
        switch sender.tag {
        case 1 :
            print("should look at view1")
            print(currentView)
            UIView.transition(from: self.currentView, to: self.viewone, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)
            currentView = viewone
            viewone.isHidden = false
            viewtwo.isHidden = true
            viewthree.isHidden = true
            viewfour.isHidden = true
        case 2 :
            print(currentView)
            UIView.transition(from: self.currentView, to: self.viewtwo, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)
            currentView = viewtwo
            viewone.isHidden = true
            viewtwo.isHidden = false
            viewthree.isHidden = true
            viewfour.isHidden = true
        case 3 :
            print(currentView)
            UIView.transition(from: self.currentView, to: self.viewthree, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)
            currentView = viewthree
            viewone.isHidden = true
            viewtwo.isHidden = true
            viewthree.isHidden = false
            viewfour.isHidden = true
        case 4 :
            print(currentView)
            UIView.transition(from: self.currentView, to: self.viewfour, duration: 1, options: UIViewAnimationOptions.curveEaseInOut, completion: nil)
            currentView = viewfour
            viewone.isHidden = true
            viewtwo.isHidden = true
            viewthree.isHidden = true
            viewfour.isHidden = false
        default:
            currentView = viewone
            viewone.isHidden = false
            viewtwo.isHidden = true
            viewthree.isHidden = true
            viewfour.isHidden = true
        }
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

The print statements show that there is still a currentview identified, but that it's frame changes from "frame = (0 0; 221 416)" to "frame = (-77 -96; 0 0)":

will layout subviews
will layout subviews
1
should look at view1
<UIView: 0x7f7f42100630; frame = (0 0; 221 416); layer = <CALayer: 0x600000221440>>
2
<UIView: 0x7f7f42100630; frame = (0 0; 221 416); layer = <CALayer: 0x600000221440>>
3
<UIView: 0x7f7f421031f0; frame = (0 0; 221 416); layer = <CALayer: 0x600000221340>>
4
<UIView: 0x7f7f421033d0; frame = (0 0; 221 416); layer = <CALayer: 0x600000220140>>
1
should look at view1
<UIView: 0x7f7f421035b0; frame = (0 0; 221 416); layer = <CALayer: 0x600000220de0>>
2
<UIView: 0x7f7f42100630; frame = (-77 -96; 0 0); layer = <CALayer: 0x600000221440>>
3
<UIView: 0x7f7f421031f0; frame = (-77 -96; 0 0); layer = <CALayer: 0x600000221340>>
4
<UIView: 0x7f7f421033d0; frame = (-77 -96; 0 0); layer = <CALayer: 0x600000220140>>

NOTE: I created a video, but I cannot seem to upload it to SO or my Gist.

I don't understand why the frame changes. What gives?


问:
Finding a list of functions in library in C
Is there a way of finding a list of functions of any library in c?

For example, i would like to find all functions of library string.h without looking it up online.

答:
You can just read it.

It generally doesn't have much stuff other than function declarations. If you want to be sure you don't miss any includes from string.h recursively, you can read the prepossessed result:

```<code>cc -E  -include string.h -x c /dev/null
</code>```

However, note that string.h is not a library. It's just a header that provides the declarations for a subset of a standard libc library (a library that gets linked to every hosted C program by default).

Also, you should generally limit yourself to using those declarations in the header that are standardized (in case some implementation declares any extras in its string.h), and to using them in a standard-sanctioned way.

Body:
You can just read it.

It generally doesn't have much stuff other than function declarations. If you want to be sure you don't miss any includes from string.h recursively, you can read the prepossessed result:

cc -E  -include string.h -x c /dev/null

However, note that string.h is not a library. It's just a header that provides the declarations for a subset of a standard libc library (a library that gets linked to every hosted C program by default).

Also, you should generally limit yourself to using those declarations in the header that are standardized (in case some implementation declares any extras in its string.h), and to using them in a standard-sanctioned way.


问:
Convert generic IList into an array of a subtype
(please don't ask why I'm doing this - I'm interfacing with some legacy code)

I have an IList<Animal> and I want to convert it to an array of a sub-type of Animal (e.g. Leopard), but the sub-type is not known at compile time - it's passed in as a parameter.

[edit: it's guaranteed the list will only contain leopards]

I have found a way that works:

var myArray = (object[])new ArrayList(animals.ToList()).ToArray(animalType)

the caller will then cast myArray to Leopard[] for instance.

is there a better solution?

答:
Try this:</p>

```<code>Animal[] animalArray = new Animal[animals.Count];
animals.CopyTo(animalArray, 0);
</code>```

Body:
Try this:

Animal[] animalArray = new Animal[animals.Count];
animals.CopyTo(animalArray, 0);


问:
is it possible to access value from a model databasetable in the application.html.erb?
im trying to make a app

with users
this users can join multiple groups - every group has the same menu on the page
their group page is accessable about group/1 or group/2

so i wanted to put the the menu in the application.html.erb, with lnks depending on the group.id - but i dont know how to acces this id in the application.html.erb

答:
This is often done using content_for in the layout. Let's say you want your menu in a certain div in application.html.erb:

```<code># application.html.erb
<div id="menu_div>
  <ul>
  ... etc ...
  </ul>
</div>
</code>```

Replace the inner content with a yield statement:

```<code><div id="menu_div>
  <%= yield :group_menu %>
</div>
</code>```

Then in the view template add the content_for block:

```<code># page
<% content_for :group_menu do %>
  <ul>
  ... etc ...
  </ul>
<% end %>
</code>```

Each page template can then define its own menu code in a  content_for block. This can be further generalized by using a helper method in the block and passing in instance variables.

EDIT

Assuming @group is assigned in the controller, you might do something like:

```<code><% content_for :group_menu do %>
  <%= show_me_the_menu(@group) %>
<% end %>
</code>```

and in the helper (obviously contrived example):

```<code>def show_me_the_menu(group)
  content_tag :ul do
    group.users.collect do |user|
      concat(content_tag(:li, user.some_method))
    end
  end
end
</code>```

Body:
This is often done using content_for in the layout. Let's say you want your menu in a certain div in application.html.erb:

# application.html.erb
<div id="menu_div>
  <ul>
  ... etc ...
  </ul>
</div>

Replace the inner content with a yield statement:

<div id="menu_div>
  <%= yield :group_menu %>
</div>

Then in the view template add the content_for block:

# page
<% content_for :group_menu do %>
  <ul>
  ... etc ...
  </ul>
<% end %>

Each page template can then define its own menu code in a  content_for block. This can be further generalized by using a helper method in the block and passing in instance variables.

EDIT

Assuming @group is assigned in the controller, you might do something like:

<% content_for :group_menu do %>
  <%= show_me_the_menu(@group) %>
<% end %>

and in the helper (obviously contrived example):

def show_me_the_menu(group)
  content_tag :ul do
    group.users.collect do |user|
      concat(content_tag(:li, user.some_method))
    end
  end
end


问:
What boot() method do in laravel?
there is register() method in Service Provider which is used for bind the classes but i don't know what boot() method's do ? can you please explain it.</p>

答:
What i can tell you is that Interfaces can be used in such situations where you want users to mandate to use defined methods in every inherited class. Such as when you define user login check method in your interface you can inherit to classes which are required to use this method to perform this method.

One noticeable problem with Interfaces is that once if you add a new method to your Interface it effects all its child classes as they might not have declared the new method in them. So it breaks and throws an error.

Title: What boot() method do in laravel?


问:
Check if the array contains a certain object
I was wondering how i could check if an array contains a certain value after the data is retrieved from firebase. I retrieve the data and store it in an array as follows:

```<code>    [self.firebase2 observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot){

    if (newMessagesOnTop) {
        [self.chat2 insertObject:snapshot.value atIndex:0];
    } else {
        [self.chat2 addObject:snapshot.value];
    }
</code>```

From here i want to check if there is a particular object in the array chat2. And I also want to know in which particular method should I put it.

Any help will be appreciated.

答:
```<code>if ([self.chat2 containsObject:snapshot.value]) {
    [self.chat2 insertObject:snapshot.value atIndex:0];
} else {
    [self.chat2 addObject:snapshot.value];
}
[self setNeedsDisplay];
[tableView reloadData];
</code>```

Body:
I was wondering how i could check if an array contains a certain value after the data is retrieved from firebase. I retrieve the data and store it in an array as follows:

    [self.firebase2 observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot){

    if (newMessagesOnTop) {
        [self.chat2 insertObject:snapshot.value atIndex:0];
    } else {
        [self.chat2 addObject:snapshot.value];
    }

From here i want to check if there is a particular object in the array chat2. And I also want to know in which particular method should I put it.

Any help will be appreciated.


问:
One-liner version of this function? (Ruby 1.8.6)
In the version of Ruby i'm using, (1.8.6 - don't ask), the Hash class doesn't define the Hash#hash method, which means that calling uniq on an array of hashes doesn't test whether the content is the same - it tests whether the objects are the same (using the default base Object#hash method).

To get around this, I can use include?, like so:

```<code>hashes = <a big list of hashes>
uniq_hashes = []
hashes.each do |hash|
  unless uniq_hashes.include?(hash)
    uniq_hashes << hash
  end
end;uniq_hashes.size
</code>```

Can anyone think of a way to condense this into a one-line method?

答:
```<code>hashes = <a big list of hashes>
uniq_hashes = []
hashes.each do |hash|
  unless uniq_hashes.include?(hash)
    uniq_hashes << hash
  end
end;uniq_hashes.size
</code>```

Can anyone think of a way to condense this into a one-line method?

Easy:

```<code>hashes = <a big list of hashes>; uniq_hashes = []; hashes.each do |hash| unless uniq_hashes.include?(hash) then uniq_hashes << hash end end;uniq_hashes.size
</code>```

In fact, you can always condense any Ruby code into one line, since newlines are completely optional. Newlines can always be replaced with either semicolons, separator keywords, or just nothing.

Body:
In the version of Ruby i'm using, (1.8.6 - don't ask), the Hash class doesn't define the Hash#hash method, which means that calling uniq on an array of hashes doesn't test whether the content is the same - it tests whether the objects are the same (using the default base Object#hash method).

To get around this, I can use include?, like so:

hashes =
uniq_hashes = []
hashes.each do |hash|
  unless uniq_hashes.include?(hash)
    uniq_hashes << hash
  end
end;uniq_hashes.size

Can anyone think of a way to condense this into a one-line method?

Body:
hashes = <a big list of hashes>
uniq_hashes = []
hashes.each do |hash|
  unless uniq_hashes.include?(hash)
    uniq_hashes << hash
  end
end;uniq_hashes.size

Can anyone think of a way to condense this into a one-line method?

Easy:

hashes = <a big list of hashes>; uniq_hashes = []; hashes.each do |hash| unless uniq_hashes.include?(hash) then uniq_hashes << hash end end;uniq_hashes.size

In fact, you can always condense any Ruby code into one line, since newlines are completely optional. Newlines can always be replaced with either semicolons, separator keywords, or just nothing.


问:
Modal jQuery doesn't work (bootstrap 4)
I have a problem with jQuery. When I click on the link the modal opens and I want to pass the value of data-href to the button inside the modal.

Nothing happens when I click the button. Could you please help me?

Link

```<code><a href="#" data-href="stackoverflow.com" data-toggle="modal" data-target="#openModal">Link</a>
</code>```

Modal

```<code><div class="modal fade" id="openModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-danger btn-ok" href="">Go</button>
                    </div>
                </div>
            </div>
        </div>
</code>```

JQuery

```<code>    <script>
        $('#openModal').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
            $('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-ok').attr('href') + '</strong>');
        });
    </script>
</code>```

jQuery/Popper/JS

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.2/umd/popper.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</code>```

Error

```<code>Uncaught ReferenceError: $ is not defined
</code>```

答:
Try this:

```<code>$('#openModal').on('show.bs.modal', function(e) {
    var data_href = $(e.relatedTarget).attr('data-href');
    console.log('data_href: ' + data_href);

    $(this).find('.btn-ok').attr('href', data_href);
    $('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-ok').attr('href') + '</strong>');
});
</code>```

What you did was good, but there was a little mistake in your code:

```<code>$(e.relatedTarget).data('href')
</code>```

You were trying to get the attribute href but the attribute on the button you are looking for is data-href

Title: Modal jQuery doesn't work (bootstrap 4)

Body:
I have a problem with jQuery. When I click on the link the modal opens and I want to pass the value of data-href to the button inside the modal.

Nothing happens when I click the button. Could you please help me?

Link

Link

Modal

                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-danger btn-ok" href="">Go</button>

JQuery

jQuery/Popper/JS

Error

Uncaught ReferenceError: $ is not defined

Body:
Try this:

$('#openModal').on('show.bs.modal', function(e) {
    var data_href = $(e.relatedTarget).attr('data-href');
    console.log('data_href: ' + data_href);

    $(this).find('.btn-ok').attr('href', data_href);
    $('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-ok').attr('href') + '</strong>');
});

What you did was good, but there was a little mistake in your code:

$(e.relatedTarget).data('href')

You were trying to get the attribute href but the attribute on the button you are looking for is data-href


问:
How to rename functions in android ndk library
guys. I want to change function names that I import from static lib, like ProGuard does it with java methods and classes. I think it can make reverse much harder. For example, if I check some file with sha1 I don't want the reverser to know what this function exactly is. He can see some func0024 instead.

Is it possible to make this with standard tools in android cmake? Or if it's not what tools can you advise for this task?

答:
According to Michael's answer you should add this line to your CMakeLists.txt file

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wl,--exclude-libs,ALL")


问:
scripts.bundle.js net::ERR_ABORTED running ng serve
I'm new to angular. I was able to run my angular application locally until I pushed it to heroku. This error shows up on my local machine. On heroku, it has another error Unexpected token < not sure if it's related.
So I do not know where to go to debug this error scripts.bundle.js net::ERR_ABORTED and scripts.bundle.js 404 (Not Found). This error shows up at the root of the app. Any guidance or some kind of direction would be really appreciated!

package.json

```<code>{
  "name": "user-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng server.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --aot -prod"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/cli": "^1.5.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "enhanced-resolve": "^3.3.0",
    "express": "4.16.2",
    "jquery": "^3.2.1",
    "jw-bootstrap-switch-ng2": "^1.0.7",
    "ng2-nouislider": "^1.7.4",
    "nouislider": "^10.1.0",
    "popper.js": "^1.12.3",
    "rxjs": "^5.4.2",
    "typescript": "2.6.1",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.6.2",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.2.16",
    "@types/node": "~8.0.47",
    "codelyzer": "~4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.2.0",
    "ts-node": "~3.3.0",
    "tslint": "~5.8.0"
  },
  "engines": {
    "node": "6.11.5",
    "npm": "5.5.1"
  }
}
</code>```

index.html

```<code><head>
<base href="/">
</head>
<body class="full-screen">
    <app-root></app-root>
</body>
</code>```

答:
I got the same error updating angular 4 to 5 and cli 1.4.7 to 1.5

I fixed it running:
npm cache verify

I hope that will solve your problem too.

Body:
I'm new to angular. I was able to run my angular application locally until I pushed it to heroku. This error shows up on my local machine. On heroku, it has another error Unexpected token < not sure if it's related.
So I do not know where to go to debug this error scripts.bundle.js net::ERR_ABORTED and scripts.bundle.js 404 (Not Found). This error shows up at the root of the app. Any guidance or some kind of direction would be really appreciated!

package.json

{
  "name": "user-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng server.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --aot -prod"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/cli": "^1.5.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "enhanced-resolve": "^3.3.0",
    "express": "4.16.2",
    "jquery": "^3.2.1",
    "jw-bootstrap-switch-ng2": "^1.0.7",
    "ng2-nouislider": "^1.7.4",
    "nouislider": "^10.1.0",
    "popper.js": "^1.12.3",
    "rxjs": "^5.4.2",
    "typescript": "2.6.1",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.6.2",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.2.16",
    "@types/node": "~8.0.47",
    "codelyzer": "~4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.2.0",
    "ts-node": "~3.3.0",
    "tslint": "~5.8.0"
  },
  "engines": {
    "node": "6.11.5",
    "npm": "5.5.1"
  }
}

index.html

<base href="/">

    <app-root></app-root>