问:
The cells in my collectionView are repeated. Which is the error?
I`m working on a project where I have to take the forecast data from the internet by using a method that takes the city name as a parameter. This information has to be shown in a collectionViewCell that also has a tableView. The problem is that the collectionViewCells are repeated but the information inside the array which contains the cities is not repeated.
If the information in the array says [Paris, Madrid, Washington], the cells appear as Paris, Madrid, Paris

```<code>import UIKit

class AddNewCityViewController: UIViewController, UIAlertViewDelegate {
@IBOutlet weak var LabelTextField: UILabel!
@IBOutlet weak var cityTextField: UITextField!

var cityName:String!
override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ForecastCollectionViewController.addNewCityName(_:)), name: message, object: self)

}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func addNewCity(sender: AnyObject) {

    cityName = cityTextField.text!
    var  cityNameDict = [String: String]()
    cityNameDict["cityName"] = cityName

    if cityTextField.text! != "" {
    NSNotificationCenter.defaultCenter().postNotificationName(message, object: nil, userInfo:cityNameDict)
    self.navigationController?.popViewControllerAnimated(true)

    } else {
        noTextAlert()
    }
}

    func noTextAlert () {
        let alertController = UIAlertController(title: "Campo de texto vacío", message: "Escriba el nombre de la ciudad.", preferredStyle: .Alert)

        let accept = UIAlertAction(title: "Aceptar", style: .Cancel) { (action) -> Void in
        }

        alertController.addAction(accept)

        self.presentViewController(alertController, animated: true, completion: nil)
    }
</code>```

}

//Collection View Controller

```<code>class ForecastCollectionViewController: UICollectionViewController, UIAlertViewDelegate{

@IBOutlet weak var infoLabel: UILabel!
var cityNames:[String] = []
var cityData = [CityData]()

override func viewDidLoad() {
    super.viewDidLoad()

    infoLabel.text = "Pulsa + para agrega una nueva ciudad"

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ForecastCollectionViewController.addNewCityName(_:)), name: message, object: nil)

}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print ("Number of items: \(cityData.count)")
    return  cityData.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    print("La ciudad agregada es \(cityData[indexPath.row].name!)")

    let collectionCell = self.collectionView!.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as! ForecastCollectionCell

    for item in cityData {
    collectionCell.currentCity = item
    collectionCell.current = item.name!
    print("Es " + item.name!)
    }

    return collectionCell
}

@IBAction func addButton(sender: AnyObject) {
    performSegueWithIdentifier("segue1", sender: nil)
}

func addNewCityName(notification: NSNotification) {

    let cityNameDict : [String:String!] = notification.userInfo as! [String:String!]
    let cityName = cityNameDict["cityName"]
    self.cityNames.append(cityName!)

    WeatherBase.sharedInstance.weatherDataWith(cityName!, completion: {(city) -> Void in
        print ("Se ejecuto el closure")
        let cityForecast = city.forecasts
        let name = city.name
        let countryISO = city.countryISO

        let newCity = CityData(name: name!, countryISO: countryISO!, forecasts: cityForecast!)

        self.cityData.append(newCity)
        self.collectionView!.reloadData()
        self.infoLabel.text = ""
        }
    )

    print("Se agregó \(cityName!) a la lista de ciudades.")

}

@IBAction func quitCity(sender: AnyObject) {

    let alertController = UIAlertController(title: "Desea eliminar esta ciudad", message: "Me falta completar esto :)", preferredStyle: .Alert)

    let yes = UIAlertAction(title: "Sí", style: .Default) { (action) -> Void in
        self.cityData.removeLast()
        self.collectionView?.reloadData()
    }
    let no = UIAlertAction(title: "No", style: .Cancel) { (action) -> Void in

    }

    alertController.addAction(yes)
    alertController.addAction(no)
    self.presentViewController(alertController, animated: true, completion: nil)
}
</code>```

//CollectionViewCellCotroller

```<code>class ForecastCollectionCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var countryNameLabel: UILabel!
@IBOutlet weak var countryTemperatureLabel: UILabel!
@IBOutlet weak var forecastTableView: UITableView!

var currentCity = CityData()
var current = CityData().name

override func awakeFromNib() {
    super.awakeFromNib()

    forecastTableView.delegate = self
    forecastTableView.dataSource = self

    print ("Llego información de: \(currentCity.name)")

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return  currentCity.forecasts.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let weatherCell = forecastTableView.dequeueReusableCellWithIdentifier("weatherTableCell", forIndexPath:  indexPath) as! WeatherTableViewCell

    let formatter = NSDateFormatter()
    formatter.dateFormat = "dd/MM/yyyy HH:mm"
    let myStringafd = formatter.stringFromDate(currentCity.forecasts[indexPath.row].time!)
    weatherCell.dateLabel.text = myStringafd

    weatherCell.temperatureLabel.text = String(currentCity.forecasts[indexPath.row].temperature) + "ºC"
    weatherCell.maxTemperatureLabel.text = String(currentCity.forecasts[indexPath.row].maximumTemperature) + "ºC"
    weatherCell.minTemperatureLabel.text = String(currentCity.forecasts[indexPath.row].minimumTemperature) + "ºC"
    weatherCell.backgroundImage.image = currentCity.forecasts[indexPath.row].background
    weatherCell.weatherDescriptionLabel.text = currentCity.forecasts[indexPath.row].weatherDescription
    weatherCell.weatherDescriptionLabel.textColor = UIColor.whiteColor()
    weatherCell.iconImageView.image = currentCity.forecasts[indexPath.row].icon

    for item in currentCity.forecasts {
    countryNameLabel.text = "\(current!), \(currentCity.countryISO!)"
    countryTemperatureLabel.text = String(item.temperature!) + "ºC"
    }
    return weatherCell
  }
}
</code>```

I´ve been thinking that the error is in the cellForRowAtItem, but I can`t see it clearly.

答:
Check how many no of rows are there in your No of Rows per section method

Print --> currentCity.forecasts.count

Body:
I`m working on a project where I have to take the forecast data from the internet by using a method that takes the city name as a parameter. This information has to be shown in a collectionViewCell that also has a tableView. The problem is that the collectionViewCells are repeated but the information inside the array which contains the cities is not repeated.
If the information in the array says [Paris, Madrid, Washington], the cells appear as Paris, Madrid, Paris

import UIKit

class AddNewCityViewController: UIViewController, UIAlertViewDelegate {
@IBOutlet weak var LabelTextField: UILabel!
@IBOutlet weak var cityTextField: UITextField!

var cityName:String!
override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ForecastCollectionViewController.addNewCityName(_:)), name: message, object: self)

}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func addNewCity(sender: AnyObject) {

    cityName = cityTextField.text!
    var  cityNameDict = [String: String]()
    cityNameDict["cityName"] = cityName

    if cityTextField.text! != "" {
    NSNotificationCenter.defaultCenter().postNotificationName(message, object: nil, userInfo:cityNameDict)
    self.navigationController?.popViewControllerAnimated(true)

    } else {
        noTextAlert()
    }
}

    func noTextAlert () {
        let alertController = UIAlertController(title: "Campo de texto vacío", message: "Escriba el nombre de la ciudad.", preferredStyle: .Alert)

        let accept = UIAlertAction(title: "Aceptar", style: .Cancel) { (action) -> Void in
        }

        alertController.addAction(accept)

        self.presentViewController(alertController, animated: true, completion: nil)
    }

}

//Collection View Controller

class ForecastCollectionViewController: UICollectionViewController, UIAlertViewDelegate{

@IBOutlet weak var infoLabel: UILabel!
var cityNames:[String] = []
var cityData = [CityData]()

override func viewDidLoad() {
    super.viewDidLoad()

    infoLabel.text = "Pulsa + para agrega una nueva ciudad"

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ForecastCollectionViewController.addNewCityName(_:)), name: message, object: nil)

}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print ("Number of items: \(cityData.count)")
    return  cityData.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    print("La ciudad agregada es \(cityData[indexPath.row].name!)")

    let collectionCell = self.collectionView!.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as! ForecastCollectionCell

    for item in cityData {
    collectionCell.currentCity = item
    collectionCell.current = item.name!
    print("Es " + item.name!)
    }

    return collectionCell
}

@IBAction func addButton(sender: AnyObject) {
    performSegueWithIdentifier("segue1", sender: nil)
}

func addNewCityName(notification: NSNotification) {

    let cityNameDict : [String:String!] = notification.userInfo as! [String:String!]
    let cityName = cityNameDict["cityName"]
    self.cityNames.append(cityName!)

    WeatherBase.sharedInstance.weatherDataWith(cityName!, completion: {(city) -> Void in
        print ("Se ejecuto el closure")
        let cityForecast = city.forecasts
        let name = city.name
        let countryISO = city.countryISO

        let newCity = CityData(name: name!, countryISO: countryISO!, forecasts: cityForecast!)

        self.cityData.append(newCity)
        self.collectionView!.reloadData()
        self.infoLabel.text = ""
        }
    )

    print("Se agregó \(cityName!) a la lista de ciudades.")

}

@IBAction func quitCity(sender: AnyObject) {

    let alertController = UIAlertController(title: "Desea eliminar esta ciudad", message: "Me falta completar esto :)", preferredStyle: .Alert)

    let yes = UIAlertAction(title: "Sí", style: .Default) { (action) -> Void in
        self.cityData.removeLast()
        self.collectionView?.reloadData()
    }
    let no = UIAlertAction(title: "No", style: .Cancel) { (action) -> Void in

    }

    alertController.addAction(yes)
    alertController.addAction(no)
    self.presentViewController(alertController, animated: true, completion: nil)
}

//CollectionViewCellCotroller

class ForecastCollectionCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var countryNameLabel: UILabel!
@IBOutlet weak var countryTemperatureLabel: UILabel!
@IBOutlet weak var forecastTableView: UITableView!

var currentCity = CityData()
var current = CityData().name

override func awakeFromNib() {
    super.awakeFromNib()

    forecastTableView.delegate = self
    forecastTableView.dataSource = self

    print ("Llego información de: \(currentCity.name)")

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return  currentCity.forecasts.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let weatherCell = forecastTableView.dequeueReusableCellWithIdentifier("weatherTableCell", forIndexPath:  indexPath) as! WeatherTableViewCell

    let formatter = NSDateFormatter()
    formatter.dateFormat = "dd/MM/yyyy HH:mm"
    let myStringafd = formatter.stringFromDate(currentCity.forecasts[indexPath.row].time!)
    weatherCell.dateLabel.text = myStringafd

    weatherCell.temperatureLabel.text = String(currentCity.forecasts[indexPath.row].temperature) + "ºC"
    weatherCell.maxTemperatureLabel.text = String(currentCity.forecasts[indexPath.row].maximumTemperature) + "ºC"
    weatherCell.minTemperatureLabel.text = String(currentCity.forecasts[indexPath.row].minimumTemperature) + "ºC"
    weatherCell.backgroundImage.image = currentCity.forecasts[indexPath.row].background
    weatherCell.weatherDescriptionLabel.text = currentCity.forecasts[indexPath.row].weatherDescription
    weatherCell.weatherDescriptionLabel.textColor = UIColor.whiteColor()
    weatherCell.iconImageView.image = currentCity.forecasts[indexPath.row].icon

    for item in currentCity.forecasts {
    countryNameLabel.text = "\(current!), \(currentCity.countryISO!)"
    countryTemperatureLabel.text = String(item.temperature!) + "ºC"
    }
    return weatherCell
  }
}

I´ve been thinking that the error is in the cellForRowAtItem, but I can`t see it clearly.


来源: stackexchange

问:
Filter pandas DataFrame by substring criteria
I have a pandas DataFrame with a column of string values. I need to select rows based on partial string matches.

Something like this idiom:

```<code>re.search(pattern, cell_in_question)
</code>```

returning a boolean. I am familiar with the syntax of df[df['A'] == "hello world"] but can't seem to find a way to do the same with a partial string match, say 'hello'.

答:
Maybe you want to search for some text in all columns of the Pandas dataframe, and not just in the subset of them. In this case, the following code will help.

```<code>df[df.apply(lambda row: row.astype(str).str.contains('String To Find').any(), axis=1)]
</code>```

Warning. This method is relatively slow, albeit convenient.

ContentLicense: CC BY-SA 4.0

Body:
I have a pandas DataFrame with a column of string values. I need to select rows based on partial string matches.

Something like this idiom:

re.search(pattern, cell_in_question)

returning a boolean. I am familiar with the syntax of df[df['A'] == "hello world"] but can't seem to find a way to do the same with a partial string match, say 'hello'.

Body:
Maybe you want to search for some text in all columns of the Pandas dataframe, and not just in the subset of them. In this case, the following code will help.

df[df.apply(lambda row: row.astype(str).str.contains('String To Find').any(), axis=1)]

Warning. This method is relatively slow, albeit convenient.


问:
fadeOut not working in IE7/IE8
I'm not quite sure why this bit of jQuery isn't working in IE7 & IE8.  Does anyone have any ideas what could be causing this?</p>

答: I got it, I just needed to remove position:relative and it fades out perfectly.  I'm not quite sure why that is though...</p>

ContentLicense: CC BY-SA 3.0

Title: fadeOut not working in IE7/IE8


问:
How do I get two dockerized applications to talk on a given port?
I'm trying to get two dockerized applications to speak to eachother on a given port according to my docker-compose.yml file.

They are able to speak to eachother on port app1:61001 and app2:61002, but my friend tells me that they should be able to communicate on port 80. example.. app2:80, and that port 61001 and 61002 should only be the accessible ports exposed out of the swarm.

The applications themselves are set to server.port=80

Any idea how I can get it working as my friend suggests?

Here is the docker-compose file I'm using:

docker compose

```<code>version: "3.5"

services:
  app1:
    image: docker.artifactory.gr.gr.com/app1:latest
    ports:
      - "61001:80"
    deploy:
      replicas: 2
    networks:
      - custom-network

  app2:
    image: docker.artifactory.gr.gr.com/app2:latest
    ports:
      - "61002:80"
    deploy:
      replicas: 2
    networks:
      - custom-network

networks:
  custom-network:
</code>```

My

答:
first, look if your service expose port 80 with docker-compose ps command.

If is in this case, juste remove folowing code of your both services

```<code>    ports:
      - "61002:80"
</code>```

if not, remove

```<code>    ports:
      - "61002:80"
</code>```

and add

```<code>    expose: 80
</code>```

and in your app script, to call one service, just call appN:80

I hope i understood your request and i helped you

Body:
I'm trying to get two dockerized applications to speak to eachother on a given port according to my docker-compose.yml file.

They are able to speak to eachother on port app1:61001 and app2:61002, but my friend tells me that they should be able to communicate on port 80. example.. app2:80, and that port 61001 and 61002 should only be the accessible ports exposed out of the swarm.

The applications themselves are set to server.port=80

Any idea how I can get it working as my friend suggests?

Here is the docker-compose file I'm using:

docker compose

version: "3.5"

services:
  app1:
    image: docker.artifactory.gr.gr.com/app1:latest
    ports:
      - "61001:80"
    deploy:
      replicas: 2
    networks:
      - custom-network

  app2:
    image: docker.artifactory.gr.gr.com/app2:latest
    ports:
      - "61002:80"
    deploy:
      replicas: 2
    networks:
      - custom-network

networks:
  custom-network:

My

Body:
first, look if your service expose port 80 with docker-compose ps command.

If is in this case, juste remove folowing code of your both services

    ports:
      - "61002:80"

if not, remove

    ports:
      - "61002:80"

and add

    expose: 80

and in your app script, to call one service, just call appN:80

I hope i understood your request and i helped you


问:
How to collect data and headers for non blank cells in a row in Sheets
I cannot find a solution to my problem:

I have a sheet with ~290 rows and ~80 columns. The first row and column are fixed/header.

I would like to collect non-blank values and their header into column B.

I've tried to search for solutions, but I'm not as good at excel, so I cannot wrap my head around most of the advice that I've found.

答:
Excel is not the same Google Sheets

```<code>=ARRAYFORMULA(TRIM(REGEXREPLACE(
  TRANSPOSE(
    QUERY(TRANSPOSE(IF(C2:F13<>"",C1:F1 & ", ","")),,99^99)
  ),
  "((\s+)|(,\s*$))",
  " "
)))
</code>```

My sample

Body:
Excel is not the same Google Sheets

=ARRAYFORMULA(TRIM(REGEXREPLACE(
  TRANSPOSE(
    QUERY(TRANSPOSE(IF(C2:F13<>"",C1:F1 & ", ","")),,99^99)
  ),
  "((\s+)|(,\s*$))",
  " "
)))

My sample


问:
How to do a Close Confirmation with a Xamarin Forms mac App?
I have a Xamarin.Forms application for iOS, Android, and now hopefully Mac.  I made all the adjustments for the UI to look great on Mac.  Submitted it for approval where it was rejected because the user can close the window while the app and menu bar is still running.  So I figure I would just add a confirmation pop-up asking if they want to exit the app when they try to close the window.

OK = Terminate the App.

Cancel = Keep the window open.

I find lots of articles on how to handle this with a Xamarin.Mac app, but nothing on how to handle Xamarin.Forms on Mac.  The FormsApplicationDelegate does not give access to the View Controller or the Window Delegate in order to override the WindowShouldClose method.  I found that I can use NSAlert to do the pop-up which works great.  Now I cannot find anything on what to do when the user responds. Open to suggestions.

```<code> private void Window_WillClose(object sender, System.EventArgs e)
    {
        NSNotification senderNotification = ((NSNotification)sender);
        NSWindow closingWindow = (NSWindow)senderNotification.Object;

        var confirmation = new NSAlert()
        {
            AlertStyle = NSAlertStyle.Warning,
            InformativeText = "Are you sure you want to exit the App?",
            MessageText = "Exit?"
        };
        confirmation.AddButton("OK");
        confirmation.AddButton("Cancel");
        var result = confirmation.RunModal();

        if (result == 1001)
        {
            //Cancel closing the window
        }
        else
        {
            //terminate the app
        }

    }
</code>```

答:
After a lot of experimenting, I did find a solution.  Here is what officially passed Apple's review.  It requires that n menu action is linked as "New Window".  It keeps tracks of the open windows and when there is only one left, it prompts to close the app.  If the user closes all the windows and keeps the app running, they have the option to open a new window in the menu.</p>

```<code> [Register("AppDelegate")]
    public class AppDelegate : FormsApplicationDelegate
    {
        public NSWindow window;
        private bool closeApp;
        private List<NSWindow> openWindows;
        public override NSWindow MainWindow
        {
            get { return window; }
        }

        public AppDelegate()
        {
            this.closeApp = false;
            this.openWindows = new List<NSWindow>();
            createNewWindow();
        }

        [Action("newWindow:")]
        public void newWindow(NSObject sender)
        {

            createNewWindow();
            this.window.MakeKeyAndOrderFront(sender);
            LoadApplication(new App());
            base.DidFinishLaunching(null);

        }

        private void createNewWindow()
        {
            var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled;
            var rect = new CoreGraphics.CGRect(200, 1000, 1024, 768);
            window = new MainWindow(rect, style, NSBackingStore.Buffered, false);
            window.Title = "MyApp"; // choose your own Title here
            window.TitleVisibility = NSWindowTitleVisibility.Hidden;
            window.WillClose += Window_WillClose;
            openWindows.Add(window);
        }

        private void Window_WillClose(object sender, System.EventArgs e)
        {
            openWindows.Remove((NSWindow)((NSNotification)sender).Object);
            if (openWindows.Count == 0)
            {
                var confirmation = new NSAlert()
                {
                    AlertStyle = NSAlertStyle.Warning,
                    InformativeText = "Do you want to exit the app?",
                    MessageText = "Exit?"
                };
                confirmation.AddButton("Yes");
                confirmation.AddButton("No");
                var result = confirmation.RunModal();

                if (result == 1001)
                {
                    this.closeApp = false;
                }
                else
                {
                    //terminate the app
                    this.closeApp = true;
                }
            }
        }

        public override bool ApplicationShouldTerminateAfterLastWindowClosed(NSApplication sender)
        {
            return closeApp;
        }

        public override void DidFinishLaunching(NSNotification notification)
        {
            Forms.Init();
            LoadApplication(new App());
            base.DidFinishLaunching(notification);
        }
    }
</code>```

Body:
I have a Xamarin.Forms application for iOS, Android, and now hopefully Mac.  I made all the adjustments for the UI to look great on Mac.  Submitted it for approval where it was rejected because the user can close the window while the app and menu bar is still running.  So I figure I would just add a confirmation pop-up asking if they want to exit the app when they try to close the window.

OK = Terminate the App.

Cancel = Keep the window open.

I find lots of articles on how to handle this with a Xamarin.Mac app, but nothing on how to handle Xamarin.Forms on Mac.  The FormsApplicationDelegate does not give access to the View Controller or the Window Delegate in order to override the WindowShouldClose method.  I found that I can use NSAlert to do the pop-up which works great.  Now I cannot find anything on what to do when the user responds. Open to suggestions.

 private void Window_WillClose(object sender, System.EventArgs e)
    {
        NSNotification senderNotification = ((NSNotification)sender);
        NSWindow closingWindow = (NSWindow)senderNotification.Object;

        var confirmation = new NSAlert()
        {
            AlertStyle = NSAlertStyle.Warning,
            InformativeText = "Are you sure you want to exit the App?",
            MessageText = "Exit?"
        };
        confirmation.AddButton("OK");
        confirmation.AddButton("Cancel");
        var result = confirmation.RunModal();

        if (result == 1001)
        {
            //Cancel closing the window
        }
        else
        {
            //terminate the app
        }

    }

Body:
After a lot of experimenting, I did find a solution.  Here is what officially passed Apple's review.  It requires that n menu action is linked as "New Window".  It keeps tracks of the open windows and when there is only one left, it prompts to close the app.  If the user closes all the windows and keeps the app running, they have the option to open a new window in the menu.

 [Register("AppDelegate")]
    public class AppDelegate : FormsApplicationDelegate
    {
        public NSWindow window;
        private bool closeApp;
        private List<NSWindow> openWindows;
        public override NSWindow MainWindow
        {
            get { return window; }
        }

        public AppDelegate()
        {
            this.closeApp = false;
            this.openWindows = new List<NSWindow>();
            createNewWindow();
        }

        [Action("newWindow:")]
        public void newWindow(NSObject sender)
        {

            createNewWindow();
            this.window.MakeKeyAndOrderFront(sender);
            LoadApplication(new App());
            base.DidFinishLaunching(null);

        }

        private void createNewWindow()
        {
            var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled;
            var rect = new CoreGraphics.CGRect(200, 1000, 1024, 768);
            window = new MainWindow(rect, style, NSBackingStore.Buffered, false);
            window.Title = "MyApp"; // choose your own Title here
            window.TitleVisibility = NSWindowTitleVisibility.Hidden;
            window.WillClose += Window_WillClose;
            openWindows.Add(window);
        }

        private void Window_WillClose(object sender, System.EventArgs e)
        {
            openWindows.Remove((NSWindow)((NSNotification)sender).Object);
            if (openWindows.Count == 0)
            {
                var confirmation = new NSAlert()
                {
                    AlertStyle = NSAlertStyle.Warning,
                    InformativeText = "Do you want to exit the app?",
                    MessageText = "Exit?"
                };
                confirmation.AddButton("Yes");
                confirmation.AddButton("No");
                var result = confirmation.RunModal();

                if (result == 1001)
                {
                    this.closeApp = false;
                }
                else
                {
                    //terminate the app
                    this.closeApp = true;
                }
            }
        }

        public override bool ApplicationShouldTerminateAfterLastWindowClosed(NSApplication sender)
        {
            return closeApp;
        }

        public override void DidFinishLaunching(NSNotification notification)
        {
            Forms.Init();
            LoadApplication(new App());
            base.DidFinishLaunching(notification);
        }
    }


问:
DllNotFoundException while using unity native c++ Plugins
Getting DllNotFoundException when trying to build a native c++ plugin for Unity.

FirstDll.cpp

```<code>#include "FirstDll.h"

  DLLExport int add(int a, int b){
      return a+b;
  }

  FirstDll::FirstDll(){
  }

   FirstDll::~FirstDll(){
 }
</code>```

FirstDll.h

```<code>#define DLLExport __declspec(dllexport)

   extern "C"{
       DLLExport int add(int a, int b);
   }

  class FirstDll{
  public:
       FirstDll();
      ~FirstDll();
 };
</code>```

I am then generating a so file via this command

```<code>g++ -dynamiclib -flat_namespace -fms-extensions FirstDll.cpp -o libmyclass.so
</code>```

I am then added this .so file in Assets/Plugins/x86_64 folder and in my unity c# code, I am trying to run this piece of code.

```<code>[DllImport("myclass")]
    static extern int add(int a, int b);
</code>```

After getting this error, I have tried to moved the so file to different locations and test. I am always getting DllNotFoundException.

答:
Try using the following clang command instead

```<code>clang *.cpp -O3 -dynamiclib -arch i386 -arch x86_64 -o libmyclass.bundle
</code>```

Then make sure to select the correct platform in Unity

Or you can check this simple plugin from Unity: SimplestPluginExample

Body:
Getting DllNotFoundException when trying to build a native c++ plugin for Unity.

FirstDll.cpp

#include "FirstDll.h"

  DLLExport int add(int a, int b){
      return a+b;
  }

  FirstDll::FirstDll(){
  }

   FirstDll::~FirstDll(){
 }

FirstDll.h

#define DLLExport __declspec(dllexport)

   extern "C"{
       DLLExport int add(int a, int b);
   }

  class FirstDll{
  public:
       FirstDll();
      ~FirstDll();
 };

I am then generating a so file via this command

g++ -dynamiclib -flat_namespace -fms-extensions FirstDll.cpp -o libmyclass.so

I am then added this .so file in Assets/Plugins/x86_64 folder and in my unity c# code, I am trying to run this piece of code.

[DllImport("myclass")]
    static extern int add(int a, int b);

After getting this error, I have tried to moved the so file to different locations and test. I am always getting DllNotFoundException.

Body:
Try using the following clang command instead

clang *.cpp -O3 -dynamiclib -arch i386 -arch x86_64 -o libmyclass.bundle

Then make sure to select the correct platform in Unity

Or you can check this simple plugin from Unity: SimplestPluginExample


问:
Is there any way to accept all the parameters as a single string?
For example,

Input:

```<code>echo( hello world
</code>```

Program:

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

int main(int n,char** args){
// Replace all the '\0' with ' '
system(args[1]);
return printf("\n");
}
</code>```

Output:

```<code>hello world

</code>```

Now I need hello world in a pointer.

I know that **char doesn't work the way I want it to..

But is there any efficient way out, instead of calculating the length of each argument, malloc-ing those many bytes and then concatenating it to the allocated memory?

Some access specifier for char** maybe?

I am trying to add echo( a command to DOSBox, so basically echo params and then print a newline. That's it.

Also, is there any way to exclude to recognize an exe without any spaces or is it console specific?

答:
I want a way to get all the arguments in a single pointer, a string that's terminated at the end.

Using either form of the main() function:

```<code>int main(int argc, char *argv[]) {...};
int main(int argc, char **argv) {...};
</code>```

which are equivalent signatures for the C main() function, will allow you to pass any number of arguments, each of any size.  If you want to pass a single string containing many arguments just pass a single string with some kind of delimiter.  If the delimiter is a space ( " " ), then by definition of the behavior of the C main() function command line argument requires surrounding them with ":

Say your exe name is prog.exe

```<code>prog this,is,one,argument
prog "this is one argument"  //double quotes provide cohesion between space delimited command line arguments
prog this-is-one-argument
</code>```

Will all be contained in a single variable:  argv[1]

If you compile this as echo.exe it will put to stdout any thing typed into stdin:

```<code>int main(int argc, char **argv)
{
  if(argv != 2) return 0;
  fputs(argv[1], stdout);
  return(0);
}
</code>```

Usage: echo "this will be echoed onto stdout"<return>

Usage: abc000<return>

Usage: this-is-one-argument<return>

Body:
For example,

Input:

echo( hello world

Program:

#include<stdio.h>

int main(int n,char** args){
// Replace all the '\0' with ' '
system(args[1]);
return printf("\n");
}

Output:

hello world

Now I need hello world in a pointer.

I know that **char doesn't work the way I want it to..

But is there any efficient way out, instead of calculating the length of each argument, malloc-ing those many bytes and then concatenating it to the allocated memory?

Some access specifier for char** maybe?

I am trying to add echo( a command to DOSBox, so basically echo params and then print a newline. That's it.

Also, is there any way to exclude to recognize an exe without any spaces or is it console specific?

Body:
I want a way to get all the arguments in a single pointer, a string that's terminated at the end.

Using either form of the main() function:

int main(int argc, char *argv[]) {...};
int main(int argc, char **argv) {...};

which are equivalent signatures for the C main() function, will allow you to pass any number of arguments, each of any size.  If you want to pass a single string containing many arguments just pass a single string with some kind of delimiter.  If the delimiter is a space ( " " ), then by definition of the behavior of the C main() function command line argument requires surrounding them with ":

Say your exe name is prog.exe

prog this,is,one,argument
prog "this is one argument"  //double quotes provide cohesion between space delimited command line arguments
prog this-is-one-argument

Will all be contained in a single variable:  argv[1]

If you compile this as echo.exe it will put to stdout any thing typed into stdin:

int main(int argc, char **argv)
{
  if(argv != 2) return 0;
  fputs(argv[1], stdout);
  return(0);
}

Usage: echo "this will be echoed onto stdout"<return>

Usage: abc000<return>

Usage: this-is-one-argument<return>


问:
How to test ECS autoscaling properly?
I have a ECS service that I have set up auto-scaling for. It is a service that has 2 Fargate tasks. The problem is the Docker containers' CPU utilization is usually very low, generally around 0.1%. I would like to test my auto-scaling set up, especially auto-scaling down which should happen when CPU utilization drops below a threshold. What is the best approach to test it?</p>

答: If your app exposes an HTTP API, you could use load testers such as hey or ab to generate load and hence trigger scaling.</p>

Title: How to test ECS autoscaling properly?


问:
result for variable not as expected
ok, this is my updated question because still the variable will be shown false in another function.

I changed now my code as Asperi proposed (thank you Asperi)...looks better now, but...

still in my function updatePivotForTextNode() the animationType is .none!?

Output debugger:

makeuiview flyThrough  // good

2020-02-20 14:30:00.287089+0100 EasyTest[3837:134164] Metal API Validation Enabled

dy= 7.3564453

update pivot none // not good

updateui flyThrough  // good

```<code>import SwiftUI
import SceneKit

class SceneTextView: SCNView {

    enum AnimationType {
        case none
        case wiggleHorizontal
        case flyThrough
    }

    var text: String {
        didSet {
            (textNode?.geometry as! SCNText).string = text
            updatePivotForTextNode()
        }
    }

    let cameraNode = SCNNode()

    var font : UIFont = UIFont(name: "Verdana", size: 12)!
    var color: UIColor = .orange
    var lightIntensity : CGFloat = 30000
    var cameraPosition : SCNVector3 = SCNVector3(2,0,40)
    var spotlightPosition : SCNVector3 = SCNVector3(6,2,25)
    var animationType : AnimationType = .none

    var textNode : SCNNode? = nil

    var justOnce = true

    var animatingAngle : CGFloat = 0

    override init(frame: CGRect, options: [String : Any]? = nil) {

        self.text = ""
        self.animatingAngle = CGFloat.pi * 2 / 30
        super.init(frame: frame, options: options)
    }

    init(frame: CGRect, animatingAngle: CGFloat = CGFloat.pi * 2 / 30,  options: [String : Any]? = nil) {

        self.text = ""
        self.animatingAngle = animatingAngle
        super.init(frame: frame, options: options)
    }

    func updatePivotForTextNode() {

        let boundingBox = textNode!.boundingBox

        let max = boundingBox.max
        let min = boundingBox.min
        let dx = min.x + 0.5 * (max.x - min.x)
        let dy = animationType == .flyThrough ? min.y + 0.5 * (max.y - min.y) * 2 : min.y + 0.5 * (max.y - min.y)
        // weird result here
        print("dy=",dy)
        print("update pivot", self.animationType)
        let dz = min.z + 0.5 * (max.z - min.z)

    }

    init(frame: CGRect, font: UIFont, color: UIColor, lightIntensity: CGFloat = 30000, lightPosition: SCNVector3 = SCNVector3(6,2,25), cameraPosition: SCNVector3 = SCNVector3(2,0,40), text: String, animationType: AnimationType = .none) {

        self.text = text
        super.init(frame: frame) // !! < here

        self.font = font
        self.color = color
        self.lightIntensity = lightIntensity
        self.spotlightPosition = lightPosition
        self.animationType = animationType

        backgroundColor = UIColor.clear

        scene = SCNScene()

        let textGeometry = SCNText(string: "Bla", extrusionDepth: 4)
        textGeometry.firstMaterial?.isDoubleSided = true
        textNode = SCNNode(geometry: textGeometry)
        scene?.rootNode.addChildNode(textNode!)

        updatePivotForTextNode()

    }

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

final class SceneTextViewWrapper : UIViewRepresentable {

    @State var animationType : SceneTextView.AnimationType

    init(animationType: SceneTextView.AnimationType ) {
        self.animationType = animationType
    }

    func makeUIView(context: Context) -> SceneTextView {
        print("makeuiview", animationType)
        return SceneTextView(frame: CGRect(x: 0, y: 0, width: 200, height: 200),
                             font: UIFont.boldSystemFont(ofSize: 3),
                             color: .blue,
                             lightIntensity: 8000,
                             lightPosition: SCNVector3(0,0,0),
                             cameraPosition: SCNVector3(0,0,22),
                             text: "Winner",
                             animationType: .flyThrough)
    }

    func updateUIView(_ uiView: SceneTextView, context: UIViewRepresentableContext<SceneTextViewWrapper>) {
        print("updateui", animationType)
    }
}

struct ContentView: View {

    @State var animate = true

    var body: some View {
        ZStack {
            Rectangle()
                .background(Color.black)
            SceneTextViewWrapper(animationType: .flyThrough)
                .onAppear() {

            }
        }.edgesIgnoringSafeArea(.all)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

答:
Just don't initialise it before init

```<code>final class SceneTextViewWrapper : UIViewRepresentable {

    @State var animationType : SceneTextView.AnimationType // << only declaration
</code>```

Title: result for variable not as expected

Body:
ok, this is my updated question because still the variable will be shown false in another function.

I changed now my code as Asperi proposed (thank you Asperi)...looks better now, but...

still in my function updatePivotForTextNode() the animationType is .none!?

Output debugger:

makeuiview flyThrough  // good

2020-02-20 14:30:00.287089+0100 EasyTest[3837:134164] Metal API Validation Enabled

dy= 7.3564453

update pivot none // not good

updateui flyThrough  // good

import SwiftUI
import SceneKit

class SceneTextView: SCNView {

    enum AnimationType {
        case none
        case wiggleHorizontal
        case flyThrough
    }

    var text: String {
        didSet {
            (textNode?.geometry as! SCNText).string = text
            updatePivotForTextNode()
        }
    }

    let cameraNode = SCNNode()

    var font : UIFont = UIFont(name: "Verdana", size: 12)!
    var color: UIColor = .orange
    var lightIntensity : CGFloat = 30000
    var cameraPosition : SCNVector3 = SCNVector3(2,0,40)
    var spotlightPosition : SCNVector3 = SCNVector3(6,2,25)
    var animationType : AnimationType = .none

    var textNode : SCNNode? = nil

    var justOnce = true

    var animatingAngle : CGFloat = 0

    override init(frame: CGRect, options: [String : Any]? = nil) {

        self.text = ""
        self.animatingAngle = CGFloat.pi * 2 / 30
        super.init(frame: frame, options: options)
    }

    init(frame: CGRect, animatingAngle: CGFloat = CGFloat.pi * 2 / 30,  options: [String : Any]? = nil) {

        self.text = ""
        self.animatingAngle = animatingAngle
        super.init(frame: frame, options: options)
    }

    func updatePivotForTextNode() {

        let boundingBox = textNode!.boundingBox

        let max = boundingBox.max
        let min = boundingBox.min
        let dx = min.x + 0.5 * (max.x - min.x)
        let dy = animationType == .flyThrough ? min.y + 0.5 * (max.y - min.y) * 2 : min.y + 0.5 * (max.y - min.y)
        // weird result here
        print("dy=",dy)
        print("update pivot", self.animationType)
        let dz = min.z + 0.5 * (max.z - min.z)

    }

    init(frame: CGRect, font: UIFont, color: UIColor, lightIntensity: CGFloat = 30000, lightPosition: SCNVector3 = SCNVector3(6,2,25), cameraPosition: SCNVector3 = SCNVector3(2,0,40), text: String, animationType: AnimationType = .none) {

        self.text = text
        super.init(frame: frame) // !! < here

        self.font = font
        self.color = color
        self.lightIntensity = lightIntensity
        self.spotlightPosition = lightPosition
        self.animationType = animationType

        backgroundColor = UIColor.clear

        scene = SCNScene()

        let textGeometry = SCNText(string: "Bla", extrusionDepth: 4)
        textGeometry.firstMaterial?.isDoubleSided = true
        textNode = SCNNode(geometry: textGeometry)
        scene?.rootNode.addChildNode(textNode!)

        updatePivotForTextNode()

    }

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

final class SceneTextViewWrapper : UIViewRepresentable {

    @State var animationType : SceneTextView.AnimationType

    init(animationType: SceneTextView.AnimationType ) {
        self.animationType = animationType
    }

    func makeUIView(context: Context) -> SceneTextView {
        print("makeuiview", animationType)
        return SceneTextView(frame: CGRect(x: 0, y: 0, width: 200, height: 200),
                             font: UIFont.boldSystemFont(ofSize: 3),
                             color: .blue,
                             lightIntensity: 8000,
                             lightPosition: SCNVector3(0,0,0),
                             cameraPosition: SCNVector3(0,0,22),
                             text: "Winner",
                             animationType: .flyThrough)
    }

    func updateUIView(_ uiView: SceneTextView, context: UIViewRepresentableContext<SceneTextViewWrapper>) {
        print("updateui", animationType)
    }
}

struct ContentView: View {

    @State var animate = true

    var body: some View {
        ZStack {
            Rectangle()
                .background(Color.black)
            SceneTextViewWrapper(animationType: .flyThrough)
                .onAppear() {

            }
        }.edgesIgnoringSafeArea(.all)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Body:
Just don't initialise it before init

final class SceneTextViewWrapper : UIViewRepresentable {

    @State var animationType : SceneTextView.AnimationType // << only declaration


问:
Handling overlap of divs
I want the inner part of the red circle to be white while overlapping with the blue circle and transparent for the rest so that you can see the green color.

I would be happy if someone knows how to handle this.

#bigCircle {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 380px;
    height: 380px;
    border-radius: 50%;
    background-color: rgba(11, 122, 30, 0.8);
}

#middleCircle {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 240px;
    height: 240px;
    border-radius: 50%;
    background-color: rgba(0,0,250,0.5);
}

.smallCircle {
    margin-top: -244px;
    margin-left: 1px;
    border: solid rgb(226, 85, 20);
    width: 13px;
    height: 13px;
    border-radius: 50%;
    background-color:rgba(255,255,255,0);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div id="bigCircle">
                <div id="middleCircle">
                    <div class="smallCircle" />
                </div>
        </div ></code>```

答:
#bigCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 380px;
  height: 380px;
  border-radius: 50%;
  background-color: rgba(11, 122, 30, 0.8);
}

#middleCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 240px;
  height: 240px;
  border-radius: 50%;
  background-color: rgba(0, 0, 250, 0.5);
}

.smallCircle {
  margin-top: -242px;
  margin-left: 1px;
  border: solid rgb(226, 85, 20) 3px;
  width: 13px;
  height: 13px;
  border-radius: 50%;
  position: relative;
}

.smallCircle:after {
  display: block;
  content: '';
  border: solid rgb(226, 85, 20) 3px;
  width: 13px;
  height: 13px;
  border-radius: 50%;
  clip-path: circle(120px at 50% 130px);
  background-color: rgb(255, 255, 255);
  position: absolute;
  top: -3px;
  left: -3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bigCircle">
  <div id="middleCircle">
    <div class="smallCircle">
    </div>
  </div>
</div></code>```

Title: Handling overlap of divs

Body:
#bigCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 380px;
  height: 380px;
  border-radius: 50%;
  background-color: rgba(11, 122, 30, 0.8);
}

#middleCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 240px;
  height: 240px;
  border-radius: 50%;
  background-color: rgba(0, 0, 250, 0.5);
}

.smallCircle {
  margin-top: -242px;
  margin-left: 1px;
  border: solid rgb(226, 85, 20) 3px;
  width: 13px;
  height: 13px;
  border-radius: 50%;
  position: relative;
}

.smallCircle:after {
  display: block;
  content: '';
  border: solid rgb(226, 85, 20) 3px;
  width: 13px;
  height: 13px;
  border-radius: 50%;
  clip-path: circle(120px at 50% 130px);
  background-color: rgb(255, 255, 255);
  position: absolute;
  top: -3px;
  left: -3px;
}

<div id="bigCircle">
  <div id="middleCircle">
    <div class="smallCircle">
    </div>
  </div>
</div>


问:
Can i substract 2 column given some conditions pandas
I have a df that looks like this

I want to subtract  EndTime - StartTime only if channel is 1000
smth like this: df.loc[df['Channel'] == 1000]['X channel view time']=df['EndTime']-df['StartTime']
this should be the fastest but does not appear to be working so

```<code>def watch_time(row,channel):
    val=0
    if row['Channel']==channel:
        val=row['EndTime']-row['StartTime']

    return val
df['BTV_view_time'] = df.apply(watch_time,args=250,axis=1)
</code>```

but this is a lot slower?

答:
notice you are taking a slice of the df, that's why it is not working, you can do something like this:

smaller_df =  df[df['Channel'] == 1000]['EndTime']-df[df['Channel'] == 1000]['StartTime']

you can also create a new column:

```<code>df['subtraction'] = [0]*len(df)
df['subtraction'] = df[df['Channel'] == 1000]['EndTime']-df[df['Channel'] == 1000]['StartTime']

</code>```

replace [0]*len(df) by what you want if 'Channel' is different of 1000

Body:
I have a df that looks like this

I want to subtract  EndTime - StartTime only if channel is 1000
smth like this: df.loc[df['Channel'] == 1000]['X channel view time']=df['EndTime']-df['StartTime']
this should be the fastest but does not appear to be working so

def watch_time(row,channel):
    val=0
    if row['Channel']==channel:
        val=row['EndTime']-row['StartTime']

    return val
df['BTV_view_time'] = df.apply(watch_time,args=250,axis=1)

but this is a lot slower?

Body:
notice you are taking a slice of the df, that's why it is not working, you can do something like this:

smaller_df =  df[df['Channel'] == 1000]['EndTime']-df[df['Channel'] == 1000]['StartTime']

you can also create a new column:

df['subtraction'] = [0]*len(df)
df['subtraction'] = df[df['Channel'] == 1000]['EndTime']-df[df['Channel'] == 1000]['StartTime']

replace [0]*len(df) by what you want if 'Channel' is different of 1000


问:
Is it possible to compile C# into IL and decompile the resulting IL into F#?
C# compiles into IL which is then easy to decompile back to C# using ILSpy or dotPeek.

Is there any tool that allows that same IL to be decompiled into F#?

i.e. is there a sneaky way to translate C# into F#, via IL?

RATIONALE:

We have a very large C# project and want to "go functional".

Translation is a massive job.

If a first-pass translation can be automated, we can improve it by hand after

i.e. would this be faster than writing everything from scratch in F#.

We are not yet experienced in F# hence the possible naivety of this question.

FURTHER NOTE
Yes, we are using the functional stuff in C# but for various reasons we want to go fully functional with F#.  That choice isn't up for debate here but thanks for the comments on this.

答:
Idiomatic F# code uses different types, approaches and structure. There isn't much to gain from "decompiling" C#-generated IL to F#, especially when you consider that you can interface with C# code quite easily. To make things worse, decompiling anything makes you lose lots of information - names of locals, constants, comments all sort of mangling. It's not impossible, but you're wasting lots of effort rebuilding something that is an intermediate step anyway.

Break your C# code into parts that you can slowly replace with F# code. This way, you have a chance of producing good F# code, and incrementally replace everything as needed. Do not start writing anything from scratch - keep as much of the old code as possible, and only change what needs to be changed to improve the interfacing with the F# code.

C# is already quite a "functional-capable" language - not quite as neat and expressive as F#, but there's very few things you can do in F# but not in C# in a reasonably simple way. This means incrementally changing over to functional style isn't as difficult as it might sound - and it's work you can't avoid anyway, if your goal is (for some reason; I hope you have an actual goal as well, and this is just an intermediate step :) functional code.


答:
here's a for-loop answer.

```<code>df_final <- data.table()
for(i in seq(24)){
  if(i %in% df[,hour]){
    a <- df[hour==i]
  }else{
    a <- data.table(customer="x", hour=i, visits=0)}

  df_final <- rbind(df_final, a)
}
df_final
</code>```

You can wrap this in another for-loop to have your multiple customers x, y, etc. (the following loop isnt very clean but gets the job done).

```<code>df_final <- data.table()

for(j in unique(df[,customer])){

  for(i in seq(24)){

    if(i %in% df[,hour]){
      if(df[hour==i,customer] %in% j){
        a <- df[hour==i]
      }else{
        a <- data.table(customer=j, hour=i, visits=0)
      }
    }else{
      a <- data.table(customer=j, hour=i, visits=0)
    }

    df_final <- rbind(df_final, a)
  }
}

df_final
</code>```

Title: how to insert sequential rows in data.table in R (Example given)?

Body:
df is data.table and df_expected is desired data.table . I want to add hour column from 0 to 23 and visits value would be filled as 0 for hours newly added .

df<-data.table(customer=c("x","x","x","y","y"),location_id=c(1,1,1,2,3),hour=c(2,5,7,0,4),visits=c(40,50,60,70,80))

df_expected<-data.table(customer=c("x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x",
                               "y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y",
                               "y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y"),

                    location_id=c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
                                  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                                  3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3),

                    hour=c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,
                           0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,
                           0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23),

                    visits=c(0,0,40,0,0,50,0,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                             70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                             0,0,0,0,80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))

This is what I tried to obtain my result , but it did not work

df1<-df[,':='(hour=seq(0:23)),by=(customer)]
Error in `[.data.table`(df, , `:=`(hour = seq(0L:23L)), by = (customer)) :
Type of RHS ('integer') must match LHS ('double'). To check and coerce would impact
performance too much for the fastest cases. Either change the type of the target column, or
coerce the RHS of := yourself (e.g. by using 1L instead of 1)

Body:
here's a for-loop answer.

df_final <- data.table()
for(i in seq(24)){
  if(i %in% df[,hour]){
    a <- df[hour==i]
  }else{
    a <- data.table(customer="x", hour=i, visits=0)}

  df_final <- rbind(df_final, a)
}
df_final

You can wrap this in another for-loop to have your multiple customers x, y, etc. (the following loop isnt very clean but gets the job done).

df_final <- data.table()

for(j in unique(df[,customer])){

  for(i in seq(24)){

    if(i %in% df[,hour]){
      if(df[hour==i,customer] %in% j){
        a <- df[hour==i]
      }else{
        a <- data.table(customer=j, hour=i, visits=0)
      }
    }else{
      a <- data.table(customer=j, hour=i, visits=0)
    }

    df_final <- rbind(df_final, a)
  }
}

df_final


问:
Error when Styling a combo box with multiple triggers
I have a combo box to which I am trying to add some styles hence inside my Combobox. Style I am trying to set triggers for two properties but it seems like it doesn't allow me to set both properties at once. The code I am having trouble is below

The error displayed says Property elements cannot be in the middle of an element's content. They must be before or after the content

```<code><ComboBox.Style>
    <Style TargetType="{x:Type ComboBox}">
        <Setter Property="Foreground" Value="..." />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="..." />
            </Trigger>
        </Style.Triggers>

        <Setter Property="IsEnabled" Value="False" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsExecuting}" Value="False">
                <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.Style>
</code>```

Am I writing syntactically wrong XAML here? would appreciate some help here

答:
This compiles for me:

```<code><ComboBox.Style>
    <Style TargetType="{x:Type ComboBox}">
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="IsEnabled" Value="False" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="Blue" />
            </Trigger>
            <DataTrigger Binding="{Binding Path=IsExecuting}" Value="False">
                <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.Style>
</code>```

All I did was made sure there is only one Style.Triggers

Body:
I have a combo box to which I am trying to add some styles hence inside my Combobox. Style I am trying to set triggers for two properties but it seems like it doesn't allow me to set both properties at once. The code I am having trouble is below

The error displayed says Property elements cannot be in the middle of an element's content. They must be before or after the content

<ComboBox.Style>

        <Setter Property="IsEnabled" Value="False" />

    </Style>
</ComboBox.Style>

Am I writing syntactically wrong XAML here? would appreciate some help here

Body:
This compiles for me:

<ComboBox.Style>
    <Style TargetType="{x:Type ComboBox}">
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="IsEnabled" Value="False" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="Blue" />
            </Trigger>
            <DataTrigger Binding="{Binding Path=IsExecuting}" Value="False">
                <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.Style>

All I did was made sure there is only one Style.Triggers


问:
woocommerce add custom post type to cart
I'm using woocommerce and i created a custom post type that has to be treated as a product and user may add to cart. I followed this tutorial
http://reigelgallarde.me/programming/how-to-add-custom-post-type-to-woocommerce/
and made sure my price field meta key is “_price”
but it didn't work.

when I tried to add this code to functions.php

```<code>function reigel_woocommerce_get_price($price = null,$post = null){
if ($post->post->post_type === 'aytam'){
    $price = get_post_meta($post->id, "_price", true);
    }

return $price;
}
add_filter('woocommerce_get_price','reigel_woocommerce_get_price',20,1);
add_action( 'init', 'reigel_woocommerce_get_price' );
</code>```

didn't work either

答:
been tackling with this and since the above code didn't work, I went ahead and made a working version. Note that this code works with Woocommerce 3.6.2 (at least) and is intended to make it work with custom post type industry-ad , but you can change to what you desire

```<code>class IA_Woo_Product extends WC_Product  {

    protected $post_type = 'industry-ad';

    public function get_type() {
        return 'industry-ad';
    }

    public function __construct( $product = 0 ) {
        $this->supports[]   = 'ajax_add_to_cart';

        parent::__construct( $product );

    }
    // maybe overwrite other functions from WC_Product

}

class IA_Data_Store_CPT extends WC_Product_Data_Store_CPT {

    public function read( &$product ) { // this is required
        $product->set_defaults();
        $post_object = get_post( $product->get_id() );

        if ( ! $product->get_id() || ! $post_object || 'industry-ad' !== $post_object->post_type ) {

            throw new Exception( __( 'Invalid product.', 'woocommerce' ) );
        }

        $product->set_props(
            array(
                'name'              => $post_object->post_title,
                'slug'              => $post_object->post_name,
                'date_created'      => 0 < $post_object->post_date_gmt ? wc_string_to_timestamp( $post_object->post_date_gmt ) : null,
                'date_modified'     => 0 < $post_object->post_modified_gmt ? wc_string_to_timestamp( $post_object->post_modified_gmt ) : null,
                'status'            => $post_object->post_status,
                'description'       => $post_object->post_content,
                'short_description' => $post_object->post_excerpt,
                'parent_id'         => $post_object->post_parent,
                'menu_order'        => $post_object->menu_order,
                'reviews_allowed'   => 'open' === $post_object->comment_status,
            )
        );

        $this->read_attributes( $product );
        $this->read_downloads( $product );
        $this->read_visibility( $product );
        $this->read_product_data( $product );
        $this->read_extra_data( $product );
        $product->set_object_read( true );
    }

    // maybe overwrite other functions from WC_Product_Data_Store_CPT

}

class IA_WC_Order_Item_Product extends WC_Order_Item_Product {
    public function set_product_id( $value ) {
        if ( $value > 0 && 'industry-ad' !== get_post_type( absint( $value ) ) ) {
            $this->error( 'order_item_product_invalid_product_id', __( 'Invalid product ID', 'woocommerce' ) );
        }
        $this->set_prop( 'product_id', absint( $value ) );
    }

}

function IA_woocommerce_data_stores( $stores ) {
    // the search is made for product-$post_type so note the required 'product-' in key name
    $stores['product-industry-ad'] = 'IA_Data_Store_CPT';
    return $stores;
}
add_filter( 'woocommerce_data_stores', 'IA_woocommerce_data_stores' , 11, 1 );

function IA_woo_product_class( $class_name ,  $product_type ,  $product_id ) {
    if ($product_type == 'industry-ad')
        $class_name = 'IA_Woo_Product';
    return $class_name;
}
add_filter('woocommerce_product_class','IA_woo_product_class',25,3 );

function my_woocommerce_product_get_price( $price, $product ) {

    if ($product->get_type() == 'industry-ad' ) {
        $price = 10;  // or get price how ever you see fit
    }
    return $price;
}
add_filter('woocommerce_get_price','my_woocommerce_product_get_price',20,2);
add_filter('woocommerce_product_get_price', 'my_woocommerce_product_get_price', 10, 2 );

// required function for allowing posty_type to be added; maybe not the best but it works
function IA_woo_product_type($false,$product_id) {
    if ($false === false) { // don't know why, but this is how woo does it
        global $post;
        // maybe redo it someday?!
        if (is_object($post) && !empty($post)) { // post is set
            if ($post->post_type == 'industry-ad' && $post->ID == $product_id)
                return 'industry-ad';
            else {
                $product = get_post( $product_id );
                if (is_object($product) && !is_wp_error($product)) { // post not set but it's a industry-ad
                    if ($product->post_type == 'industry-ad')
                        return 'industry-ad';
                } // end if
            }

        } else if(wp_doing_ajax()) { // has post set (usefull when adding using ajax)
            $product_post = get_post( $product_id );
            if ($product_post->post_type == 'industry-ad')
                return 'industry-ad';
        } else {
            $product = get_post( $product_id );
            if (is_object($product) && !is_wp_error($product)) { // post not set but it's a industry-ad
                if ($product->post_type == 'industry-ad')
                    return 'industry-ad';
            } // end if

        } // end if  // end if

    } // end if
    return false;
}
add_filter('woocommerce_product_type_query','IA_woo_product_type',12,2 );

function IA_woocommerce_checkout_create_order_line_item_object($item, $cart_item_key, $values, $order) {

    $product                    = $values['data'];
    if ($product->get_type() == 'industry-ad') {
        return new IA_WC_Order_Item_Product();
    } // end if
    return $item ;
}
add_filter( 'woocommerce_checkout_create_order_line_item_object', 'IA_woocommerce_checkout_create_order_line_item_object', 20, 4 );

function cod_woocommerce_checkout_create_order_line_item($item,$cart_item_key,$values,$order) {
    if ($values['data']->get_type() == 'industry-ad') {
        $item->update_meta_data( '_industry-ad', 'yes' ); // add a way to recognize custom post type in ordered items
        return;
    } // end if

}
add_action( 'woocommerce_checkout_create_order_line_item', 'cod_woocommerce_checkout_create_order_line_item', 20, 4 );

function IA_woocommerce_get_order_item_classname($classname, $item_type, $id) {
    global $wpdb;
    $is_IA = $wpdb->get_var("SELECT meta_value FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id = {$id} AND meta_key = '_industry-ad'");

    if ('yes' === $is_IA) { // load the new class if the item is our custom post
        $classname = 'IA_WC_Order_Item_Product';
    } // end if
    return $classname;
}
add_filter( 'woocommerce_get_order_item_classname', 'IA_woocommerce_get_order_item_classname', 20, 3 );
</code>```

Body:
I'm using woocommerce and i created a custom post type that has to be treated as a product and user may add to cart. I followed this tutorial
http://reigelgallarde.me/programming/how-to-add-custom-post-type-to-woocommerce/
and made sure my price field meta key is “_price”
but it didn't work.

when I tried to add this code to functions.php

function reigel_woocommerce_get_price($price = null,$post = null){
if ($post->post->post_type === 'aytam'){
    $price = get_post_meta($post->id, "_price", true);
    }

return $price;
}
add_filter('woocommerce_get_price','reigel_woocommerce_get_price',20,1);
add_action( 'init', 'reigel_woocommerce_get_price' );

didn't work either

Body:
been tackling with this and since the above code didn't work, I went ahead and made a working version. Note that this code works with Woocommerce 3.6.2 (at least) and is intended to make it work with custom post type industry-ad , but you can change to what you desire

class IA_Woo_Product extends WC_Product  {

    protected $post_type = 'industry-ad';

    public function get_type() {
        return 'industry-ad';
    }

    public function __construct( $product = 0 ) {
        $this->supports[]   = 'ajax_add_to_cart';

        parent::__construct( $product );

    }
    // maybe overwrite other functions from WC_Product

}

class IA_Data_Store_CPT extends WC_Product_Data_Store_CPT {

    public function read( &$product ) { // this is required
        $product->set_defaults();
        $post_object = get_post( $product->get_id() );

        if ( ! $product->get_id() || ! $post_object || 'industry-ad' !== $post_object->post_type ) {

            throw new Exception( __( 'Invalid product.', 'woocommerce' ) );
        }

        $product->set_props(
            array(
                'name'              => $post_object->post_title,
                'slug'              => $post_object->post_name,
                'date_created'      => 0 < $post_object->post_date_gmt ? wc_string_to_timestamp( $post_object->post_date_gmt ) : null,
                'date_modified'     => 0 < $post_object->post_modified_gmt ? wc_string_to_timestamp( $post_object->post_modified_gmt ) : null,
                'status'            => $post_object->post_status,
                'description'       => $post_object->post_content,
                'short_description' => $post_object->post_excerpt,
                'parent_id'         => $post_object->post_parent,
                'menu_order'        => $post_object->menu_order,
                'reviews_allowed'   => 'open' === $post_object->comment_status,
            )
        );

        $this->read_attributes( $product );
        $this->read_downloads( $product );
        $this->read_visibility( $product );
        $this->read_product_data( $product );
        $this->read_extra_data( $product );
        $product->set_object_read( true );
    }

    // maybe overwrite other functions from WC_Product_Data_Store_CPT

}

class IA_WC_Order_Item_Product extends WC_Order_Item_Product {
    public function set_product_id( $value ) {
        if ( $value > 0 && 'industry-ad' !== get_post_type( absint( $value ) ) ) {
            $this->error( 'order_item_product_invalid_product_id', __( 'Invalid product ID', 'woocommerce' ) );
        }
        $this->set_prop( 'product_id', absint( $value ) );
    }

}

function IA_woocommerce_data_stores( $stores ) {
    // the search is made for product-$post_type so note the required 'product-' in key name
    $stores['product-industry-ad'] = 'IA_Data_Store_CPT';
    return $stores;
}
add_filter( 'woocommerce_data_stores', 'IA_woocommerce_data_stores' , 11, 1 );

function IA_woo_product_class( $class_name ,  $product_type ,  $product_id ) {
    if ($product_type == 'industry-ad')
        $class_name = 'IA_Woo_Product';
    return $class_name;
}
add_filter('woocommerce_product_class','IA_woo_product_class',25,3 );

function my_woocommerce_product_get_price( $price, $product ) {

    if ($product->get_type() == 'industry-ad' ) {
        $price = 10;  // or get price how ever you see fit
    }
    return $price;
}
add_filter('woocommerce_get_price','my_woocommerce_product_get_price',20,2);
add_filter('woocommerce_product_get_price', 'my_woocommerce_product_get_price', 10, 2 );

// required function for allowing posty_type to be added; maybe not the best but it works
function IA_woo_product_type($false,$product_id) {
    if ($false === false) { // don't know why, but this is how woo does it
        global $post;
        // maybe redo it someday?!
        if (is_object($post) && !empty($post)) { // post is set
            if ($post->post_type == 'industry-ad' && $post->ID == $product_id)
                return 'industry-ad';
            else {
                $product = get_post( $product_id );
                if (is_object($product) && !is_wp_error($product)) { // post not set but it's a industry-ad
                    if ($product->post_type == 'industry-ad')
                        return 'industry-ad';
                } // end if
            }

        } else if(wp_doing_ajax()) { // has post set (usefull when adding using ajax)
            $product_post = get_post( $product_id );
            if ($product_post->post_type == 'industry-ad')
                return 'industry-ad';
        } else {
            $product = get_post( $product_id );
            if (is_object($product) && !is_wp_error($product)) { // post not set but it's a industry-ad
                if ($product->post_type == 'industry-ad')
                    return 'industry-ad';
            } // end if

        } // end if  // end if

    } // end if
    return false;
}
add_filter('woocommerce_product_type_query','IA_woo_product_type',12,2 );

function IA_woocommerce_checkout_create_order_line_item_object($item, $cart_item_key, $values, $order) {

    $product                    = $values['data'];
    if ($product->get_type() == 'industry-ad') {
        return new IA_WC_Order_Item_Product();
    } // end if
    return $item ;
}
add_filter( 'woocommerce_checkout_create_order_line_item_object', 'IA_woocommerce_checkout_create_order_line_item_object', 20, 4 );

function cod_woocommerce_checkout_create_order_line_item($item,$cart_item_key,$values,$order) {
    if ($values['data']->get_type() == 'industry-ad') {
        $item->update_meta_data( '_industry-ad', 'yes' ); // add a way to recognize custom post type in ordered items
        return;
    } // end if

}
add_action( 'woocommerce_checkout_create_order_line_item', 'cod_woocommerce_checkout_create_order_line_item', 20, 4 );

function IA_woocommerce_get_order_item_classname($classname, $item_type, $id) {
    global $wpdb;
    $is_IA = $wpdb->get_var("SELECT meta_value FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id = {$id} AND meta_key = '_industry-ad'");

    if ('yes' === $is_IA) { // load the new class if the item is our custom post
        $classname = 'IA_WC_Order_Item_Product';
    } // end if
    return $classname;
}
add_filter( 'woocommerce_get_order_item_classname', 'IA_woocommerce_get_order_item_classname', 20, 3 );


问:
NameError: name '*' is not defined
Why this line add(root, sum, 0) gets NameError: name 'add' is not defined error?

```<code>class Solution:
    def rob(root: TreeNode) -> int:
        sum = [0, 0]
        add(root, sum, 0)
        if sum[0] < sum[1]:
            return sum[1]
        else:
            return sum[0]

    def add(node: TreeNode, sum: List[int], index: int):
        if not node:
            return
        sum[index] += node.val
        index += 1
        if index >= len(sum):
            index = 0;
        add(node.left, sum, index)
        add(node.right, sum, index)
</code>```

答:
they are class functions, make use of self

Define like this:
def add(self, node: TreeNode, sum: List[int], index: int):

and use it

self.add(node.left, sum, index)

Title: NameError: name '*' is not defined

Body:
Why this line add(root, sum, 0) gets NameError: name 'add' is not defined error?

class Solution:
    def rob(root: TreeNode) -> int:
        sum = [0, 0]
        add(root, sum, 0)
        if sum[0] < sum[1]:
            return sum[1]
        else:
            return sum[0]

    def add(node: TreeNode, sum: List[int], index: int):
        if not node:
            return
        sum[index] += node.val
        index += 1
        if index >= len(sum):
            index = 0;
        add(node.left, sum, index)
        add(node.right, sum, index)


问:
Initializing a 2D array of pointer of type double through double pointer with structure
I am doing something like following;

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

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm->arr = (double **)malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = (double *)malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));

   return 0;
}
</code>```

It is giving me seg fault error. Please tell me how can I define a 2D array through double-pointer method with structure just like I am trying to do in above code?

答:
Either you do this :

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

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication comm;
    comm.arr = malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm.arr[i] = malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm.arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm.arr[i]+j));

   return 0;
}
</code>```

Or this :

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

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm = malloc(sizeof(communication));
    comm->arr = malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));

   return 0;
}
</code>```

Body:
I am doing something like following;

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm->arr = (double **)malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = (double *)malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));

   return 0;
}

It is giving me seg fault error. Please tell me how can I define a 2D array through double-pointer method with structure just like I am trying to do in above code?

Body:
Either you do this :

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication comm;
    comm.arr = malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm.arr[i] = malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm.arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm.arr[i]+j));

   return 0;
}

Or this :

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm = malloc(sizeof(communication));
    comm->arr = malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));

   return 0;
}


答:
In Google Sheets you could use an Array formula. I got this:

The formula I've used:

```<code>=ArrayFormula(CONCATENATE(IF(--(C2:G2<>"")*COLUMN($C$1:$G$1)<>0;$C$1:$G$1&" "&C2:G2;"")))
</code>```

This is how it works:

(--(C2:G2<>"") will return an array of 0 and 1 if the cell is blank or not

COLUMN($C$1:$G$1) will return an array of column numbers of each cell

(C2:G2<>"")*COLUMN($C$1:$G$1) we multiply both arrays, so we will get an array of column numbers of non blank cells and 0 of blank cells

<>0;$C$1:$G$1&" "&C2:G2;"") We check if each number in the array obtained in step 3 is 0 or not. If it's 0, it returns a null value, if not, it returns the value of cell

CONCATENATE will concatenate all values from previous array (step 4) so we concatenate null values with real values of non blank cells.

Not sure if this will make the sheet load slower if you have too many records.

Hope this helps

Title: How to collect data and headers for non blank cells in a row in Sheets

Body:
I cannot find a solution to my problem:

I have a sheet with ~290 rows and ~80 columns. The first row and column are fixed/header.

I would like to collect non-blank values and their header into column B.

I've tried to search for solutions, but I'm not as good at excel, so I cannot wrap my head around most of the advice that I've found.

Body:
In Google Sheets you could use an Array formula. I got this:

The formula I've used:

=ArrayFormula(CONCATENATE(IF(--(C2:G2<>"")*COLUMN($C$1:$G$1)<>0;$C$1:$G$1&" "&C2:G2;"")))

This is how it works:

(--(C2:G2<>"") will return an array of 0 and 1 if the cell is blank or not

COLUMN($C$1:$G$1) will return an array of column numbers of each cell

(C2:G2<>"")*COLUMN($C$1:$G$1) we multiply both arrays, so we will get an array of column numbers of non blank cells and 0 of blank cells

<>0;$C$1:$G$1&" "&C2:G2;"") We check if each number in the array obtained in step 3 is 0 or not. If it's 0, it returns a null value, if not, it returns the value of cell

CONCATENATE will concatenate all values from previous array (step 4) so we concatenate null values with real values of non blank cells.

Not sure if this will make the sheet load slower if you have too many records.

Hope this helps


问:
How to group and aggregate in pandas
I have df like this.
this value is projected values so that many columns exist.

```<code>Customer seg value0  value1
A         a   10      60
A         b   20      50
A         c   30      40
B         a   40      30
B         b   50      20
B         c   60      10
</code>```

I would like to calculate value by referring to seg columns.

a-b-c ( a minus b minus c)

in each customers

```<code>customer value0 value1
A        -40     -30
B        -70      0
</code>```

How can I calculate each values by grouping customers.

df.groupby(customer)

Thanks

答:
How about this:

```<code>In [42]: df
Out[42]:
  Customer seg  value0  value1
0        A   a      10      60
1        A   b      20      50
2        A   c      30      40
3        B   a      40      30
4        B   b      50      20
5        B   c      60      10

In [43]: df.pivot('seg', 'Customer').T.eval('a - b - c').unstack(level=0)
Out[43]:
          value0  value1
Customer
A            -40     -30
B            -70       0
</code>```

If you prefer groupby, there is another solution:

```<code>In [44]: df.groupby('Customer').apply(lambda x:
            x.set_index('seg')[['value0', 'value1']].T.eval('a - b - c'))
</code>```

Title: How to group and aggregate in pandas

Body:
I have df like this.
this value is projected values so that many columns exist.

Customer seg value0  value1
A         a   10      60
A         b   20      50
A         c   30      40
B         a   40      30
B         b   50      20
B         c   60      10

I would like to calculate value by referring to seg columns.

a-b-c ( a minus b minus c)

in each customers

customer value0 value1
A        -40     -30
B        -70      0

How can I calculate each values by grouping customers.

df.groupby(customer)

Thanks

Body:
How about this:

In [42]: df
Out[42]:
  Customer seg  value0  value1
0        A   a      10      60
1        A   b      20      50
2        A   c      30      40
3        B   a      40      30
4        B   b      50      20
5        B   c      60      10

In [43]: df.pivot('seg', 'Customer').T.eval('a - b - c').unstack(level=0)
Out[43]:
          value0  value1
Customer
A            -40     -30
B            -70       0

If you prefer groupby, there is another solution:

In [44]: df.groupby('Customer').apply(lambda x:
            x.set_index('seg')[['value0', 'value1']].T.eval('a - b - c'))


问:
Can Someone tell me how to put a .text file in to a dictionary containing a number and a string with python
I am making a project about a contact saver but I am not able to read a single contact in the code...
Please help me...
I am giving the code and the problem
If you can please provide me with the whole part of finding the single user or all the related users...
Thanks...

```<code>what = input("Do you want to read a single contact(y, n): ")
if what == 'y':
    who = input("Please Enter the name: ")
    a = open('contacts.txt', 'a')
    for line in a:
        k, v = line.strip().split('=')
        users[k.strip()] = v.strip()
        a.close()

    for i in users:
        if who.lower() == i.lower() or i.startswith(who[:3]):
            print(i)
</code>```

and this is the error:
'

Traceback (most recent call last):
  File "C:/Users/Teerth Jain/Desktop/teerth_made_projects/contacts.py", line 18, in
    for line in a:
io.UnsupportedOperation: not readable enter code here

'

答:
You've opened the file in a writing mode as opposed to a reading mode, use "r" instead of "a" (which is append to file)

```<code>a = open('contacts.txt', 'r')
</code>```

Also, not sure if you've included your question's indentation correctly, but the a.close() should be outside the for loop

As noted in the comments, using with is preferred over explicitly closing the file.

```<code>with open('contacts.txt', "r") as a:
    for line in a:
        k, v = line.strip().split('=')
        users[k.strip()] = v.strip()
</code>```

Body:
I am making a project about a contact saver but I am not able to read a single contact in the code...
Please help me...
I am giving the code and the problem
If you can please provide me with the whole part of finding the single user or all the related users...
Thanks...

what = input("Do you want to read a single contact(y, n): ")
if what == 'y':
    who = input("Please Enter the name: ")
    a = open('contacts.txt', 'a')
    for line in a:
        k, v = line.strip().split('=')
        users[k.strip()] = v.strip()
        a.close()

    for i in users:
        if who.lower() == i.lower() or i.startswith(who[:3]):
            print(i)

and this is the error:
'

Traceback (most recent call last):
  File "C:/Users/Teerth Jain/Desktop/teerth_made_projects/contacts.py", line 18, in
    for line in a:
io.UnsupportedOperation: not readable enter code here

'

Body:
You've opened the file in a writing mode as opposed to a reading mode, use "r" instead of "a" (which is append to file)

a = open('contacts.txt', 'r')

Also, not sure if you've included your question's indentation correctly, but the a.close() should be outside the for loop

As noted in the comments, using with is preferred over explicitly closing the file.

with open('contacts.txt', "r") as a:
    for line in a:
        k, v = line.strip().split('=')
        users[k.strip()] = v.strip()


问:
How to join two figures with different sizes in matplotlib?
I have two different figures from matplotlib.
The first one shows cell sizes through time :

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mahotas
import random

fig,ax_curves = plt.subplots(figsize=(8,6))

for cell in range(1,11):

    ax_curves.set_ylim(0,100)
    ax_curves.set_xlim(0,25)
    ax_curves.set_xticks(np.arange(0,21))

    ax_curves.plot(np.arange(0,21), random.sample(range(40, 61), 21), label = str(cell))
    ax_curves.legend(loc='right',frameon=False)
    ax_curves.spines['right'].set_visible(False)
    ax_curves.spines['top'].set_visible(False)
    ax_curves.set_title('Curves')

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

The second one shows images of these cells at different time points :

```<code>fig, ax_images =plt.subplots(10,5,figsize=(9, 16))
columns = 5
rows = 10

for column in range(0, columns):

    cell = 1

    for row in range(0,rows):

        ax_images[row, column].axes.get_xaxis().set_visible(False)

        ax_images[row, column].tick_params(
                    axis='y',
                    which='both',
                    left=False,
                    right=False,
                    labelleft=False)

        ax_images[row, 0].set_ylabel('Cell ' + str(cell), rotation = 0, color=tab10.colors[row])
        ax_images[row, 0].yaxis.set_label_coords(-0.4,0.5)

        if column == 0:
            plt.figtext(0.14 , 0.9, '0 hour',fontsize = 20)
            img = mahotas.imread('path/to/image_t0.tif')
        if column == 1:
            plt.figtext(0.28, 0.9, '5 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t5.tif')
        if column == 2:
            plt.figtext(0.44 , 0.9, '10 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t10.tif')
        if column == 3:
            plt.figtext(0.60, 0.9, '15 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t15.tif')
        if column == 4:
            plt.figtext(0.76 , 0.9, '20 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t20.tif')

        ax_images[row, column].imshow(img)

        cell = cell + 1

plt.figtext(0.5,0.95,'Cell size through time', fontsize = 20, horizontalalignment='center')
plt.show()
</code>```

I would like to "gather" those two figures (the first on the left and the second on the right fro example). I tried for several hours with GrisSpec or add_subplot but I failed... Please, could you let me know if you have any clue to solve this problem ?

Kindly yours !

答:
Thanks to @gboffi 's answer, I have been able to solve my issue :

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mahotas
import random

f = plt.figure(figsize=(13,4))
ax_curves = f.add_axes((0.10,1.5, 0.33, 0.85))

for cell in range(1,11):

    ax_curves.set_ylim(0,100)
    ax_curves.set_xlim(0,30)
    ax_curves.set_xticks(np.arange(0,21,5))

    ax_curves.plot(np.arange(0,21), random.sample(range(40, 61), 21), label = 'Cell ' + str(cell))
    ax_curves.legend(loc='right',frameon=False)
    ax_curves.spines['right'].set_visible(False)
    ax_curves.spines['top'].set_visible(False)
    ax_curves.set_title('Curves')

for column in np.linspace(0.5, 0.9, 5):

    cell = 1

    tab10 = matplotlib.cm.get_cmap('tab10')

    for row in np.linspace(2.8, 0.10, 10):
    # LL corner, width, height in figure coordinates, 0 ≤ x,y,h,w ≤ 1
        ax_images = f.add_axes((column, row, 0.09, 0.27))

        ax_images.axes.get_xaxis().set_visible(False)

        ax_images.tick_params(
                    axis='y',
                    which='both',
                    left=False,
                    right=False,
                    labelleft=False)

        if column == 0.5:
            ax_images.set_ylabel('Cell ' + str(cell), rotation = 0, color=tab10.colors[cell-1])
            ax_images.yaxis.set_label_coords(-0.4,0.5)

        else :
            pass

        if column == 0.5:
            plt.figtext(column+0.01 , 3.1, '0 hour',fontsize = 20)
#             img = mahotas.imread('path/to/image_t0.tif')
        if column == 0.6:
            plt.figtext(column, 3.1, '5 hours',fontsize = 20)
#             img = mahotas.imread('path/to/image_t5.tif')
        if column == 0.7:
            plt.figtext(column , 3.1, '10 hours', fontsize = 20)
#             img = mahotas.imread('path/to/image_t10.tif')
        if column == 0.8:
            plt.figtext(column, 3.1, '15 hours',fontsize = 20)
#             img = mahotas.imread('path/to/image_t15.tif')
        if column == 0.9:
            plt.figtext(column , 3.1, '20 hours', fontsize = 20)
#             img = mahotas.imread('path/to/image_t20.tif')

#         ax[row, column].imshow(img)

        cell = cell + 1
plt.figtext(0.5,3.33,'Cell sizes through time', fontsize = 20, horizontalalignment='center')
</code>```

Thank you very much for your help !!!

Body:
I have two different figures from matplotlib.
The first one shows cell sizes through time :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mahotas
import random

fig,ax_curves = plt.subplots(figsize=(8,6))

for cell in range(1,11):

    ax_curves.set_ylim(0,100)
    ax_curves.set_xlim(0,25)
    ax_curves.set_xticks(np.arange(0,21))

    ax_curves.plot(np.arange(0,21), random.sample(range(40, 61), 21), label = str(cell))
    ax_curves.legend(loc='right',frameon=False)
    ax_curves.spines['right'].set_visible(False)
    ax_curves.spines['top'].set_visible(False)
    ax_curves.set_title('Curves')

plt.show()

The second one shows images of these cells at different time points :

fig, ax_images =plt.subplots(10,5,figsize=(9, 16))
columns = 5
rows = 10

for column in range(0, columns):

    cell = 1

    for row in range(0,rows):

        ax_images[row, column].axes.get_xaxis().set_visible(False)

        ax_images[row, column].tick_params(
                    axis='y',
                    which='both',
                    left=False,
                    right=False,
                    labelleft=False)

        ax_images[row, 0].set_ylabel('Cell ' + str(cell), rotation = 0, color=tab10.colors[row])
        ax_images[row, 0].yaxis.set_label_coords(-0.4,0.5)

        if column == 0:
            plt.figtext(0.14 , 0.9, '0 hour',fontsize = 20)
            img = mahotas.imread('path/to/image_t0.tif')
        if column == 1:
            plt.figtext(0.28, 0.9, '5 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t5.tif')
        if column == 2:
            plt.figtext(0.44 , 0.9, '10 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t10.tif')
        if column == 3:
            plt.figtext(0.60, 0.9, '15 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t15.tif')
        if column == 4:
            plt.figtext(0.76 , 0.9, '20 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t20.tif')

        ax_images[row, column].imshow(img)

        cell = cell + 1

plt.figtext(0.5,0.95,'Cell size through time', fontsize = 20, horizontalalignment='center')
plt.show()

I would like to "gather" those two figures (the first on the left and the second on the right fro example). I tried for several hours with GrisSpec or add_subplot but I failed... Please, could you let me know if you have any clue to solve this problem ?

Kindly yours !

Body:
Thanks to @gboffi 's answer, I have been able to solve my issue :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mahotas
import random

f = plt.figure(figsize=(13,4))
ax_curves = f.add_axes((0.10,1.5, 0.33, 0.85))

for cell in range(1,11):

    ax_curves.set_ylim(0,100)
    ax_curves.set_xlim(0,30)
    ax_curves.set_xticks(np.arange(0,21,5))

    ax_curves.plot(np.arange(0,21), random.sample(range(40, 61), 21), label = 'Cell ' + str(cell))
    ax_curves.legend(loc='right',frameon=False)
    ax_curves.spines['right'].set_visible(False)
    ax_curves.spines['top'].set_visible(False)
    ax_curves.set_title('Curves')

for column in np.linspace(0.5, 0.9, 5):

    cell = 1

    tab10 = matplotlib.cm.get_cmap('tab10')

    for row in np.linspace(2.8, 0.10, 10):
    # LL corner, width, height in figure coordinates, 0 ≤ x,y,h,w ≤ 1
        ax_images = f.add_axes((column, row, 0.09, 0.27))

        ax_images.axes.get_xaxis().set_visible(False)

        ax_images.tick_params(
                    axis='y',
                    which='both',
                    left=False,
                    right=False,
                    labelleft=False)

        if column == 0.5:
            ax_images.set_ylabel('Cell ' + str(cell), rotation = 0, color=tab10.colors[cell-1])
            ax_images.yaxis.set_label_coords(-0.4,0.5)

        else :
            pass

        if column == 0.5:
            plt.figtext(column+0.01 , 3.1, '0 hour',fontsize = 20)
#             img = mahotas.imread('path/to/image_t0.tif')
        if column == 0.6:
            plt.figtext(column, 3.1, '5 hours',fontsize = 20)
#             img = mahotas.imread('path/to/image_t5.tif')
        if column == 0.7:
            plt.figtext(column , 3.1, '10 hours', fontsize = 20)
#             img = mahotas.imread('path/to/image_t10.tif')
        if column == 0.8:
            plt.figtext(column, 3.1, '15 hours',fontsize = 20)
#             img = mahotas.imread('path/to/image_t15.tif')
        if column == 0.9:
            plt.figtext(column , 3.1, '20 hours', fontsize = 20)
#             img = mahotas.imread('path/to/image_t20.tif')

#         ax[row, column].imshow(img)

        cell = cell + 1
plt.figtext(0.5,3.33,'Cell sizes through time', fontsize = 20, horizontalalignment='center')

Thank you very much for your help !!!