I'm trying to optionally set $_url to "not-found" if there's no href.
xidel --trace-stack --ignore-namespaces 'https://www.uline.com/Grp_41/Peanuts-and-Dispensers' --user-agent 'Mozilla/5.0 Firefox/94.0.1' \
-f '//(a[#class="cssa"]|a[#class="subgroupName"])/#href' \
--xml --xquery '
let $title := //(h1|div[#class="item-result-desc"]/a)/text()
return <product>
<title>{$title}</title>
<url>{$url}</url>
{
for $model in //(table[#class="subgroupChart"]|table[#class="item-result-price-grid__table"])//tr[position()>2 and not(contains(#class, "subgroupChartHeader"))]
let $link := $model//td[1]//(a|span)
let $name := $link/text()
let $_url := $link/(string(#href), "not-found")
let $price := $model//(td[contains(#class, "PriceCellwebPrice")][1]//attrib|td[contains(#class, "qtyBreaksPriceColumn")][1]//span)/text()
return <model>
{ if ($name) then
<name>{$name}</name>
else()
}
{ if ($price) then
<price>{$price}</price>
else ()
}
{ if ($_url) then
<url>https://uline.com{$_url}</url>
else ()
}
</model>
}
</product>'
Sometimes its a link sometimes its a span.
I think you want let $_url := $link/(#href/string(), "not-found")[1] as (#href/string(), "not-found") forms the string sequence of the value of any existing href attribute plus the string literal "not-found" and with the [1] it will return the attribute value if one exists or the constant if the attribute doesn't exist.
Related
I have a Search Bar with a UITableView and if I search something in the searchBar it will print the result in the table view.
If I search a name like "Name 01" and I click on this name to get information and later I re-open the Search Bar and I try to search other name like "Name 02" I will see the "Name 01" result in the Table View and I don't know how to clear it.
I have tried to refresh Table View too but without success.
Video of the problem: https://streamable.com/98j0w
The code is this
extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
//print("updateSearchResults")
if searchController.searchBar.text == nil {
seenNames.removeAll()
matchingItems.removeAll()
self.tableView.reloadData()
}
guard let mapView = mapView,
let searchBarText = searchController.searchBar.text else { return }
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { response, _ in
guard let response = response else {
return
}
for (index , name) in response.mapItems.enumerated() {
let item = response.mapItems[index]
if(checkIfItemExistInDatabase(key: String(item.name!)) != nil && !seenNames.contains(name.name!)){
matchingItems.append(item)
seenNames.insert(name.name!)
self.tableView.reloadData()
}
}
}
}
}
I want that If I do a research the tableview result with searchbar text is cleaned and doesn’t show the previously result
Instead of:
if searchController.searchBar.text == nil {
...
...
Try with
let searchText = searchController.searchBar.text
if searchText == nil || searchText.isEmpty {
...
...
And another thing, just before
search.start { response, _ in
add
matchingItems.removeAll()
tableView.reloadData()
I use "text/template" module.
I have struct like this to parse XML from Blogger
type Media struct {
ThumbnailUrl string `xml:"url,attr"`
}
type Entry struct {
ID string `xml:"id"`
Published Date `xml:"published"`
Updated Date `xml:"updated"`
Draft Draft `xml:"control>draft"`
Title string `xml:"title"`
Content string `xml:"content"`
Tags Tags `xml:"category"`
Author Author `xml:"author"`
Media Media `xml:"thumbnail"`
Extra string
}
Then I create Go Template like this
[image]
src = "{{ replace .Media.ThumbnailUrl 's72-c' 's1600' }}"
link = ""
thumblink = "{{ .Media.ThumbnailUrl }}"
alt = ""
title = ""
author = ""
license = ""
licenseLink = ""
The replace function not defined. I want to replace URL from {{ .Media.ThumbnailUrl }}
For example:
from this URL
https://2.bp.blogspot.com/-DEeRanrBa6s/WGWGwA2qW5I/AAAAAAAADg4/feGUc-g9rXc9B7hXpKr0ecG9UOMXU3_VQCK4B/s72-c/pemrograman%2Bjavascript%2B-%2Bpetanikode.png
To this URL
https://2.bp.blogspot.com/-DEeRanrBa6s/WGWGwA2qW5I/AAAAAAAADg4/feGUc-g9rXc9B7hXpKr0ecG9UOMXU3_VQCK4B/s1600/pemrograman%2Bjavascript%2B-%2Bpetanikode.png
You can write a helper view function like this
func replace(input, from,to string) string {
return strings.Replace(input,from,to, -1)
}
funcMap = template.FuncMap{
"replace": replace,
}
template := template.New("").Funcs(internalFuncMap)
and use the template to render the view.
code ref links
https://github.com/sairam/kinli/blob/master/template_funcs.go#L57-L59
https://github.com/sairam/kinli/blob/master/templates.go#L48
I am new to swift.I want to delete white space and also delete new line white space from TextView.So please advice.
Thanks in advance.
For new line or when the enter button is pressed you can use the delegate method
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
add this to the method
if text == "\n"
{
self.view.endEditing(true)
return false
}
For whitespace in the end use the below code.
var stringFromText = textView.text
var lastChar = stringFromText.characters.last
while lastChar == " " {
stringFromText = String(stringFromText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))
print(stringFromText!)
if stringFromText != "" {
lastChar = stringFromText?.characters.last
}
else
{
lastChar = "A" //Any random char
}
print(lastChar!)
}
textComment.text = stringFromText
Hope it helps.
This is Swift 2.1.
How would you go about extracting an amount from a string that looks like "add egg (£2.00)"? In this example, I would need the "2.00" portion.
Would it be a hard-check looking for whatever's enclosed between the brackets? Or is there a more effective way to do so? I.e. regex or something?
'pure' Swift solution, no brackets necessary
let str = ["add egg £ 2.00",
"the price is $12.00 per unit",
"send €10.22 to somebody",
"invalid $(12)"]
func value(str: String, currency: String)->Double {
var chars = str.characters
let currs = currency.characters
while !currs.contains(chars.popFirst() ?? " ") {}
let arr = chars.split(" ")
guard let value = arr.first,
let d = Double(String(value)) else { return Double.NaN }
return d
}
let values = str.flatMap { value($0, currency: "£$€") }
print(values)
/*
[2.0, 12.0, 10.220000000000001, nan]
*/
if you really need the brackets there, no problem ...
let str = ["add egg (£2.00)",
"the price is ($12.00) per unit",
"send (€10.22) to somebody",
"invalid ($-12)"]
func value(str: String, currency: String)->Double {
var chars = str.characters
let currs = currency.characters
while !currs.contains(chars.popFirst() ?? " ") {}
let arr = chars.split(")")
guard let value = arr.first,
let d = Double(String(value)) else { return Double.NaN }
return d
}
let values = str.flatMap { value($0, currency: "£$€") }
print(values)
/*
[2.0, 12.0, 10.220000000000001, -12.0]
*/
There's many ways to achieve what you want - here's a simple example with a regex.
I'm using (?<=\\()[^\\)]+ to find anything between ( and ), then I use a couple of ranges to extract the values: one for the currency symbol, another for the value.
extension String {
func extractValueBetweenParenthesis() -> (currency: String?, value: String?) {
if let range = self.rangeOfString("(?<=\\()[^\\)]+", options: .RegularExpressionSearch) {
let cr = range.startIndex..<range.startIndex.advancedBy(1)
let vr = range.startIndex.advancedBy(1)..<range.endIndex
return (currency: self.substringWithRange(cr), value: self.substringWithRange(vr))
}
return (nil, nil)
}
}
Call the method on a String then safely unwrap the optional results:
let str = "add egg (£2.00)"
let result = str.extractValueBetweenParenthesis()
if let currency = result.currency, value = result.value {
print("Currency is '\(currency)' and value is '\(value)'")
}
Prints:
Currency is '£' and value is '2.00'
var myString = "add egg (£2.00)"
myString = myString.stringByReplacingOccurrencesOfString("", withString: "")
let components = myString.componentsSeparatedByString("add egg (£")
let finalString = components[1].stringByReplacingOccurrencesOfString(")", withString: "")
print(finalString)
//This prints 2.00
I use SwiftLocation for get coordinates:
try! SwiftLocation.shared.currentLocation(Accuracy.House, timeout: 20, onSuccess: { (location) -> Void in
print(location?.description)
}) { (error) -> Void in
print("something went wrong")
}
In location?.description I get it:
<+37.78583400,-122.40641700> +/- 5.00m (speed -1.00 mps / course
-1.00) # 2/22/16, 6:35:55 PM Indochina Time
And I need to take just coordinates. So I make loop for it:
while name.characters.last != ">" { // delete all after ">"
name = String(name.characters.dropLast())
}
name = String(name.characters.dropLast()) // delete ">"
name = String(name.characters.dropFirst()) // delete "<"
name = String(name.characters.dropFirst()) // delete "+"
print(name) // get 37.78583400,-122.40641700
tempMyLat = name
while tempMyLat.characters.last != "," { // delete all after ","
tempMyLat = String(tempMyLat.characters.dropLast())
}
tempMyLon = name
while tempMyLon.characters.first != "," { // delete all before ","
tempMyLon = String(tempMyLon.characters.dropFirst())
}
tempMyLon = String(tempMyLon.characters.dropFirst()) // delete ","
But this code work ONLY for string. When I get location?.description - I can't convert it for type - string, because "location" is a CLLocation type.
So, my question: How convert location?.description to String ?
or
how get only coordinates from the SwiftLocation
Thanks.
In Xcode 10+ and Swift 3, you may have to do something similar to the following:
let myLocation: CLLocation = locations[0] as CLLocations
var myLatitude: String = String(format: "%f", myLocation.coordinate.latitude)
var myLongitude: String = String(format:"%f", myLocation.coordinate.longitude)
If you want to get locations from CLLocation you dont need to convert string from CLLocation object. you can get locations directly from CLLocation object.
Here is an example :
var locationObj = locationArray.lastObject as CLLocation
var coord = locationObj.coordinate
var longitude = coord.longitude //Latitude & Longitude as String
var latitude = coord.latitude
I'd create an extension for CLLocation like this:
extension CLLocation {
/// Provide optional coordinate components labels
func locationString(with labels:[String]? = ["lat","lon"]) -> String {
return "\(latitudeString(with: labels!.first!))- \(longitudeString(with: labels!.last!))"
}
// Get string for each component
//This is not necessary, as you could combine this into formattedLabel: label
//But it's good to have these separate in case you need just one of the components
func latitudeString(with label: String?) -> String {
return "\(formattedLabel(from: label))\(self.coordinate.latitude)"
}
func longitudeString(with label: String?) -> String {
return "\(formattedLabel(from: label))\(self.coordinate.longitude)"
}
// Returns formatted label or nothing in case nothing is needed
func formattedLabel(from label: String?) -> String {
var sortedLabel = ""
if label != nil {
sortedLabel = "\(label!): "
}
return sortedLabel
}
}
And then call it like:
let locationString = someCLLocation.locationString()
// or someCLLocation.locationString(with: ["label 1", "label 2"])