问:
How to get parameters out of Query in NestJS
I want to be able to get a license plate from my query parameters, but it doesn't seem to work, whatever way I write my code, so I'm getting quite confused why it's not working.

Here's the expected behaviour: when using the following GET request: http://localhost:3978/licenseplate/getleasingcompany?licenseplate=1-WMW-478
I want to extract the licenseplate parameter.

Here's my current code:

```<code>@Get('getleasingcompany')
async getLeasingCompany(@Query('licenseplate') licenseplate: string) {
    console.log(licenseplate);
}
</code>```

This logs licenseplate as undefined when trying in postman.

I also tried variants of this code, such as:

```<code>@Get('getleasingcompany')
async getLeasingCompany(@Query() query) {
    console.log(query);
}
</code>```

This logged query as [Function: getQuery], which I have no idea how to handle (query.licenseplate is undefined)

Another option is found in a Stackoverflow explanation here, in which Kim uses path parameters. This did work for me, but isn't behaviour my program can use, unfortunately.

Could anyone explain what I'm doing wrong? Thanks!

EDIT 1: After a few comments, I updated my packages to version 7.1.2, to no avail. Returning the query to postman gives following output:

```<code>function getQuery() {
// always return a string, because this is the raw query string.
// if the queryParser plugin is used, req.query will provide an empty
// object fallback.
return this.getUrl().query || '';
}
</code>```

EDIT 2: Tried going the Express route by importing Request as follows: import { Request } from "express";. The code now looks like this:

```<code>@Get('getleasingcompany')
  async getLeasingCompany(@Req() request: Request) {
    console.log(request);
}
</code>```

A part of this log does show me that the query saved the variable:

```<code>originalUrl: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
  _parsedUrl:
   Url {
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: '?licenseplate=1-WMW-478',
     query: 'licenseplate=1-WMW-478',
     pathname: '/licenseplate/getleasingcompany',
     path: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
     href: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
     _raw: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478' },
</code>```

However, when logging the request.query, I still get [Function: GetQuery] as the result.

答:
Nothing looks wrong in your code. On Nest v7 using the following controller and curl I get what you'd expect

import { Controller, Get, Query } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(@Query() query: Record<string, any>): string {
    console.log(query);
    return this.appService.getHello();
  }
}
```

<pre class="lang-sh prettyprint-override"><code>curl http://localhost:3000/\?queryparam\=something
</code>```

[Nest] 46471   - 06/02/2020, 2:55:11 PM   [NestFactory] Starting Nest application...
[Nest] 46471   - 06/02/2020, 2:55:11 PM   [InstanceLoader] AppModule dependencies initialized +12ms
[Nest] 46471   - 06/02/2020, 2:55:11 PM   [RoutesResolver] AppController {}: +15ms
[Nest] 46471   - 06/02/2020, 2:55:11 PM   [RouterExplorer] Mapped {, GET} route +9ms
[Nest] 46471   - 06/02/2020, 2:55:11 PM   [NestApplication] Nest application successfully started +9ms
{ queryparam: 'something' }
```

My only guess is some mismatched version of Nest

Body:
I want to be able to get a license plate from my query parameters, but it doesn't seem to work, whatever way I write my code, so I'm getting quite confused why it's not working.

Here's the expected behaviour: when using the following GET request: http://localhost:3978/licenseplate/getleasingcompany?licenseplate=1-WMW-478
I want to extract the licenseplate parameter.

Here's my current code:

@Get('getleasingcompany')
async getLeasingCompany(@Query('licenseplate') licenseplate: string) {
    console.log(licenseplate);
}

This logs licenseplate as undefined when trying in postman.

I also tried variants of this code, such as:

@Get('getleasingcompany')
async getLeasingCompany(@Query() query) {
    console.log(query);
}

This logged query as [Function: getQuery], which I have no idea how to handle (query.licenseplate is undefined)

Another option is found in a Stackoverflow explanation here, in which Kim uses path parameters. This did work for me, but isn't behaviour my program can use, unfortunately.

Could anyone explain what I'm doing wrong? Thanks!

EDIT 1: After a few comments, I updated my packages to version 7.1.2, to no avail. Returning the query to postman gives following output:

function getQuery() {
// always return a string, because this is the raw query string.
// if the queryParser plugin is used, req.query will provide an empty
// object fallback.
return this.getUrl().query || '';
}

EDIT 2: Tried going the Express route by importing Request as follows: import { Request } from "express";. The code now looks like this:

@Get('getleasingcompany')
  async getLeasingCompany(@Req() request: Request) {
    console.log(request);
}

A part of this log does show me that the query saved the variable:

originalUrl: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
  _parsedUrl:
   Url {
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: '?licenseplate=1-WMW-478',
     query: 'licenseplate=1-WMW-478',
     pathname: '/licenseplate/getleasingcompany',
     path: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
     href: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
     _raw: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478' },

However, when logging the request.query, I still get [Function: GetQuery] as the result.

Body:
Nothing looks wrong in your code. On Nest v7 using the following controller and curl I get what you'd expect

import { Controller, Get, Query } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(@Query() query: Record<string, any>): string {
    console.log(query);
    return this.appService.getHello();
  }
}

curl http://localhost:3000/\?queryparam\=something

[Nest] 46471   - 06/02/2020, 2:55:11 PM   [NestFactory] Starting Nest application...
[Nest] 46471   - 06/02/2020, 2:55:11 PM   [InstanceLoader] AppModule dependencies initialized +12ms
[Nest] 46471   - 06/02/2020, 2:55:11 PM   [RoutesResolver] AppController {}: +15ms
[Nest] 46471   - 06/02/2020, 2:55:11 PM   [RouterExplorer] Mapped {, GET} route +9ms
[Nest] 46471   - 06/02/2020, 2:55:11 PM   [NestApplication] Nest application successfully started +9ms
{ queryparam: 'something' }

My only guess is some mismatched version of Nest


来源: stackexchange

问:
Make for identical workflow in separate directories
I'm using make to automate some of my data analysis. I have several directories, each containing a different realization of the data, which consists of several files representing the state of the data at a given time, like so:

```<code>├── a
│   ├── time_01.dat
│   ├── time_02.dat
│   ├── time_03.dat
│   └── ...
├── b
│   ├── time_01.dat
│   └── ...
├── c
│   ├── time_01.dat
│   └── ...
├── ...
</code>```

The number of datafiles in each directory is unknown, and more can be added at any time. The files all have the same naming convention in each directory.

I want to use make to run the exact same set of recipes in each directory (to analyze each dataset separately and uniformly). In particular, there is one script that should run any time a new datafile is added, and creates an output file (analysis_time_XX.txt) for each datafile in the directory. This script does not update any files that have been previously created, but does create all the missing files. Refactoring this script is not a possibility, unfortunately.

So I have one recipe creating many targets, yet it must run separately for each directory. The solutions I've found to create multiple targets with one recipe (e.g. here) do not work in my case, as I need one rule to do this separately for multiple sets of files in separate directories.

These intermediate files are needed for their own sake (as they help validate the data collected), but are also used to create a final comparison plot between the datasets.

My current setup is an ugly combination of functions and .SECONDEXPANSION

```<code>dirs = a b c

datafiles = $(foreach dir,$(dirs),$(wildcard $(dir)/*.dat))

df_to_analysis = $(subst .dat,.txt,$(subst time_,analysis_time_,$(1)))
analysis_to_df = $(subst .txt,.dat,$(subst analysis_time_,time_,$(1)))

analysis_files = $(foreach df,$(datafiles),$(call df_to_analysis,$(df)))

all: final_analysis_plot.png

.SECONDEXPANSION:
$(analysis_files): %: $$(call analysis_to_df,%)
    python script.py $(dir $@)

final_analysis_plot.png: $(analysis_files)
    python make_plot.py $(analysis_files)
</code>```

Note that script.py creates all of the analysis_time_XX.txt files in the given directory. The flaw with this setup is that make does not know that the first script generates all the targets, and so runs unnecessarily when parallel make is used. For my application parallel make is a necessity, as these scripts have a long runtime, and parallelization saves a lot of time as the setup is "embarrassingly parallel."

Is there an elegant way to fix this issue? Or even an elegant way to clean up the code I have now? I've shown a simple example here, which already requires a good bit of setup, and doing this for several different scripts gets unwieldy quickly.

答:
I think, in your case there's no need to bother with .txt files. If script.py was nicer and could work per-file, there would be a value in writing individual file rules. In this case, we need to introduce an intermediate per-directory .done files.

```<code>DATA_DIRS := a b c
# A directory/.done.analysis file means that `script.py` was run here.
DONE_FILES := $(DATA_DIRS:%=%/*.done.analysis)

# .done.analysis depends on all the source data files.
# When a .dat file is added or changes, it will be newer than
# a .done.analysis file; and the analysis would be re-run.
$(DONE_FILES): %/.done.analysis: $(wildcard %/*.dat)
    python script.py $(@D)

final_analysis_plot.png: $(DONE_FILES)
    python make_plot.py $(wildcard $(DATA_DIRS)/analysis_time_*.txt)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using make to automate some of my data analysis. I have several directories, each containing a different realization of the data, which consists of several files representing the state of the data at a given time, like so:

├── a
│   ├── time_01.dat
│   ├── time_02.dat
│   ├── time_03.dat
│   └── ...
├── b
│   ├── time_01.dat
│   └── ...
├── c
│   ├── time_01.dat
│   └── ...
├── ...

The number of datafiles in each directory is unknown, and more can be added at any time. The files all have the same naming convention in each directory.

I want to use make to run the exact same set of recipes in each directory (to analyze each dataset separately and uniformly). In particular, there is one script that should run any time a new datafile is added, and creates an output file (analysis_time_XX.txt) for each datafile in the directory. This script does not update any files that have been previously created, but does create all the missing files. Refactoring this script is not a possibility, unfortunately.

So I have one recipe creating many targets, yet it must run separately for each directory. The solutions I've found to create multiple targets with one recipe (e.g. here) do not work in my case, as I need one rule to do this separately for multiple sets of files in separate directories.

These intermediate files are needed for their own sake (as they help validate the data collected), but are also used to create a final comparison plot between the datasets.

My current setup is an ugly combination of functions and .SECONDEXPANSION

dirs = a b c

datafiles = $(foreach dir,$(dirs),$(wildcard $(dir)/*.dat))

df_to_analysis = $(subst .dat,.txt,$(subst time_,analysis_time_,$(1)))
analysis_to_df = $(subst .txt,.dat,$(subst analysis_time_,time_,$(1)))

analysis_files = $(foreach df,$(datafiles),$(call df_to_analysis,$(df)))

all: final_analysis_plot.png

.SECONDEXPANSION:
$(analysis_files): %: $$(call analysis_to_df,%)
    python script.py $(dir $@)

final_analysis_plot.png: $(analysis_files)
    python make_plot.py $(analysis_files)

Note that script.py creates all of the analysis_time_XX.txt files in the given directory. The flaw with this setup is that make does not know that the first script generates all the targets, and so runs unnecessarily when parallel make is used. For my application parallel make is a necessity, as these scripts have a long runtime, and parallelization saves a lot of time as the setup is "embarrassingly parallel."

Is there an elegant way to fix this issue? Or even an elegant way to clean up the code I have now? I've shown a simple example here, which already requires a good bit of setup, and doing this for several different scripts gets unwieldy quickly.

Body:
I think, in your case there's no need to bother with .txt files. If script.py was nicer and could work per-file, there would be a value in writing individual file rules. In this case, we need to introduce an intermediate per-directory .done files.

DATA_DIRS := a b c
# A directory/.done.analysis file means that `script.py` was run here.
DONE_FILES := $(DATA_DIRS:%=%/*.done.analysis)

# .done.analysis depends on all the source data files.
# When a .dat file is added or changes, it will be newer than
# a .done.analysis file; and the analysis would be re-run.
$(DONE_FILES): %/.done.analysis: $(wildcard %/*.dat)
    python script.py $(@D)

final_analysis_plot.png: $(DONE_FILES)
    python make_plot.py $(wildcard $(DATA_DIRS)/analysis_time_*.txt)


问:
Is there a CodeIgniter equivalent ASP.NET?
CodeIgniter is a great tool for speeding up development. Is there a CodeIgniter equivalent for ASP.NET? I am very new to ASP.NET 4 and C#</p>

答: I think ASP.NET MVC would be the closest thing.</p>

ContentLicense: CC BY-SA 3.0


问:
Sometimes getting nil while converting UTC date string to timestamp
Sometimes I am getting nil while converting date string to timestamp.

Here is my code:

```<code>class func createTimeStampFromDateString(dateString : String) -> Double? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let convertedDate = dateFormatter.date(from: dateString)
    let timeIntervalsince1970 = convertedDate?.timeIntervalSince1970
    return timeIntervalsince1970
}
</code>```

Could you please let me know what is wrong in this code.

Thanks in advance!

答:
When using the standard DateFormatter for an ISO8601 date, you should set the locale to en_US_POSIX (dateFormatter.locale = Locale(identifier: "en_US_POSIX")) before converting from string.

Also when converting a string to a date it can always happen that the string is in the wrong format (missing or wrong number/character). There are many things that can be wrong here.

But for ISO8601 dates there is a dedicated ISO8601DateFormatter. It can handle multiple variants of ISO8601 formatted dates. But it is only available since iOS 10.

Body:
Sometimes I am getting nil while converting date string to timestamp.

Here is my code:

class func createTimeStampFromDateString(dateString : String) -> Double? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let convertedDate = dateFormatter.date(from: dateString)
    let timeIntervalsince1970 = convertedDate?.timeIntervalSince1970
    return timeIntervalsince1970
}

Could you please let me know what is wrong in this code.

Thanks in advance!


问:
What is the best way to override the behavior of Picker Component of FluentUI?
What I would like to do is...
- Change the callout that appears when the user tries to type something. I want to add a custom component with a Search Box and also the ability for the user to choose the category.
- Change the look of rendered text. Just like People Picker but with icon and text.
- Ability to trigger the callout to appear when an external button is clicked. Maybe I can fire focus event on Picker when Button is clicked. Just thinking out loud.

I tried implementing it but there's not much documentation on it. Any example related to it would be appreciated.

Thanks!

答:
Change the callout that appears when the user tries to type something. I want to add a custom component with a Search Box and also the ability for the user to choose the category.

The pickers are mainly intended to show options that correspond directly to the input, and usually are constrained by the input. It should be possible to build what you're describing, though I expect building it from scratch would be easier than repurposing a picker.

Change the look of rendered text. Just like People Picker but with icon and text.

Starting from the Picker example, changing the look of suggestions can be done by overriding onRenderSuggestionsItem, such as in the following:

```<code><TagPicker
          onResolveSuggestions={this._onFilterChanged}
          onRenderSuggestionsItem={(p) => <TagItemSuggestion>
                                           <FontIcon iconName="Dictionary"/> key: {p.key}, name: {p.name}
                                          </TagItemSuggestion>}
        />
</code>```

Ability to trigger the callout to appear when an external button is clicked. Maybe I can fire focus event on Picker when Button is clicked

I would recommend using a ref to access the imperative interface, then call focus() when the button is clicked. I don't believe there's an API to actually show the suggestion pane, but that will at least put users in the right context.

Body:
Change the callout that appears when the user tries to type something. I want to add a custom component with a Search Box and also the ability for the user to choose the category.

The pickers are mainly intended to show options that correspond directly to the input, and usually are constrained by the input. It should be possible to build what you're describing, though I expect building it from scratch would be easier than repurposing a picker.

Change the look of rendered text. Just like People Picker but with icon and text.

Starting from the Picker example, changing the look of suggestions can be done by overriding onRenderSuggestionsItem, such as in the following:

<TagPicker
          onResolveSuggestions={this._onFilterChanged}
          onRenderSuggestionsItem={(p) => <TagItemSuggestion>
                                           <FontIcon iconName="Dictionary"/> key: {p.key}, name: {p.name}
                                          </TagItemSuggestion>}
        />

Ability to trigger the callout to appear when an external button is clicked. Maybe I can fire focus event on Picker when Button is clicked

I would recommend using a ref to access the imperative interface, then call focus() when the button is clicked. I don't believe there's an API to actually show the suggestion pane, but that will at least put users in the right context.


问:
Missing argument for parameter 'delegate' in call // JSON file corrupted in SWIFT?
I am following an e-class tutorial for SWIFT // XCODE 11.4 and I have to fetch data from Open Weather API and display it on the interface where people can type in a city and the view controller will display temperature, cloud icon, and description.

Clima App Tutorial

I am using the MVC pattern design and the delegate design to accomplish this tutorial. My swift files are as followed:

Swift Files in MVC Design Pattern

Here are the codes in each of the important files:

I. Model folder

WeatherManager.swift

```<code>protocol WeatherManagerDelegate {
    func didUpdateWeather(weather: WeatherModel)
}

struct WeatherManager {
    let weatherURL = "https://api.openweathermap.org/d.5/weather?appid=c8b50079338280b47a65dd6082551e3b&units=imperial"

    let delegate: WeatherManagerDelegate?

    func fetchWeather(cityName: String) {
        let urlString = "\(weatherURL)&q=\(cityName)"
        performRequest(urlString: urlString)
    }

    func performRequest(urlString: String) {

        //create a URL
        if let url = URL(string: urlString) {

            //create a URLSession
            let session = URLSession(configuration: .default)

            //give session a task
            let task = session.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print(error!)
                    return //exit out of the func if there is an error
                }

                if let safeData = data {

                    if let weather =  self.parseJSON(weatherData: safeData) {
                    self.delegate?.didUpdateWeather(weather: weather)
                    }
                }
            }
            //start the tast
            task.resume()
        }
    }

    func parseJSON (weatherData: Data) -> WeatherModel? {
        let decoder = JSONDecoder()
        do {
            let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
            let id = decodedData.weather[0].id
            let temp = decodedData.main.temp
            let name = decodedData.name

            let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
            return weather

        } catch {
            print(error)
            return nil
        }
    }

}
</code>```

WeatherData.swift

```<code>struct WeatherData: Codable {
    let name: String
    let main: Main
    let weather: [Weather]
}

struct Main: Codable {
    let temp: Double
}

struct Weather: Codable {
    let id: Int
}
</code>```

WeatherModel.swift

```<code>struct WeatherModel {
    let conditionId: Int
    let cityName: String
    let temperature: Double

    var temperatureString: String {
        return String(format: "%.1f", temperature)
    }

    var conditionName: String {
        switch conditionId {
        case 200...232:
            return "cloud.bolt"
        case 300...321:
            return "cloud.drizzle"
        case 500...531:
            return "cloud.rain"
        case 600...622:
            return "cloud.snow"
        case 701...781:
            return "cloud.fog"
        case 800:
            return "sun.max"
        case 801...804:
            return "cloud.bolt"
        default:
            return "cloud"
        }
    }

}
</code>```

II. Controller

WeatherViewController.swift (place where the error is)

```<code>class WeatherViewController: UIViewController, UITextFieldDelegate, WeatherManagerDelegate {

    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var temperatureLabel: UILabel!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var searchTextField: UITextField!

    var weatherManager = WeatherManager()

    override func viewDidLoad() {

        super.viewDidLoad()
        weatherManager.delegate = self

        searchTextField.delegate = self
    }

    @IBAction func searchPressed(_ sender: UIButton) {
        searchTextField.endEditing(true)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        searchTextField.endEditing(true)
        print(searchTextField.text!)
        return true
    }

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if textField.text != "" {
            return true
        } else {
            textField.placeholder = "Type something..."
            return false
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        if let city = searchTextField.text {
            weatherManager.fetchWeather(cityname: city)
        }

        searchTextField.text = ""

    }

    func didUpdateWeather(weather: WeatherModel) {
        print(weather.temperature)
    }

}
</code>```

Here is the error message: Missing argument for parameter 'delegate' in call
Error message in WeatherViewControl.swift

And when I hit the run button, I also got this error in the debug console:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

Error in the debug console

What should I do to get rid of these errors?

答:
Missing argument for parameter 'delegate' in call

When a struct is create a value for each property is required.

If each property is specified with a default value and there is no user-defined initializer then Swift will create a default initializer for the struct.

If there is at least one property without a default value and there is no user-defined initializer then Swift will create a memberwise initializer which has one parameter for each property without a default value.

For example your type:

```<code>struct WeatherModel {
   let conditionId: Int
   let cityName: String
   let temperature: Double
...
</code>```

has three properties without default values. If you start typing:

```<code>let myWeatherModel = WeatherModel(
</code>```

and then take the completion offered you will get (something like):

```<code>let wm = WeatherModel(conditionId: <Int>, cityName: <String>, temperature: <Double>)
</code>```

The completion is showing the memberwise initializer.

Your type which produces the error is:

```<code>struct WeatherManager {
   let weatherURL = "https://api.openweathermap.org/d.5/weather?appid=c8b50079338280b47a65dd6082551e3b&units=imperial"
   let delegate: WeatherManagerDelegate?
</code>```

which has two properties only one of which has a default value, and it has no initializers, so Swift will create a member wise initialiser automatically.

There is nothing wrong so far.

The line producing the error is:

```<code>var weatherManager = WeatherManager()
</code>```

Here you are attempting to create a WeatherManager without invoking the member wise initalizer, so Swift gives you the error message.

If you click on the error message itself you will see a Fix is offered, click that and Swift will change your code to:

```<code>var weatherManager = WeatherManager(delegate: <WeatherManagerDelegate?>)
</code>```

Select the <WeatherManagerDelegate?> and type the value you wish to pass.

HTH

Body:
I am following an e-class tutorial for SWIFT // XCODE 11.4 and I have to fetch data from Open Weather API and display it on the interface where people can type in a city and the view controller will display temperature, cloud icon, and description.

Clima App Tutorial

I am using the MVC pattern design and the delegate design to accomplish this tutorial. My swift files are as followed:

Swift Files in MVC Design Pattern

Here are the codes in each of the important files:

I. Model folder

WeatherManager.swift

protocol WeatherManagerDelegate {
    func didUpdateWeather(weather: WeatherModel)
}

struct WeatherManager {
    let weatherURL = "https://api.openweathermap.org/d.5/weather?appid=c8b50079338280b47a65dd6082551e3b&units=imperial"

    let delegate: WeatherManagerDelegate?

    func fetchWeather(cityName: String) {
        let urlString = "\(weatherURL)&q=\(cityName)"
        performRequest(urlString: urlString)
    }

    func performRequest(urlString: String) {

        //create a URL
        if let url = URL(string: urlString) {

            //create a URLSession
            let session = URLSession(configuration: .default)

            //give session a task
            let task = session.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print(error!)
                    return //exit out of the func if there is an error
                }

                if let safeData = data {

                    if let weather =  self.parseJSON(weatherData: safeData) {
                    self.delegate?.didUpdateWeather(weather: weather)
                    }
                }
            }
            //start the tast
            task.resume()
        }
    }

    func parseJSON (weatherData: Data) -> WeatherModel? {
        let decoder = JSONDecoder()
        do {
            let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
            let id = decodedData.weather[0].id
            let temp = decodedData.main.temp
            let name = decodedData.name

            let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
            return weather

        } catch {
            print(error)
            return nil
        }
    }

}

WeatherData.swift

struct WeatherData: Codable {
    let name: String
    let main: Main
    let weather: [Weather]
}

struct Main: Codable {
    let temp: Double
}

struct Weather: Codable {
    let id: Int
}

WeatherModel.swift

struct WeatherModel {
    let conditionId: Int
    let cityName: String
    let temperature: Double

    var temperatureString: String {
        return String(format: "%.1f", temperature)
    }

    var conditionName: String {
        switch conditionId {
        case 200...232:
            return "cloud.bolt"
        case 300...321:
            return "cloud.drizzle"
        case 500...531:
            return "cloud.rain"
        case 600...622:
            return "cloud.snow"
        case 701...781:
            return "cloud.fog"
        case 800:
            return "sun.max"
        case 801...804:
            return "cloud.bolt"
        default:
            return "cloud"
        }
    }

}

II. Controller

WeatherViewController.swift (place where the error is)

class WeatherViewController: UIViewController, UITextFieldDelegate, WeatherManagerDelegate {

    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var temperatureLabel: UILabel!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var searchTextField: UITextField!

    var weatherManager = WeatherManager()

    override func viewDidLoad() {

        super.viewDidLoad()
        weatherManager.delegate = self

        searchTextField.delegate = self
    }

    @IBAction func searchPressed(_ sender: UIButton) {
        searchTextField.endEditing(true)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        searchTextField.endEditing(true)
        print(searchTextField.text!)
        return true
    }

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if textField.text != "" {
            return true
        } else {
            textField.placeholder = "Type something..."
            return false
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        if let city = searchTextField.text {
            weatherManager.fetchWeather(cityname: city)
        }

        searchTextField.text = ""

    }

    func didUpdateWeather(weather: WeatherModel) {
        print(weather.temperature)
    }

}

Here is the error message: Missing argument for parameter 'delegate' in call
Error message in WeatherViewControl.swift

And when I hit the run button, I also got this error in the debug console:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

Error in the debug console

What should I do to get rid of these errors?

Body:
Missing argument for parameter 'delegate' in call

When a struct is create a value for each property is required.

If each property is specified with a default value and there is no user-defined initializer then Swift will create a default initializer for the struct.

If there is at least one property without a default value and there is no user-defined initializer then Swift will create a memberwise initializer which has one parameter for each property without a default value.

For example your type:

struct WeatherModel {
   let conditionId: Int
   let cityName: String
   let temperature: Double
...

has three properties without default values. If you start typing:

let myWeatherModel = WeatherModel(

and then take the completion offered you will get (something like):

let wm = WeatherModel(conditionId: <Int>, cityName: <String>, temperature: <Double>)

The completion is showing the memberwise initializer.

Your type which produces the error is:

struct WeatherManager {
   let weatherURL = "https://api.openweathermap.org/d.5/weather?appid=c8b50079338280b47a65dd6082551e3b&units=imperial"
   let delegate: WeatherManagerDelegate?

which has two properties only one of which has a default value, and it has no initializers, so Swift will create a member wise initialiser automatically.

There is nothing wrong so far.

The line producing the error is:

var weatherManager = WeatherManager()

Here you are attempting to create a WeatherManager without invoking the member wise initalizer, so Swift gives you the error message.

If you click on the error message itself you will see a Fix is offered, click that and Swift will change your code to:

var weatherManager = WeatherManager(delegate: <WeatherManagerDelegate?>)

Select the <WeatherManagerDelegate?> and type the value you wish to pass.

HTH


问:
Android MotionLayout don't showing animation on real device
I create animation in MotionLayout Editor in Android Studio 4.0.

I have this animation scene:

```<code><?xml version="1.0" encoding="utf-8"?>
<MotionScene
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@id/start"
        motion:duration="1000">
       <KeyFrameSet>
       </KeyFrameSet>
    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint
            android:id="@+id/bt_authorization_login"
            motion:layout_constraintEnd_toEndOf="@+id/ll_login_password_container"
            motion:layout_constraintStart_toEndOf="parent"
            android:layout_width="0dp"
            android:layout_height="@dimen/_35sdp"
            android:visibility="invisible"
            motion:layout_constraintTop_toBottomOf="@+id/tv_authorization_forget_password"
            motion:layout_constraintStart_toStartOf="@+id/ll_login_password_container"
            android:layout_marginTop="@dimen/_16sdp" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
    </ConstraintSet>
</MotionScene>
</code>```

Animation in MotionLayout Editor work is fine.
animation in editor

But when I start it on real device, animation don't showing. I tryed on diferent devices.

How to start animation on device?

答:
I suggest to explicitly define button constraints in the end constraint set. You also can use  attribute for code simplicity if you want just to change button visibility in constraint sets.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@id/start"
        motion:duration="1000">
    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint android:id="@+id/bt_authorization_login">
            <PropertySet android:visibility="invisible" />
        </Constraint>
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint android:id="@+id/bt_authorization_login">
            <PropertySet android:visibility="visible" />
        </Constraint>
    </ConstraintSet>
</MotionScene>
</code>```

Body:
I create animation in MotionLayout Editor in Android Studio 4.0.

I have this animation scene:

<?xml version="1.0" encoding="utf-8"?>
<MotionScene
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@id/start"
        motion:duration="1000">
       <KeyFrameSet>
       </KeyFrameSet>
    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint
            android:id="@+id/bt_authorization_login"
            motion:layout_constraintEnd_toEndOf="@+id/ll_login_password_container"
            motion:layout_constraintStart_toEndOf="parent"
            android:layout_width="0dp"
            android:layout_height="@dimen/_35sdp"
            android:visibility="invisible"
            motion:layout_constraintTop_toBottomOf="@+id/tv_authorization_forget_password"
            motion:layout_constraintStart_toStartOf="@+id/ll_login_password_container"
            android:layout_marginTop="@dimen/_16sdp" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
    </ConstraintSet>
</MotionScene>

Animation in MotionLayout Editor work is fine.
animation in editor

But when I start it on real device, animation don't showing. I tryed on diferent devices.

How to start animation on device?

Body:
I suggest to explicitly define button constraints in the end constraint set. You also can use  attribute for code simplicity if you want just to change button visibility in constraint sets.

<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@id/start"
        motion:duration="1000">
    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint android:id="@+id/bt_authorization_login">
            <PropertySet android:visibility="invisible" />
        </Constraint>
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint android:id="@+id/bt_authorization_login">
            <PropertySet android:visibility="visible" />
        </Constraint>
    </ConstraintSet>
</MotionScene>


问:
Vue, can't get why it acting strange in a function. Runs 5 times forEach when there is a return
That's my whole test file. I've done so far, validation and it changes span class correctly due to correctly or not correctly fulfilled input. But where I'm stuck is I want disable button if there is not correctly fulfilled input or empty at all. And I think I've done logic right, but it doesn't work. I consoled.loged it, I see where is an issue, but why it happens for me is a mystery.

In short what happens: button is signed to variable button, and inputs on every input event calling function ft_button which check's if inputs are correctly fulfilled and buy that result it changes variable button. And it would have been fine, but in this function I don't know why it runs forEach cycle 5 times when there is return written. Is it some sort of JS thing? Cause in C if there is a return it stopps looping no matter what. And of course it will print out active at the end since it just skips all returns in forEach loop.

on pic you can see it logs 5 times 2 which is actually a surprise for me, cause after return it should just stop looping. Gmm how then should I return active or disabled...

```<code> <!doctype html>
    <html lang="ru">
    <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>1</title>
         <link rel="stylesheet" href="css/bootstrap.min.css">
         <link rel="stylesheet" href="css/font-awesome.min.css">
         <link href="css/styles.css" rel="stylesheet">
         <script src="js/vue.js"></script>
    </head>
    <body>
         <div class="wrapper">
              <div class="sample">
                    <form>
                    <div class="progress">
                        <div class="progress-bar"></div>
                    </div>
                    <div>
                        <div class="form-group" v-for="v in info">
                            <label v-bind:for='v.name'>{{ v.name | capitalize }}</label><span :class="alertType(v.value)"></span>
                            <input id="intra" type="text" class="form-control" v-on:input="checkInput($event, v)">
                            <div>{{ v.value ? 'true' : 'false'}}</div>
                        </div>
                    </div>
                    <button class="btn btn-primary" :class="button">
                        Send Data
                    </button>
                </form>
                <div>
                    <table class="table table-bordered">
                        <tr>
                            <td></td>
                            <td></td>
                        </tr>
                    </table>
                </div>
            </div>
         </div>
        <script>
        Vue.filter('capitalize', function (value) {
              if (!value) return '';
              value = value.toString();
              return value.charAt(0).toUpperCase() + value.slice(1)
        })

            new Vue({
                el: '.sample',
                data: {
                    button: 'disabled',
                    info: [
                        {
                            name: 'intra',
                            value: '',
                            pattern: /^[a-zA-Z ]{2,30}$/
                        },
                        {
                            name: 'phone',
                            value: '',
                            pattern: /^[0-9]{7,14}$/
                        },
                        {
                            name: 'email',
                            value: '',
                            pattern: /.+/
                        },
                        {
                            name: 'password',
                            value: '',
                            pattern: /.+/
                        },
                        {
                            name: 'repeatPassword',
                            value: '',
                            pattern: /.+/
                        }
                    ]
                },
                methods:
                {
                    checkInput(e, obj){
                        obj.value = obj.pattern.test(e.target.value);
                        this.button = this.ft_button();
                    },
                    alertType(value)
                    {
                        if(value === true)
                            return "fa fa-check-circle";
                        if(value === false)
                            return "fa fa-exclamation-circle";
                    },
                    ft_button()
                    {
                        this.info.forEach((el) =>
                            {
                                if (el.value === false || el.value === '')
                                {
                                    console.log(2);
                                    return 'disabled';
                                }
                            })
                        console.log(1);
                        return 'active';
                    }
                },
                computed:
                {
                }
            });
        </script>
    </body>
    </html>
</code>```

答: you can't return from forEach the same way you can in a vanilla for loop. This question may be helpful: What does `return` keyword mean inside `forEach` function?

Body:
That's my whole test file. I've done so far, validation and it changes span class correctly due to correctly or not correctly fulfilled input. But where I'm stuck is I want disable button if there is not correctly fulfilled input or empty at all. And I think I've done logic right, but it doesn't work. I consoled.loged it, I see where is an issue, but why it happens for me is a mystery.

In short what happens: button is signed to variable button, and inputs on every input event calling function ft_button which check's if inputs are correctly fulfilled and buy that result it changes variable button. And it would have been fine, but in this function I don't know why it runs forEach cycle 5 times when there is return written. Is it some sort of JS thing? Cause in C if there is a return it stopps looping no matter what. And of course it will print out active at the end since it just skips all returns in forEach loop.

on pic you can see it logs 5 times 2 which is actually a surprise for me, cause after return it should just stop looping. Gmm how then should I return active or disabled...

 <!doctype html>

         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>1</title>
         <link rel="stylesheet" href="css/bootstrap.min.css">
         <link rel="stylesheet" href="css/font-awesome.min.css">
         <link href="css/styles.css" rel="stylesheet">

                    <form>

                            {{ v.name | capitalize }}
                            <input id="intra" type="text" class="form-control" v-on:input="checkInput($event, v)">

{{ v.value ? 'true' : 'false'}}

                    <button class="btn btn-primary" :class="button">
                        Send Data
                    </button>
                </form>


问:
how to I make my footer responsive without glitching?
So im pretty happy with my footer now and its fairly responsive. The Problem: its pretty glitchy. When resizing the window, the text and the links will stack on each other and so on. Can someone help me to fix this? I would love if the middle links would stay side by side and also the social media links to stay in a block.

thank you so much.

.footer {
 position: static;
 flex-shrink: 0;
    bottom: 0px;
    left: 0px;
    right: 0px;
    padding: 0px;
    width: 100%;
    background-color: #F9F9F9;
    text-align: center;
 box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
 z-index: 99;
    /*outline: 2px dashed orange;*/
}
.footerline {
 padding: 50px;
    display: flex;
    font-family: 'Source Code Pro', monospace;
    font-style: normal;
    font-weight: 400;
    font-size: 15px;
    color: #D5D5D5;
    justify-content: center;
    align-items: center;
    /*outline: 2px dashed orange;*/
}
#footerlineshadow {
 color: rgba(240,240,240, 0.9);
    text-shadow: 1px 1px 1px #fff, 0 0 0 #000, 1px 1px 1px #fff;
}
.subfooter {
    height: 40px;
    background-color: #E5E5E5;
    box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
}
.footercontent {
    display: flex;
    font-family: lato;
    color: #ABABAB;
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    text-align: center;
    justify-content: center;
    height: 100%;
}
#footertext {
 text-align: center;
 margin-right: 20%;
 /*outline: 2px dashed orange;*/
}
#footerlinks {
 text-align: center;
 /*outline: 2px dashed orange;*/

}
#footerlinks a {
    margin: 0px 40px;
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    color: #ABABAB;
    text-decoration: none; /*outline: 2px dashed orange;*/
}
#footerlinks a:hover {
 opacity: 0.7;
 font-style: normal;
    font-weight: 100;
    font-size: 12px;
 text-decoration: none;
 /*outline: 2px dashed orange;*/
}
#footersocialmedia {
 margin-left: 20%;
}
 /* Style all font awesome icons */
.fa {
  padding: 5px;
  font-size: 30px;
  width: 25px;
 height: 100%;
  text-align: center;
  text-decoration: none;
}

/* Add a hover effect if you want */
.fa:hover {
  opacity: 0.7;
}

/* Set a specific color for each brand */

/* Facebook */
.fa-facebook {
  background: #3B5998;
  color: white;
}

/* Twitter */
.fa-twitter {
  background: #55ACEE;
  color: white;
}
.fa-youtube {
  background: #bb0000;
  color: white;
}

.fa-instagram {
  background: #125688;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" id="applicationStylesheet" href="header_footer.css"/>
<link rel="stylesheet" type="text/css" id="mainStylesheet" href="kontakt.css"/>
<link href="http://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<footer class="footer">
   <div class="footerline">
     <p id="footerlineshadow">&ltp&gtThis is a Footer&lt/p&gt</p>
      </div>
 <div class="subfooter">
  <div class="footercontent">
   <div id="footertext">
    <p>Copyright © 2020 Henning Frenzel</p>
   </div>

   <div id="footerlinks">
    <p>
    Home
    Über Mich
         Portfolio
         Kontakt
    Impressum
    </p>
   </div>
   <div id="footersocialmedia">

   </div>
  </div>
 </div>
</footer>
</html></code>```

答:
Here is the code for responsive footer

.footer {
  display:flex;
  flex-direction:row;
    min-height:50px;
    width: 100%;
    background-color: #F9F9F9;
    justify-content:center;
    align-items:center;

    text-align: center;
        flex-wrap:wrap;

 box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
}
.footerline {
    display: flex;
    font-family: 'Source Code Pro', monospace;
    font-style: normal;
    font-weight: 400;
    font-size: 15px;
    color: #D5D5D5;
    width:100%;
    justify-content: center;
    align-items: center;
    flex-direction:row;
    flex-wrap:wrap;
    /*outline: 2px dashed orange;*/
}
#footerlineshadow {
 color: rgba(240,240,240, 0.9);
    text-shadow: 1px 1px 1px #fff, 0 0 0 #000, 1px 1px 1px #fff;
}
.subfooter {
    background-color: #E5E5E5;
    box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
}
.footercontent {
    display: flex;
    font-family: lato;
    color: #ABABAB;
    font-style: normal;
    font-weight: 100;
    width:100%;
    font-size: 12px;
    text-align: center;
    justify-content: center;
    min-height:50px;
}
#footertext {
 text-align: center;
 /*outline: 2px dashed orange;*/
}
#footerlinks {
 text-align: center;
 /*outline: 2px dashed orange;*/

}
#footerlinks a {
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    padding:0 15px;
    color: #ABABAB;
    text-decoration: none; /*outline: 2px dashed orange;*/
}
#footerlinks a:hover {
 opacity: 0.7;
 font-style: normal;
    font-weight: 100;
    font-size: 12px;
 text-decoration: none;
 /*outline: 2px dashed orange;*/
}
#footersocialmedia {
  display:flex;
  align-items:center;
  justify-content:center;
  flex-direction:row;
  flex-wrap:wrap;
}
 /* Style all font awesome icons */
.fa {
  padding: 20px;
  font-size: 30px;
  text-align: center;
  text-decoration: none;
}

/* Add a hover effect if you want */
.fa:hover {
  opacity: 0.7;
}

/* Set a specific color for each brand */

/* Facebook */
.fa-facebook {
  background: #3B5998;
  color: white;
}

/* Twitter */
.fa-twitter {
  background: #55ACEE;
  color: white;
}
.fa-youtube {
  background: #bb0000;
  color: white;
}

.fa-instagram {
  background: #125688;
  color: white;
}```

Body:
So im pretty happy with my footer now and its fairly responsive. The Problem: its pretty glitchy. When resizing the window, the text and the links will stack on each other and so on. Can someone help me to fix this? I would love if the middle links would stay side by side and also the social media links to stay in a block.

thank you so much.

.footer {
 position: static;
 flex-shrink: 0;
    bottom: 0px;
    left: 0px;
    right: 0px;
    padding: 0px;
    width: 100%;
    background-color: #F9F9F9;
    text-align: center;
 box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
 z-index: 99;
    /*outline: 2px dashed orange;*/
}
.footerline {
 padding: 50px;
    display: flex;
    font-family: 'Source Code Pro', monospace;
    font-style: normal;
    font-weight: 400;
    font-size: 15px;
    color: #D5D5D5;
    justify-content: center;
    align-items: center;
    /*outline: 2px dashed orange;*/
}
#footerlineshadow {
 color: rgba(240,240,240, 0.9);
    text-shadow: 1px 1px 1px #fff, 0 0 0 #000, 1px 1px 1px #fff;
}
.subfooter {
    height: 40px;
    background-color: #E5E5E5;
    box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
}
.footercontent {
    display: flex;
    font-family: lato;
    color: #ABABAB;
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    text-align: center;
    justify-content: center;
    height: 100%;
}
#footertext {
 text-align: center;
 margin-right: 20%;
 /*outline: 2px dashed orange;*/
}
#footerlinks {
 text-align: center;
 /*outline: 2px dashed orange;*/

}
#footerlinks a {
    margin: 0px 40px;
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    color: #ABABAB;
    text-decoration: none; /*outline: 2px dashed orange;*/
}
#footerlinks a:hover {
 opacity: 0.7;
 font-style: normal;
    font-weight: 100;
    font-size: 12px;
 text-decoration: none;
 /*outline: 2px dashed orange;*/
}
#footersocialmedia {
 margin-left: 20%;
}
 /* Style all font awesome icons */
.fa {
  padding: 5px;
  font-size: 30px;
  width: 25px;
 height: 100%;
  text-align: center;
  text-decoration: none;
}

/* Add a hover effect if you want */
.fa:hover {
  opacity: 0.7;
}

/* Set a specific color for each brand */

/* Facebook */
.fa-facebook {
  background: #3B5998;
  color: white;
}

/* Twitter */
.fa-twitter {
  background: #55ACEE;
  color: white;
}
.fa-youtube {
  background: #bb0000;
  color: white;
}

.fa-instagram {
  background: #125688;
  color: white;
}

<link rel="stylesheet" type="text/css" id="applicationStylesheet" href="header_footer.css"/>
<link rel="stylesheet" type="text/css" id="mainStylesheet" href="kontakt.css"/>
<link href="http://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

&ltp&gtThis is a Footer&lt/p&gt

Copyright © 2020 Henning Frenzel

    Home
    Über Mich
         Portfolio
         Kontakt
    Impressum


问:
What exactly is the `#:~:text=` location hash in an URL?
Today I noticed that some searches on Google gave me links to results with apparent instructions to highlight text.

Google brought me to What is the maximum size of a zip file on Windows 10 Pro 64... at the following url:

https://superuser.com/questions/1305867/what-is-the-maximum-size-of-a-zip-file-on-windows-10-pro-64-bit#:~:text=4%20GB%20size%20is%20a,about%2016%20exabytes%20size%20limitation

I experimented a little bit further and this seems to be a feature of Google Chrome. It highlights text on the page if you append #:~:text=something to the URL. https://example.com/#:~:text=domain seems to work fine, but only on Chrome (Chrome Beta on the left, Firefox on the right).

The word text together with different characters is a bit hard to google, so I couldn't find anything on the subject.

For finding out more information about these kinds of "URL-hacks" I want to know:

What is this feature of Google Chrome called?

答:
Scroll To Text Fragment

OK, with the help of a friend and at the same time via a comment from Berto99 I found it:

Apparently this is a feature called Scroll To Text Fragment. It is enabled by default since Chrome 80, but apparently not yet implemented in other browsers.

There are quite nice examples in the "W3C Community Group Draft Report". More good examples can be found on Wikipedia.

Highlighting the first appearance of a certain text

Just append #:~:text=<text> to the URL. The text search is not case-sensitive.

Example: https://example.com#:~:text=domain

Highlighting a whole section of text

You can use #:~:text=<first word>,<last word> to highlight a whole section of text.

Example: https://stackoverflow.com/questions/62161819/what-exactly-is-the-text-location-hash-in-an-url/62162093#:~:text=Apparently,Wikipedia

More advanced techniques

Prefixing and suffixing like the example suggested in the repository for the suggestion https://en.wikipedia.org/wiki/Cat#:~:text=Claws-,Like%20almost,the%20Felidae%2C,-cats texts as proposed don't seem to work for me (yet? I use Chrome 83).

You can style the look of the highlighted text with the CSS :target and you can opt your website out so this feature does not work with it anymore.


问:
R Plot multiple tracks on PlotOnStaticMap
Here's sample code to generate plots of flights, one flight at a time.  How to modify the code to generate all four flights on one plot?  And can a legend be added with distinct colors?</p>

```<code>df <- data.frame(ICAO = c("A00050", "A00050", "A0020A", "A0020A", "A01021", "A01021", "A011AC", "A011AC"), ctime = as.POSIXct(x=c(1525202775.476, 1525202948.119, 1525178454.322, 1525179000.436, 1525181853, 1525182442.667, 1525204759.544, 1525205007.605), origin = "1970-01-01",tz = "US/Eastern"), Lat = c(38.887207, 39.099923, 38.700256, 39.098923, 38.700348, 39.097874, 38.700989, 39.0932), Long = c(-76.79933, -76.405518, -76.011538, -75.264946, -76.740457, -75.671875, -76.237, -75.8515))

library(spacetime)
library(adehabitatLT)
library(RgoogleMaps)

d <- df[df$ICAO == df$ICAO[1], ]  # Can use 1, 3, 5, and 7 to get the four flights
coordinates(d) <- ~Long+Lat
proj4string(d) <- CRS("+proj=longlat +datum=WGS84")
## convert to a STTDF class:
gpx.ltraj <- as.ltraj(coordinates(d), d$ctime, id = "th")
gpx.st <- as(gpx.ltraj, "STTDF")
## Google maps plot:
llc <- c(mean(gpx.st@sp@bbox[2,]), mean(gpx.st@sp@bbox[1,]))
MyMap <- GetMap.bbox(center=llc, zoom=8, destfile="map.png")
PlotOnStaticMap(MyMap, lat=gpx.st@sp@coords[,2], lon=gpx.st@sp@coords[,1], FUN=lines, col="black", lwd=4)```

</code>```

答:
Here is some sample code that adds the lines in a loop. Note that the second flight seems to be plotted over the first one, so the first one is not visible. The colors and legend labels can be changed as desired.

```<code>df <- data.frame(ICAO = c("A00050", "A00050", "A0020A", "A0020A", "A01021", "A01021", "A011AC", "A011AC"), ctime = as.POSIXct(x=c(1525202775.476, 1525202948.119, 1525178454.322, 1525179000.436, 1525181853, 1525182442.667, 1525204759.544, 1525205007.605), origin = "1970-01-01",tz = "US/Eastern"), Lat = c(38.887207, 39.099923, 38.700256, 39.098923, 38.700348, 39.097874, 38.700989, 39.0932), Long = c(-76.79933, -76.405518, -76.011538, -75.264946, -76.740457, -75.671875, -76.237, -75.8515))

library(spacetime)
library(adehabitatLT)
library(RgoogleMaps)

for(i in c(1,3,5,7)){

  d <- df[df$ICAO == df$ICAO[i], ]  # Can use 1, 3, 5, and 7 to get the four flights
  coordinates(d) <- ~Long+Lat
  proj4string(d) <- CRS("+proj=longlat +datum=WGS84")
  ## convert to a STTDF class:
  gpx.ltraj <- as.ltraj(coordinates(d), d$ctime, id = "th")
  gpx.st <- as(gpx.ltraj, "STTDF")
  ## Google maps plot:
  llc <- c(mean(gpx.st@sp@bbox[2,]), mean(gpx.st@sp@bbox[1,]))
  MyMap <- GetMap.bbox(center=llc, zoom=8, destfile="map.png")
  PlotOnStaticMap(MyMap, lat=gpx.st@sp@coords[,2]
                  , lon=gpx.st@sp@coords[,1], FUN=lines
                  , col=c("black",'blue','red','gray')[(i+1)/2]
                  , lwd=4
                  ,add=ifelse(i==1,F,T))

}

legend('topright'
       ,legend=df$ICAO[c(1,3,5,7)]
       ,lwd=4
       ,col=c("black",'blue','red','gray')
       ,lty=1)
</code>```

Body:
Here's sample code to generate plots of flights, one flight at a time.  How to modify the code to generate all four flights on one plot?  And can a legend be added with distinct colors?

df <- data.frame(ICAO = c("A00050", "A00050", "A0020A", "A0020A", "A01021", "A01021", "A011AC", "A011AC"), ctime = as.POSIXct(x=c(1525202775.476, 1525202948.119, 1525178454.322, 1525179000.436, 1525181853, 1525182442.667, 1525204759.544, 1525205007.605), origin = "1970-01-01",tz = "US/Eastern"), Lat = c(38.887207, 39.099923, 38.700256, 39.098923, 38.700348, 39.097874, 38.700989, 39.0932), Long = c(-76.79933, -76.405518, -76.011538, -75.264946, -76.740457, -75.671875, -76.237, -75.8515))

library(spacetime)
library(adehabitatLT)
library(RgoogleMaps)

d <- df[df$ICAO == df$ICAO[1], ]  # Can use 1, 3, 5, and 7 to get the four flights
coordinates(d) <- ~Long+Lat
proj4string(d) <- CRS("+proj=longlat +datum=WGS84")
## convert to a STTDF class:
gpx.ltraj <- as.ltraj(coordinates(d), d$ctime, id = "th")
gpx.st <- as(gpx.ltraj, "STTDF")
## Google maps plot:
llc <- c(mean(gpx.st@sp@bbox[2,]), mean(gpx.st@sp@bbox[1,]))
MyMap <- GetMap.bbox(center=llc, zoom=8, destfile="map.png")
PlotOnStaticMap(MyMap, lat=gpx.st@sp@coords[,2], lon=gpx.st@sp@coords[,1], FUN=lines, col="black", lwd=4)```

Body:
Here is some sample code that adds the lines in a loop. Note that the second flight seems to be plotted over the first one, so the first one is not visible. The colors and legend labels can be changed as desired.

df <- data.frame(ICAO = c("A00050", "A00050", "A0020A", "A0020A", "A01021", "A01021", "A011AC", "A011AC"), ctime = as.POSIXct(x=c(1525202775.476, 1525202948.119, 1525178454.322, 1525179000.436, 1525181853, 1525182442.667, 1525204759.544, 1525205007.605), origin = "1970-01-01",tz = "US/Eastern"), Lat = c(38.887207, 39.099923, 38.700256, 39.098923, 38.700348, 39.097874, 38.700989, 39.0932), Long = c(-76.79933, -76.405518, -76.011538, -75.264946, -76.740457, -75.671875, -76.237, -75.8515))

library(spacetime)
library(adehabitatLT)
library(RgoogleMaps)

for(i in c(1,3,5,7)){

  d <- df[df$ICAO == df$ICAO[i], ]  # Can use 1, 3, 5, and 7 to get the four flights
  coordinates(d) <- ~Long+Lat
  proj4string(d) <- CRS("+proj=longlat +datum=WGS84")
  ## convert to a STTDF class:
  gpx.ltraj <- as.ltraj(coordinates(d), d$ctime, id = "th")
  gpx.st <- as(gpx.ltraj, "STTDF")
  ## Google maps plot:
  llc <- c(mean(gpx.st@sp@bbox[2,]), mean(gpx.st@sp@bbox[1,]))
  MyMap <- GetMap.bbox(center=llc, zoom=8, destfile="map.png")
  PlotOnStaticMap(MyMap, lat=gpx.st@sp@coords[,2]
                  , lon=gpx.st@sp@coords[,1], FUN=lines
                  , col=c("black",'blue','red','gray')[(i+1)/2]
                  , lwd=4
                  ,add=ifelse(i==1,F,T))

}

legend('topright'
       ,legend=df$ICAO[c(1,3,5,7)]
       ,lwd=4
       ,col=c("black",'blue','red','gray')
       ,lty=1)


问:
How to detect if ancestor is focused in tvOS?
I have a custom UIView subclass and want to detect when its ancestor is in focus. But this class itself cannot be focused.

Basically, I want to do something similar to UIImageView when adjustsImageWhenAncestorFocused is set to true.

I'm hoping for a solution that doesn't require the ancestor to communicate when focus changes.

答:
We can't use didUpdateFocus(in:with:), because it isn't called for all views of hierarchy, from the documentation:

the focus engine calls this method on all focus environments that contain either the previously focused view, the next focused view, or both

So if the view return false for canBecomeFocused, this method can't be called on it.

The adequate way is to observe UIFocusSystem.didUpdateNotification, if you're using Combine it's something like this:

```<code>NotificationCenter.default.publisher(for: UIFocusSystem.didUpdateNotification).sink { [weak self] notification in
    guard let context = notification.userInfo?[UIFocusSystem.focusUpdateContextUserInfoKey] as? UIFocusUpdateContext,
        let next = context.nextFocusedView, self?.isDescendant(of: next) ?? false else {
            print("is NOT descendant")
            return
    }

    print("is descendant")
}.store(in: &cancelBag)
</code>```

Body:
We can't use didUpdateFocus(in:with:), because it isn't called for all views of hierarchy, from the documentation:

the focus engine calls this method on all focus environments that contain either the previously focused view, the next focused view, or both

So if the view return false for canBecomeFocused, this method can't be called on it.

The adequate way is to observe UIFocusSystem.didUpdateNotification, if you're using Combine it's something like this:

NotificationCenter.default.publisher(for: UIFocusSystem.didUpdateNotification).sink { [weak self] notification in
    guard let context = notification.userInfo?[UIFocusSystem.focusUpdateContextUserInfoKey] as? UIFocusUpdateContext,
        let next = context.nextFocusedView, self?.isDescendant(of: next) ?? false else {
            print("is NOT descendant")
            return
    }

    print("is descendant")
}.store(in: &cancelBag)


问: Using Emotion, new

答:
It is expected behavior, CSS-in-JS (like emotion), generates className on every unique style.

By frequently using a dynamic value like in your case, you will overflow your memory with such styles.

Instead, use style or css prop.

```<code><DynamicStyleContainer style={{ width: app.Dimensions }}>
  <div id="app" css={app} onClick={increase}></div>
</DynamicStyleContainer>;
</code>```

In styled-components you get a warning for it, don't know about warning in emotion but the fix is the same.

Over 200 classes were generated for component Component. Consider using style property for frequently changed styles.

Title: Using Emotion, new <style> is getting outputted in the <head> every time component's style is dynamically updated

Body:
I noticed that new Emotion 's are getting outputted in the  every time I update my style dynamically.

Follow an example in which every time DynamicStyleContainer is clicked, a new  is created in the head.

import { css } from "@emotion/core";
import styled from "@emotion/styled";

import React from "react";
import _ from "lodash";

const app = css`
  width: 1000px;
  background-color: pink;
  height: 100px;
`;

const dynamicStyle = (props) => ({
  width: props.appDimensions + "px",
});

const DynamicStyleContainer = styled.div`
  ${dynamicStyle};
`;

export default function App() {
  const [appDimensions, setAppDimensions] = React.useState(1);

  const increase = () => {
    setAppDimensions(appDimensions + 1);
  };

  return (
    <DynamicStyleContainer appDimensions={appDimensions}>

    </DynamicStyleContainer>
  );
}

Inspecting the head element:

I read the documentation and some examples and all seem to do something like this. Is this a normal behavior?

Body:
It is expected behavior, CSS-in-JS (like emotion), generates className on every unique style.

By frequently using a dynamic value like in your case, you will overflow your memory with such styles.

Instead, use style or css prop.

<DynamicStyleContainer style={{ width: app.Dimensions }}>
  <div id="app" css={app} onClick={increase}></div>
</DynamicStyleContainer>;

In styled-components you get a warning for it, don't know about warning in emotion but the fix is the same.

Over 200 classes were generated for component Component. Consider using style property for frequently changed styles.


问:
Tensorflow Float16 for VGG19 model parameters
I'm doing neural style transfer using TensorFlow(with the 19.01 Nvidia TensorFlow Docker image) in Python. I have an Nvidia 2070 graphics card, and I've been getting Out of Memory errors when I try to run a newer version of the TensorFlow docker image(19.08 for example). So I decided that perhaps it is time to consider using 16 bit precision instead of 32 bit for storing the parameters of the VGG19 CNN.

My initial research when I built my machine had led me to believe that switching from 32 to 16 was a cakewalk, but that hasn't been my experience now that I'm actively trying to make the transition.

This is what I have done:

I set tf.keras.backend.set_floatx('float16')

Set tf.keras.backend.set_epsilon(1e-4)

Change my image input to the VGG19 network to a float16, and any other miscellaneous parts of my code that use the float32 datatype in conjunction with the float16.

When I run the code, nvidia-smi still reports that essentially 100% of my GPU is being used. Has anyone had any success with reducing their model memory footprint by switching to float16 in TensorFlow?

答:
TensorFlow has various ways of managing mixed precision. The most suitable mixed precision approach depends on which optimizer you plan to use. Keras optimizers, for example, have an API designed to easily port code one way or the other. It is called mixed_precision.

If you are using a TFv1 optimizer, or one of the other non keras optimizers offered by TensorFlow, you can use their graph rewrite function to convert various pieces of the graph to float 16.


问:
Draw a circle with rectangles python turtle
I wanna draw (this shape) polygon with knowing rectangle length and width, and number of rectangles,

And Here's my code:

```<code>from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    circle(50, 180/num_of_rectangles, 4)
    pendown()

done()
</code>```

But this code doesn't display the wanted shape, So how can i draw the shape above?

答:
You're using the wrong number of rectangles (you only need 6, not 8) and the wrong aspect ratio for your rectangles.  (It's closer to 50x32 than 50x20.) Some of the other proposed solutions inherit these same errors, use too much code to solve the problem, and don't look like the provided image:

```<code>from turtle import Screen, Turtle

WIDTH, HEIGHT = 200, 130
RADIUS = 120
PEN_WIDTH = 8

turtle = Turtle()
turtle.hideturtle()
turtle.width(PEN_WIDTH)

for _ in range(6):
    turtle.penup()
    turtle.circle(RADIUS, extent=30)
    turtle.pendown()

    turtle.left(57)

    for _ in range(2):
        turtle.forward(WIDTH)
        turtle.left(90)
        turtle.forward(HEIGHT)
        turtle.left(90)

    turtle.right(57)

screen = Screen()
screen.exitonclick()
</code>```

To change the size of the image, multiply or divide the WIDTH, HEIGHT, RADIUS and PEN_WIDTH by the same factor.

Body:
I wanna draw (this shape) polygon with knowing rectangle length and width, and number of rectangles,

And Here's my code:

from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    circle(50, 180/num_of_rectangles, 4)
    pendown()

done()

But this code doesn't display the wanted shape, So how can i draw the shape above?

Body:
You're using the wrong number of rectangles (you only need 6, not 8) and the wrong aspect ratio for your rectangles.  (It's closer to 50x32 than 50x20.) Some of the other proposed solutions inherit these same errors, use too much code to solve the problem, and don't look like the provided image:

from turtle import Screen, Turtle

WIDTH, HEIGHT = 200, 130
RADIUS = 120
PEN_WIDTH = 8

turtle = Turtle()
turtle.hideturtle()
turtle.width(PEN_WIDTH)

for _ in range(6):
    turtle.penup()
    turtle.circle(RADIUS, extent=30)
    turtle.pendown()

    turtle.left(57)

    for _ in range(2):
        turtle.forward(WIDTH)
        turtle.left(90)
        turtle.forward(HEIGHT)
        turtle.left(90)

    turtle.right(57)

screen = Screen()
screen.exitonclick()

To change the size of the image, multiply or divide the WIDTH, HEIGHT, RADIUS and PEN_WIDTH by the same factor.


问:
How can I count the unique numbers in an array without rearranging the array elements?
I am having trouble counting the unique values in an array, and I need to do so without rearranging the array elements.

How can I accomplish this?

答:
O(n) running time max_value memory usage</p>

```<code>boolean[] data = new boolean[maxValue];
for (int n : list) {
   if (data[n]) counter++
   else data[n] = true;
}
</code>```

OwnerDisplayName: jarus

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: MarkJ

Body:
O(n) running time max_value memory usage

boolean[] data = new boolean[maxValue];
for (int n : list) {
   if (data[n]) counter++
   else data[n] = true;
}

OwnerDisplayName: Jimmy Jazz


问:
Is calling a function considered a context switching?
When I call a function as below

```<code>void main(void){
    Function();
}
</code>```

Is it considered context switching because I save registers before go to the function ?

答: No, context switch occurs when the kernel swaps a process. calling a user space function will leave you inside the same process, and therefore wont be context switch. calling a kernel function however, requires an operation from the kernel and therefore it is a context switch to the kernel.

OwnerDisplayName: Amr Tarek

Body:
When I call a function as below

void main(void){
    Function();
}

Is it considered context switching because I save registers before go to the function ?

OwnerDisplayName: nir shahar


答:
Context Switching?

When we multitask, what we really do is constantly switch from one task to another. That is what context switching is.

The term originates from computer science. A CPU running multi-threaded processes temporarily puts on hold an execution of a given thread while running another one.

Calling a function does not switch processes except for kernel processes

Title: Is calling a function considered a context switching?

OwnerDisplayName: David Kariuki


问:
In python, what does this do: tan_y[:-1][np.diff(tan_y) < 0]
While learning how to simply graph a tan function using matplotlib I stumbled upon this line of code tan_y[:-1][np.diff(tan_y) < 0] which I found online. I just want to know what each part of the code does

```<code>import matplotlib.pyplot as plt
import numpy as np

#In Degrees
x = np.linspace(0,360,600)
tan_y = np.tan(x*(np.pi/180))
tan_y[:-1][np.diff(tan_y) < 0] = np.nan #Not quite sure what the start of this function does

plt.plot(x,tan_y,linewidth = 3) #Plot tan function

plt.ylim(-20,20)
plt.xlabel('X', fontweight = 'bold', fontsize = 12)
plt.ylabel(r'$\sin(x)$', fontweight = 'bold', fontsize = 12)
plt.title('Wave', fontweight = 'bold', fontsize = 14)
plt.grid(True)
plt.show()
</code>```

答:
Program syntax explanation

tan_y is a numpy.dnarray, it represents the ordinates of the mathematical tan function, previously defined. It is a 600 element long array.

tan_y[:-1] extracts each element of the array, until the last, excluded. Since, in Python, the stop element of a loop is exclusive, this is a way to drop the last element of an array, see this example:

```<code>for i in range(5):
    print(i)

0
1
2
3
4
</code>```

Number 5 it is not printed because it is the stop element of the loop.

So, tan_y[:-1] is a way to remove the last element of this array, therefore tan_y[:-1] is 599 element long.

np.diff(tan_y) calculates the 'derivative' of tan_y, see the documentation. It takes the i-th element and subtracts the previous one (i-1)-th, as in this example:

```<code>import numpy as np

x = np.array([0, 1, 2, 5, 8, 4, -1])
dx = np.diff(x)

print(dx)

[ 1  1  3  3 -4 -5]
</code>```

As you can see, the results is an array in which each element is the result of a difference between each element of x and its previous. Important note: the result dx is 1 element shorter then x, because of the way the calculation is done. This is the reason why you need to remove the last element of the tan_y at the previous point: tan_y and np.diff(tan_y) have to have the same length in order to be compared. In this case both are 599 element long.

np.diff(tan_y) < 0 generates a boolean array of the same length of np.diff(tan_y), in this case 599, where:

if a i-th element of np.diff(tan_y) is positive, the i-th element of np.diff(tan_y) < 0 is set to False

if a i-th element of np.diff(tan_y) is negative, the i-th element of np.diff(tan_y) < 0 is set to True

This is a way to create a filter: an array of True and False according to a specified condition.

tan_y[:-1][np.diff(tan_y) < 0] applies the filter you created at the point 4. to the array you generated in the point 2. In order to do this, both arrays have to have the same length, 599 element long in this case.

tan_y[:-1][np.diff(tan_y) < 0] = np.nan sets to NaN the elements of tab_y where its derivative is negative.

Mathematical meaning

So far so good? If I have not lost you in the explanation of the Python language, we move forward to the mathematical part.

I assume you know that tan(x) is a increasing monotone function. This means it is rising in all its domain. In other words, its derivative must be always positive in its domain.

If you try to run the code, without that line of code, you will see something like this:

What are those vertical lines in correspondence of the asymptotes of the function? This appens because plt.plot() does not know it is plotting a tan(x), which has asymptotes. plt.plot() simply draws a line between each point of the curve you specify.

In order to better understanding this, I replot the previuos plot, with a small number of points (30) and this options:

```<code>plt.plot(x,tan_y,'o-',linewidth = 2)
</code>```

This is what I get:

Pretty ugly, uh? Usually, if you want to hide the dust under the carpet, you increase the number of points, this improves the resolution of the curve. Despite this, the vertical lines remain. So, the line

```<code>tan_y[:-1][np.diff(tan_y) < 0] = np.nan
</code>```

is a way to set to NaN the values of tan_y when its derivative is negative: exactly in correspondence of the vertical lines, so as to remove them!

With this filter, the graph becomes:

a clean, smooth tan(x) graph without its asymptotes.

Body:
While learning how to simply graph a tan function using matplotlib I stumbled upon this line of code tan_y[:-1][np.diff(tan_y) < 0] which I found online. I just want to know what each part of the code does

import matplotlib.pyplot as plt
import numpy as np

#In Degrees
x = np.linspace(0,360,600)
tan_y = np.tan(x*(np.pi/180))
tan_y[:-1][np.diff(tan_y) < 0] = np.nan #Not quite sure what the start of this function does

plt.plot(x,tan_y,linewidth = 3) #Plot tan function

plt.ylim(-20,20)
plt.xlabel('X', fontweight = 'bold', fontsize = 12)
plt.ylabel(r'$\sin(x)$', fontweight = 'bold', fontsize = 12)
plt.title('Wave', fontweight = 'bold', fontsize = 14)
plt.grid(True)
plt.show()

Body:
Program syntax explanation

tan_y is a numpy.dnarray, it represents the ordinates of the mathematical tan function, previously defined. It is a 600 element long array.

tan_y[:-1] extracts each element of the array, until the last, excluded. Since, in Python, the stop element of a loop is exclusive, this is a way to drop the last element of an array, see this example:

for i in range(5):
    print(i)

0
1
2
3
4

Number 5 it is not printed because it is the stop element of the loop.

So, tan_y[:-1] is a way to remove the last element of this array, therefore tan_y[:-1] is 599 element long.

np.diff(tan_y) calculates the 'derivative' of tan_y, see the documentation. It takes the i-th element and subtracts the previous one (i-1)-th, as in this example:

import numpy as np

x = np.array([0, 1, 2, 5, 8, 4, -1])
dx = np.diff(x)

print(dx)

[ 1  1  3  3 -4 -5]

As you can see, the results is an array in which each element is the result of a difference between each element of x and its previous. Important note: the result dx is 1 element shorter then x, because of the way the calculation is done. This is the reason why you need to remove the last element of the tan_y at the previous point: tan_y and np.diff(tan_y) have to have the same length in order to be compared. In this case both are 599 element long.

np.diff(tan_y) < 0 generates a boolean array of the same length of np.diff(tan_y), in this case 599, where:

if a i-th element of np.diff(tan_y) is positive, the i-th element of np.diff(tan_y) < 0 is set to False

if a i-th element of np.diff(tan_y) is negative, the i-th element of np.diff(tan_y) < 0 is set to True

This is a way to create a filter: an array of True and False according to a specified condition.

tan_y[:-1][np.diff(tan_y) < 0] applies the filter you created at the point 4. to the array you generated in the point 2. In order to do this, both arrays have to have the same length, 599 element long in this case.

tan_y[:-1][np.diff(tan_y) < 0] = np.nan sets to NaN the elements of tab_y where its derivative is negative.

Mathematical meaning

So far so good? If I have not lost you in the explanation of the Python language, we move forward to the mathematical part.

I assume you know that tan(x) is a increasing monotone function. This means it is rising in all its domain. In other words, its derivative must be always positive in its domain.

If you try to run the code, without that line of code, you will see something like this:

What are those vertical lines in correspondence of the asymptotes of the function? This appens because plt.plot() does not know it is plotting a tan(x), which has asymptotes. plt.plot() simply draws a line between each point of the curve you specify.

In order to better understanding this, I replot the previuos plot, with a small number of points (30) and this options:

plt.plot(x,tan_y,'o-',linewidth = 2)

This is what I get:

Pretty ugly, uh? Usually, if you want to hide the dust under the carpet, you increase the number of points, this improves the resolution of the curve. Despite this, the vertical lines remain. So, the line

tan_y[:-1][np.diff(tan_y) < 0] = np.nan

is a way to set to NaN the values of tan_y when its derivative is negative: exactly in correspondence of the vertical lines, so as to remove them!

With this filter, the graph becomes:

a clean, smooth tan(x) graph without its asymptotes.


问:
Get set of elements from list (Prolog)
I am trying to get a set of elements from a list in prolog, such that a query:

get_elems([1, 2, 4, 10], [a, b, c, d, e], X).

yields:
X = [a, b, d]

I would like to implement it without using the built in predicate nth.
I have tried using the following, but it does not work:

```<code>minus_one([], []).
minus_one([X|Xs], [Y|Ys]) :- minus_one(Xs, Ys), Y is X-1.

get_elems([], _, []).
get_elems(_, [], []).
get_elems([1|Ns], [A|As], Z) :- get_elems(Ns, As, B), [A|B] = Z.
get_elems(Ns, [_|As], Z) :- minus_one(Ns, Bs), get_elems(Bs, As, Z).
</code>```

Edit: The list of indices is guaranteed to be ascending, also I want to avoid implementing my own version of nth.

答:
Give this a go:

```<code>get_elems(Xs,Ys,Zs) :- get_elems(Xs,1,Ys,Zs).

get_elems(Xs,_,Ys,[]) :- Xs = []; Ys = [].
get_elems([N|Xs],N,[H|Ys],[H|Zs]) :- !, N1 is N + 1, get_elems(Xs,N1,Ys,Zs).
get_elems(Xs,N,[_|Ys],Zs) :- N1 is N + 1, get_elems(Xs,N1,Ys,Zs).
</code>```

This just keeps counting up and when the head of the second term is equal to the current index it peels off the head and makes it the head of the current output term. If it doesn't match it just discards the head and keeps going.

Title: Get set of elements from list (Prolog)

Body:
I am trying to get a set of elements from a list in prolog, such that a query:

get_elems([1, 2, 4, 10], [a, b, c, d, e], X).

yields:
X = [a, b, d]

I would like to implement it without using the built in predicate nth.
I have tried using the following, but it does not work:

minus_one([], []).
minus_one([X|Xs], [Y|Ys]) :- minus_one(Xs, Ys), Y is X-1.

get_elems([], _, []).
get_elems(_, [], []).
get_elems([1|Ns], [A|As], Z) :- get_elems(Ns, As, B), [A|B] = Z.
get_elems(Ns, [_|As], Z) :- minus_one(Ns, Bs), get_elems(Bs, As, Z).

Edit: The list of indices is guaranteed to be ascending, also I want to avoid implementing my own version of nth.

Body:
Give this a go:

get_elems(Xs,Ys,Zs) :- get_elems(Xs,1,Ys,Zs).

get_elems(Xs,_,Ys,[]) :- Xs = []; Ys = [].
get_elems([N|Xs],N,[H|Ys],[H|Zs]) :- !, N1 is N + 1, get_elems(Xs,N1,Ys,Zs).
get_elems(Xs,N,[_|Ys],Zs) :- N1 is N + 1, get_elems(Xs,N1,Ys,Zs).

This just keeps counting up and when the head of the second term is equal to the current index it peels off the head and makes it the head of the current output term. If it doesn't match it just discards the head and keeps going.


问:
Finding out the number of days between 2 timestamps in SQL
I'm struggling to work out how to work out the time difference between 2 timestamps

My goal -

A bunch of customers order on XXXX and then proceed to cancel on XXXX (different dates), I'm interested in finding out how many customers cancel within a year. So if a customer were to cancel on day 366 they wouldn't appear in my results.

I tried a few different functions, the nearest one I could find was INTERVAL

example -
WHERE cancel date >= order_date (within 365 days)

I hope this makes sense and I'm not missing anything glaringly obvious!

Cheers
Olly (an amateur)

答:
You have to be very careful about what you call "a year". For example, consider the following data:

```<code>insert into some_table (id, order_date, cancel_date)
  values (1, now() - interval '30 day', now() - interval '10 day'),
         (2, now() - interval '2 year', now() - interval '18 month'),
         (3, now() - interval '3 year', now() - interval '1 year'),
         (4, date '2016-02-29',         date '2017-03-01'),
         (5, date '2016-02-29',         date '2017-02-28'),
         (6, date '2019-02-28',         date '2020-02-29'),
         (7, date '2016-02-01',         date '2017-02-01')
</code>```

Now, depending on the definition of "one year" you choose you can have 2, 3, 4, 6, and perhaps other combinations of the above satisfy your selection criteria.

For example, if you choose to use interval '1 year' as shown here

```<code>select *
  from some_table t
  where t.cancel_date <= t.order_date + interval '1 year';
</code>```

you'll find that the rows with id values of 1, 2, 5, and 7 are chosen.

If you replace the interval above with interval '364 day' then only the rows with id's of 1 and 2 are chosen.

Using an interval of interval '365 day' chooses rows 1, 2, and 5.

And using an interval of interval '366 day' (leap years, y'know :-) picks rows 1, 2, 4, 5, 6, and 7.

And then you can change <= to < and increase the confusion level even more!

So you have options. Choose wisely... :-)

db<>fiddle here

Body:
You have to be very careful about what you call "a year". For example, consider the following data:

insert into some_table (id, order_date, cancel_date)
  values (1, now() - interval '30 day', now() - interval '10 day'),
         (2, now() - interval '2 year', now() - interval '18 month'),
         (3, now() - interval '3 year', now() - interval '1 year'),
         (4, date '2016-02-29',         date '2017-03-01'),
         (5, date '2016-02-29',         date '2017-02-28'),
         (6, date '2019-02-28',         date '2020-02-29'),
         (7, date '2016-02-01',         date '2017-02-01')

Now, depending on the definition of "one year" you choose you can have 2, 3, 4, 6, and perhaps other combinations of the above satisfy your selection criteria.

For example, if you choose to use interval '1 year' as shown here

select *
  from some_table t
  where t.cancel_date <= t.order_date + interval '1 year';

you'll find that the rows with id values of 1, 2, 5, and 7 are chosen.

If you replace the interval above with interval '364 day' then only the rows with id's of 1 and 2 are chosen.

Using an interval of interval '365 day' chooses rows 1, 2, and 5.

And using an interval of interval '366 day' (leap years, y'know :-) picks rows 1, 2, 4, 5, 6, and 7.

And then you can change <= to < and increase the confusion level even more!

So you have options. Choose wisely... :-)

db<>fiddle here


问:
Comparing iterators crashes program without errors in custom bubble sort implementation
I'm relatively new to C++. I have been trying to use iterators to sort a vector. I'm using bubble sort. I don't want to know if my bubble sort implementation works or not, I just want to know what's crashing my program.

```<code>template<typename iter>
void bubbleSort(iter start, iter end) {
    for (iter &j = end; j != start; j--) {
        for (iter &i = start; i != end; i++) {
            // std::cout << *i << std::endl;
            if (*i > *(i + 1)) { // this line is where it stops
                std::iter_swap(i, i + 1);
            }
        }
    }

    std::cout << "ended"; // this line never gets called
}
</code>```

When the program stops, though, it doesn't show any exceptions. I also try-catched the part where it stopped, but it didn't go in the try catch. Also, whenever I un-comment the first printing line:

```<code>std::cout << *i << std::endl;
</code>```

It prints 1168169449 forever. What is going wrong here?

I'm testing it like this:

```<code>std::vector<int> vector = {1, 2, 3, 6, 4, 5};
std::vector<int> temp = vector;
//std::sort(temp.begin(), temp.end());
bubbleSort(vector.begin(), vector.end());
for(auto& num : vector) {
    std::cout << num << std::endl;
}
</code>```

答:
In that line you are dereferencing i + 1, in the last iteration of the cycle it will dereference .end() which invokes undefined behavior, .end() is one past the last element, it can't be dereferenced.

Quick fix is to make your stop condition i != end - 1.

This, though will not fix the the bubble sort implementation which would still be flawed for more complex sequences, take this sample vector:

```<code>std::vector<int> vector = {1, 2, 7, 3, 6, 4, 5};
</code>```

As you can see here, it will not be sorted correctly.

A possible correction would be:

Demo

```<code>template<typename iter>
void bubbleSort(iter start, iter end) {
    for (iter i = start + 1; i != end; i++) {
        for (iter j = start; j != end - 1; j++) {
            if (*i < *j) {
                std::iter_swap(i, j);
            }
        }
    }
    std::cout << "ended" << std::endl;
}
</code>```

This version, though it works as intended, could be optimized, you could do away with one of the copies at the cost of a slightly less readable code and optimize the number of iterations:

```<code>template<typename iter>
void bubbleSort(iter start, iter end) {
    while(start != end) {
        for (iter j = start; j != end; j++) {
            if (*start > *j) {
                std::iter_swap(start, j);
            }
        }
        start++;
    }
    std::cout << "ended" << std::endl;
}
</code>```

Another thing you could do is to add a condition do to avoid dereferencing and comparing values in the same position, removing some overhead whith less indirection calls.

```<code>//...
if(start == j){ // will compare the iterators and skip the loop if they are equal
    continue;
}
//...
</code>```

All things considered, I would use something like this:

```<code>template<typename iter>
void bubbleSort(iter start, iter end) {
    for (iter i = start; i != end; i++) {
        for (iter j = i; j != end; j++) {
            if(i == j) {
                continue;
            }
            if (*i > *j) {
                std::iter_swap(i, j);
            }
        }
    }
    std::cout << "ended" << std::endl;
}
</code>```

As said in the linked thread, performance is deppendant of several factors among which are the CPU architecture, the SO or the compiler, you must test these solutions and see which one gives you the best performance.

You can also use your compiler optimization options to adjust the compilation to your needs.

Body:
I'm relatively new to C++. I have been trying to use iterators to sort a vector. I'm using bubble sort. I don't want to know if my bubble sort implementation works or not, I just want to know what's crashing my program.

template<typename iter>
void bubbleSort(iter start, iter end) {
    for (iter &j = end; j != start; j--) {
        for (iter &i = start; i != end; i++) {
            // std::cout << *i << std::endl;
            if (*i > *(i + 1)) { // this line is where it stops
                std::iter_swap(i, i + 1);
            }
        }
    }

    std::cout << "ended"; // this line never gets called
}

When the program stops, though, it doesn't show any exceptions. I also try-catched the part where it stopped, but it didn't go in the try catch. Also, whenever I un-comment the first printing line:

std::cout << *i << std::endl;

It prints 1168169449 forever. What is going wrong here?

I'm testing it like this:

std::vector<int> vector = {1, 2, 3, 6, 4, 5};
std::vector<int> temp = vector;
//std::sort(temp.begin(), temp.end());
bubbleSort(vector.begin(), vector.end());
for(auto& num : vector) {
    std::cout << num << std::endl;
}

Body:
In that line you are dereferencing i + 1, in the last iteration of the cycle it will dereference .end() which invokes undefined behavior, .end() is one past the last element, it can't be dereferenced.

Quick fix is to make your stop condition i != end - 1.

This, though will not fix the the bubble sort implementation which would still be flawed for more complex sequences, take this sample vector:

std::vector<int> vector = {1, 2, 7, 3, 6, 4, 5};

As you can see here, it will not be sorted correctly.

A possible correction would be:

Demo

template<typename iter>
void bubbleSort(iter start, iter end) {
    for (iter i = start + 1; i != end; i++) {
        for (iter j = start; j != end - 1; j++) {
            if (*i < *j) {
                std::iter_swap(i, j);
            }
        }
    }
    std::cout << "ended" << std::endl;
}

This version, though it works as intended, could be optimized, you could do away with one of the copies at the cost of a slightly less readable code and optimize the number of iterations:

template<typename iter>
void bubbleSort(iter start, iter end) {
    while(start != end) {
        for (iter j = start; j != end; j++) {
            if (*start > *j) {
                std::iter_swap(start, j);
            }
        }
        start++;
    }
    std::cout << "ended" << std::endl;
}

Another thing you could do is to add a condition do to avoid dereferencing and comparing values in the same position, removing some overhead whith less indirection calls.

//...
if(start == j){ // will compare the iterators and skip the loop if they are equal
    continue;
}
//...

All things considered, I would use something like this:

template<typename iter>
void bubbleSort(iter start, iter end) {
    for (iter i = start; i != end; i++) {
        for (iter j = i; j != end; j++) {
            if(i == j) {
                continue;
            }
            if (*i > *j) {
                std::iter_swap(i, j);
            }
        }
    }
    std::cout << "ended" << std::endl;
}

As said in the linked thread, performance is deppendant of several factors among which are the CPU architecture, the SO or the compiler, you must test these solutions and see which one gives you the best performance.

You can also use your compiler optimization options to adjust the compilation to your needs.