min() function in XQuery - xquery

I want to get the name of the zone, the number of products and the denomination of the product with the minimal stock order by the name of the zone.
I got almost everything except the denomination which prints nothing.
My code:
for $zone in distinct-values(/productos/produc/cod_zona)
let $numero := count(/productos/produc[cod_zona = $zone]/cod_prod)
let $nomzona:=/zonas/zona[cod_zona = $zone]/nombre
let $minimo :=min(/productos/produc[cod_zona = $zone]/stock_minimo)
let $deno :=/productos/produc[stock_minimo=$minimo]/denominacion
order by $nomzona ascending
return concat( 'Zona:', $nomzona,' ',
'Productes:', $numero,' ',
'Mínim stock:', $deno
The result:
Zona:Andalucía Productes:2 Mínim stock: //here must be print like that "Placa base "
Zona:Extremadura-Galicia Productes:3 Mínim stock:
Zona:Levante-Cataluña Productes:4 Mínim stock:
Zona:Madrid-CENTRO Productes:4 Mínim stock:
productos.xml:
<productos>
<TITULO>DATOS DE LA TABLA PRODUCTOS</TITULO>
<produc>
<cod_prod>1010</cod_prod>
<denominacion>Placa Base MSI G41M-P26</denominacion>
<precio>50</precio>
<stock_actual>10</stock_actual>
<stock_minimo>3</stock_minimo>
<cod_zona>10</cod_zona>
</produc>
<produc>
<cod_prod>1011</cod_prod>
<denominacion>Micro Intel Core i5-2320</denominacion>
<precio>120</precio>
<stock_actual>3</stock_actual>
<stock_minimo>5</stock_minimo>
<cod_zona>10</cod_zona>
</produc>
<produc>
<cod_prod>1012</cod_prod>
<denominacion>Micro Intel Core i5 2500</denominacion>
<precio>170</precio>
<stock_actual>5</stock_actual>
<stock_minimo>6</stock_minimo>
<cod_zona>20</cod_zona>
</produc>
<produc>
<cod_prod>1013</cod_prod>
<denominacion>HD Seagate Barracuda 250GB SATA</denominacion>
<precio>80</precio>
<stock_actual>10</stock_actual>
<stock_minimo>5</stock_minimo>
<cod_zona>20</cod_zona>
</produc>
<produc>
the other xml:
zonas.xml:
<zonas>
<TITULO>DATOS DE LA TABLA ZONAS</TITULO>
<zona>
<cod_zona>10</cod_zona>
<nombre>Madrid-CENTRO</nombre>
<director>Pedro Martín</director>
</zona>
<zona>
<cod_zona>20</cod_zona>
<nombre>Extremadura-Galicia</nombre>
<director>Alicia Pérez</director>
</zona>
<zona>
What am I doing wrong?
Thanks/Gracias/Merci

You are not restricting $deno to the current zone, so for producs with the same stock_minimo, this will return a sequence instead of an single item. So you should first add another predicate for zone:
let $deno := /productos/produc[cod_zona = $zone][stock_minimo=$minimo]/denominacion
However, if there were ever two produc in the same zone with the same min(stock_minimo), you will have the same problem, so you can plan for this in your output by using string-join instead of concat:
concat( 'Zona:', $nomzona,' ',
'Productes:', $numero,' ',
'Mínim stock:', string-join($deno, ', ') ...

Related

reading latex accents of .bib in R

When I export .bib references with accents coded in latex (as they are exported from mendeley, for example), then they don't look as expected for further independent processing in R.
myfile.bib:
#misc{Llorens1980,
abstract = {Aunque el reactor de fusi{\'{o}}n termonuclear constituye la esperanza m{\'{a}}s s{\'{o}}lida de obtenci{\'{o}}n de energ{\'{i}}a a gran escala, los problemas f{\'{i}}sicos y tecnol{\'{o}}gicos que el mismo plantea son muchos y dif{\'{i}}ciles.},
author = {Llorens, Mart{\'{i}}n and Menzell, Alfred and Villarrubia, Miguel},
booktitle = {Investigaci{\'{o}}n y Ciencia (Scientific American)},
keywords = {INGENIER{\'{I}}A NUCLEAR},
number = {51},
pages = {1--5},
title = {{F{\'{i}}sica y tecnolog{\'{i}}a del reactor de fusi{\'{o}}n}},
volume = {DICIEMBRE},
year = {1980}
}
In R:
testbibR <- RefManageR::ReadBib("myfile.bib")
testbibR$author
[1] "Mart\\'in Llorens" "Alfred Menzell" "Miguel Villarrubia"
testbibR$title
[1] "{F{\\'{i}}sica y tecnolog{\\'{i}}a del reactor de fusi{\\'{o}}n}"
btex<-bibtex::read.bib("myfile.bib")
btex$author
[1] "Mart\\'in Llorens" "Alfred Menzell" "Miguel Villarrubia"
btex$title
[1] "{F{\\'{i}}sica y tecnolog{\\'{i}}a del reactor de fusi{\\'{o}}n}"
testbib <- bib2df::bib2df("myfile.bib")
testbib$AUTHOR[[1]]
[1] "Llorens, Mart{\\'{i}}n" "Menzell, Alfred" "Villarrubia, Miguel"
testbib$TITLE
[1] "F{\\'{i}}sica y tecnolog{\\'{i}}a del reactor de fusi{\\'{o}}n"
I wonder if I can see a Martín in those places
Related post: https://github.com/ropensci/bib2df/issues/35
By the way, when importing / exporting those bibs, packages seem to rewrite in (other) latex format, the author field (Mart\'in). Only bib2df writes all fields as the original, see above.
RefManageR::WriteBib(testbibR,"refmanager.bib")
bibtex::write.bib(btex,"bibtex.bib")
bib2df::df2bib(testbib,"bib2df")
This is a workaround to remove some latex accents from .bib.
As I based this answer in this post' answer, the first part is in python.
python: Dictionary to .csv
latexAccents = [
[ u"Í", "{\\'{I}}"],
[ u"í", "{\\'{i}}"],
[ u"á", "{\\'{a}}"],
[ u"é", "{\\'{e}}"],
[ u"ó", "{\\'{o}}"],
[ u"ú", "{\\'{u}}"],
]
import pandas
mydf = pandas.DataFrame(latexAccents)
newname = "dictaccent.csv"
mydf.to_csv(newname, index =False)
R: Replace latex in .bib
dictaccent <- read.csv("dictaccent.csv")
bibLines <- readLines("myfile.bib")
library(stringi)
for (i in 1:nrow(dictaccent)){
for (j in 1:length(bibLines)) {
bibLines[j]<-stri_replace_all_fixed(bibLines[j], dictaccent$X1[i], dictaccent$X0[i])
}
}
writeLines(bibLines,"noLatex.bib")
commented in other post

What does the “slot doesn't exist” error message mean?

I'm trying to write an object and access to his parameters. I've got two files, menus.R, where I define the object, and main.R, where I use the object and try to access to a slot (parameter).
The code of both files are next:
menus.R
menu <- setClass("menu", slots=list(competition="numeric", stats="numeric"))
setMethod("show", "menu", function(object){
while (TRUE){
#Clean console
cat("\014")
cat("COMPARATIVA ENTRE EQUIPOS DE LA MISMA COMPETICION\n")
cat("-------------------------------------------------\n\n")
cat("1. Comparativa entre clubes de Liga DIA\n")
cat("2. Comparativa entre clubes de Liga Femenina 2 - Grupo 'A'\n")
cat("3. Comparativa entre clubes de Liga Femenina 2 - Grupo 'B'\n")
cat("0. Salir\n\n")
option <- readline("Selecciona opción: ")
option <- suppressWarnings(as.numeric(option))
if (!is.na(option)){
if (option == 1){
object#competition <- 14
}
if (option == 2){
object#competition <- 22
}
if (option == 3){
object#competition <- 23
}
readline("Espera ...")
if (option == 0)
break
}else{
readline("No es un número. Pulsa una tecla para introducir otra opción.")
}
}
})
main.R
menu(competition=0, stats=0)
print(menu#competition)
getClass(class(menu))
When I call menu(competition=0, stats=0) I can see what the method show gives me to me. This is correct. In show method I assign a value to competition. When I exit from show method the next instruction is print(menu#competition) and here is where I've got this error:
Error in print(menu#competition) : there is no a slot with name
"competition" for this object class "classGeneratorFunction"
Then with getClass(class(menu)) I've got this:
What am I doing wrong? How can I get access to competition or stats?
You are confusing the object constructor with the object itself.
menu(competition = 0, stats=0) generates you a new object of class menu, but you fail to save it somewhere, so it prints on the screen. Therefore your first, correct output.
But then, you want to manipulate the object. But you didn't save it! Instead, you try to manipulate the "object factory", menu(). The Type of the "object factory" is classGeneratorFunction, that's what you see.
This should work:
myMenuObject <- menu(competition=0, stats=0)
print(myMenuObject)
print(myMenuObject#competition)
getClass(class(myMenuObject))

adding numbers with comma in asp

I've got a control panel in simple asp. It has do store basic info in my Microsoft SQL Server. I have 2 fields (compenso and diritti_di_segreteria) where my customer input costs. I need the sum of these fields as the Costo value.
Compenso = Trim(Request.Form("compenso"))
Compenso = Replace(compenso, ",", ".")
Diritti_di_segreteria = Trim(Request.Form("diritti_di_segreteria"))
Diritti_di_segreteria = Replace(diritti_di_segreteria, ",", ".")
Costo = (FormatNumber(Compenso, 2) * 1) + (FormatNumber(Diritti_di_segreteria, 2) * 1)
Now, if the number is without comma, the sum is perfect. If not, the result is a mess. Example: 20 + 30 results in 50, but 20,5 + 30.7 results in 512,00. I'm sure I'm missing something important here.
You want to call FormatNumber after adding the data
Costo = FormatNumber((Compenso + Diritti_di_segreteria), 2);
Otherwise you are adding two strings together.

How to get the current bidding price for a contract

Can someone help me get started with doing some basic things with IBPY? Using IBPY, I just want to be able to enquire the current bidding price for a commodity such as the price of a single share in Google - or the current Eur/dollar exchange rate.
I found the example at the bottom of the page here:
Fundamental Data Using IbPy
useful - but the output is somewhat confusing. How do I print to screen just the current bid/asking price of a single contract?
(Just some bio info - yes I am new to IBPY and python - but I do have over 20 years experience with C)
Many kind thanks in advance!
Using the example you referred to, with slightly changes:
import signal
from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
def price_handler(msg):
if msg.field == 1:
print("bid price = %s" % msg.price)
elif msg.field == 2:
print("ask price = %s" % msg.price)
def main():
tws = ibConnection(port=7497)
tws.register(price_handler, message.tickPrice)
tws.connect()
tick_id = 1
c = Contract()
c.m_symbol = 'AAPL'
c.m_secType = 'STK'
c.m_exchange = "SMART"
c.m_currency = "USD"
tws.reqMktData(tick_id, c, '', False)
signal.pause()
if __name__ == '__main__':
main()
Output:
bid price = 149.55
ask price = 149.56
bid price = 149.59
ask price = 149.61
...

Nested dictionaries - lists of dictionaries in each other

I originally had a jsonL file that I imported line by line and am now trying to get into the Pandas dataframe. One entry looks something like the following:
*[{u'country': u'denmark',
u'gender': u'F',
u'item_type': u'user',
u'location': u'Denmark',
u'name': u'Mona',
u'profile_text': u'',
u'reviews': [{u'company_id': u'stylepit.dk',
u'date': u'2013-10-06T18:54:49.000+00:00',
u'rating': u'4',
u'text': [u'Altid glad for at handle hos Smartkids - stort sortiment af mange m\xe6rker nemt og hurtigt'],
u'title': u'Som altid kommer varerne hurtigt - super fint'},
{u'company_id': u'www.coolshop.dk',
u'date': u'2012-10-28T19:00:56.000+00:00',
u'rating': u'5',
u'text': [u'F\xf8rste gang jeg har handlet hos Coolshop, det var super nemt og hurtigt og de har et fint udvalg, hjemmesiden har flotte fotos af varen s\xe5 jeg var ikke i tvivl om hvad jeg bestilte. Jeg k\xf8ber gerne igen hos Coolshop.',
u'med venlig hilsen',
u'Mona Pedersen Ulstrup'],
u'title': u'Super hurtig ekspedering'},
{u'company_id': u'www.yourkids.dk',
u'date': u'2010-09-26T19:47:51.000+00:00',
u'rating': u'5',
u'text': [u'Har k\xf8bt rigtig mange cars via yourkids, nok den eneste side i Danmark hvor du bare kan f\xe5 alle de sidste nye biler.',
u'Lige sagen for en cars samler. Der er altid rigtig meget service, min bedste anbefaling'],
u'title': u'Super super service'}]*
So, I have a bunch of users that may have one or more reviews as a list of dictionaries. I need to match the list of reviews with each user in pandas. I just did the following:
dataframe = pd.DataFrame(reviews)
sub_data = []
for i in dataframe['reviews']:
for j in i:
sub_data.append(j)
subdata_frame = pd.DataFrame(sub_data)
subdata_frame
Which gives me two individual dataframes which, when concatenated, do not, obviously match the user with a review, but rather does add the new columns to the mutual dataframe, and just adds the extra reviews at the bottom with no user information.
How do I associate the reviews data with my users?
I answered this before over here Creating pandas dataframe from list of dictionaries containing lists of data. However, I've seen similiar questions like this and the past and decided to post a more generalized solution
Typically for nested data types like this, I merge the inner data with the outer. In your case your inner data is reviews, which is something by itself can be represented nicely with a DataFrame.
def fixInnerData(df,innerDataCol,cols = False):
if cols: f = lambda x:pd.DataFrame(x.iloc[0],columns = cols)
else: f = lambda x:pd.DataFrame(x.iloc[0])
fix = df.groupby(level=0)[innerDataCol].apply(f)
fix = fix.reset_index(level=1,drop=True)
df = pd.merge(fix,df.drop([innerDataCol],1),how='inner',left_index=True,right_index=True)
return df
df = pd.DataFrame(data)
innerDataCol = 'reviews'
fixInnerData(df,innerDataCol)
This method is great because you can use it with a loop and pull out all levels of a dictionary

Resources