wxpython: 'Example' object has no attribute 'OnClick' - python-2.7
I am making a GUI of the periodic table of elements with wxpython, I have added all the buttons. So now what I want is when the user selects multiple buttons it should give me output same as the labeled on the button. Trying to run this code but getting the error. Don't know what's wrong, I am doing here.
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title, size=(1000, 800))
self.InitUI()
self.Centre()
self.Show()
def InitUI(self):
p = wx.Panel(self)
gs = wx.GridSizer(11, 18, 5, 1)
A = ["H", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "He", "Li", "Be", " ",
" ",
" ", " ", " ", " ", " ", " ", " ", " ", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", " ", " ", " ", " ", " ",
" ",
" ", " ", " ", " ", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co",
"Ni",
"Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd",
"Ag",
"Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au",
"Hg", "Tl",
"Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn", "Nh",
"Fl",
"Mc", "Lv", "Ts", "Og",
" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ",
"La",
"Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", " ", " ", " ", "Ac",
"Th",
"Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", " ", " ", " ", " ", " ", " ",
" ",
" ", " ", "Go", " ", " ", " ", " ", " ", " ", " ", " "]
for i in A:
btn = str(i)
a = wx.Button(self, 10, "str(i)", (20, 20)) # buttons are added
a.myname = "str(i)"
self.Bind(wx.EVT_BUTTON, self.OnClick, a)
print(i)
def OnClick(self, event): # When the button is clicked
name = event.GetEventObject().myname
p.SetSizer(gs)
app = wx.App()
Example(None, title='Grid demo')
app.MainLoop()
Well, it seems that the third argument in self.Bind(wx.EVT_BUTTON, self.OnClick, a) is useless, try self.Bind(wx.EVT_BUTTON, self.OnClick)
(comparing with code generated thanks to wxformbuilder)
It's all a bit tight given the number of buttons and you must declare the buttons as part of the panel, not hope that the sizer will do the work for you.
There are few changes but they are important.
Code now includes elements{dictionary} for element display (I'm missing a few of the rarer elements like Oganesson but hey if you can't eat it, smoke it, make a purchase with it or use it to scale a mountain, who cares?)
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title = title,size = (2000,1000))
self.InitUI()
self.Layout()
self.Centre()
self.Show()
def InitUI(self):
self.elements = {'Ru': 'Ruthenium', 'Re': 'Rhenium', 'Rf': 'Rutherfordium', 'Rg': 'Roentgenium', 'Ra': 'Radium', 'Rb': 'Rubidium', 'Rn': 'Radon', 'Rh': 'Rhodium', 'Be': 'Beryllium', 'Ba': 'Barium', 'Bh': 'Bohrium', 'Bi': 'Bismuth', 'Bk': 'Berkelium', 'Br': 'Bromine', 'H': 'Hydrogen', 'P': 'Phosphorus', 'Os': 'Osmium', 'Es': 'Einsteinium', 'Hg': 'Mercury', 'Ge': 'Germanium', 'Gd': 'Gadolinium', 'Ga': 'Gallium', 'Pr': 'Praseodymium', 'Pt': 'Platinum', 'Pu': 'Plutonium', 'C': 'Carbon', 'Pb': 'Lead', 'Pa': 'Protactinium', 'Pd': 'Palladium', 'Cd': 'Cadmium', 'Po': 'Polonium', 'Pm': 'Promethium', 'Hs': 'Hassium', 'Uup': 'Ununpentium', 'Uus': 'Ununseptium', 'Uuo': 'Ununoctium', 'Ho': 'Holmium', 'Hf': 'Hafnium', 'K': 'Potassium', 'He': 'Helium', 'Md': 'Mendelevium', 'Mg': 'Magnesium', 'Mo': 'Molybdenum', 'Mn': 'Manganese', 'O': 'Oxygen', 'Mt': 'Meitnerium', 'S': 'Sulfur', 'W': 'Tungsten', 'Zn': 'Zinc', 'Eu': 'Europium', 'Zr': 'Zirconium', 'Er': 'Erbium', 'Ni': 'Nickel', 'No': 'Nobelium', 'Na': 'Sodium', 'Nb': 'Niobium', 'Nd': 'Neodymium', 'Ne': 'Neon', 'Np': 'Neptunium', 'Fr': 'Francium', 'Fe': 'Iron', 'Fl': 'Flerovium', 'Fm': 'Fermium', 'B': 'Boron', 'F': 'Fluorine', 'Sr': 'Strontium', 'N': 'Nitrogen', 'Kr': 'Krypton', 'Si': 'Silicon', 'Sn': 'Tin', 'Sm': 'Samarium', 'V': 'Vanadium', 'Sc': 'Scandium', 'Sb': 'Antimony', 'Sg': 'Seaborgium', 'Se': 'Selenium', 'Co': 'Cobalt', 'Cn': 'Copernicium', 'Cm': 'Curium', 'Cl': 'Chlorine', 'Ca': 'Calcium', 'Cf': 'Californium', 'Ce': 'Cerium', 'Xe': 'Xenon', 'Lu': 'Lutetium', 'Cs': 'Caesium', 'Cr': 'Chromium', 'Cu': 'Copper', 'La': 'Lanthanum', 'Li': 'Lithium', 'Lv': 'Livermorium', 'Tl': 'Thallium', 'Tm': 'Thulium', 'Lr': 'Lawrencium', 'Th': 'Thorium', 'Ti': 'Titanium', 'Te': 'Tellurium', 'Tb': 'Terbium', 'Tc': 'Technetium', 'Ta': 'Tantalum', 'Yb': 'Ytterbium', 'Db': 'Dubnium', 'Dy': 'Dysprosium', 'Ds': 'Darmstadtium', 'I': 'Iodine', 'U': 'Uranium', 'Y': 'Yttrium', 'Ac': 'Actinium', 'Ag': 'Silver', 'Uut': 'Ununtrium', 'Ir': 'Iridium', 'Am': 'Americium', 'Al': 'Aluminium', 'As': 'Arsenic', 'Ar': 'Argon', 'Au': 'Gold', 'At': 'Astatine', 'In': 'Indium'}
p = wx.Panel(self)
gs = wx.GridSizer(11, 18, 5, 5)
A = [ "H"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", "He", "Li", "Be"," "," "," "," "," "," "," "," "," "," ", "B" , "C", "N", "O", "F" , "Ne", "Na", "Mg"," "," "," "," "," "," "," "," "," "," ", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca","Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru","Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "" , "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "", "Rf", "Db", "Sg", "Bh", "Hs","Mt", "Ds", "Rg", "Cn", "Nh", "Fl", "Mc", "Lv", "Ts", "Og"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", " ", " "," ", " ", " ", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm","Yb", "Lu"," ", " ", " ","Ac", "Th" , "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk","Cf", "Es", "Fm", "Md" , "No", "Lr"," "," "," "," "," "," "," "," "," " ,"Go"," "," "," "," "," "," "," ","ZZ" ]
for i in A:
btn = wx.Button(p, -1, i, (10,20)) #buttons are added
btn.myname = i
gs.Add(btn,0,)
self.Bind(wx.EVT_BUTTON, self.OnClick, btn)
p.SetSizer(gs)
def OnClick(self, event): #When the button is clicked
name = event.GetEventObject().myname
try:
element = self.elements[name]
wx.MessageBox("You selected element "+element, "Selection",wx.ICON_INFORMATION | wx.OK)
except:
wx.MessageBox("You selected element "+name, "Selection",wx.ICON_INFORMATION | wx.OK)
app = wx.App()
Example(None, title = 'Grid demo')
app.MainLoop()
New version based on your other question Error with on click event in wxpython
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title = title,size = (1400,500))
self.InitUI()
self.Layout()
self.Centre()
self.Show()
def InitUI(self):
self.elements = {'Ru': 'Ruthenium', 'Re': 'Rhenium', 'Rf': 'Rutherfordium', 'Rg': 'Roentgenium', 'Ra': 'Radium', 'Rb': 'Rubidium', 'Rn': 'Radon', 'Rh': 'Rhodium', 'Be': 'Beryllium', 'Ba': 'Barium', 'Bh': 'Bohrium', 'Bi': 'Bismuth', 'Bk': 'Berkelium', 'Br': 'Bromine', 'H': 'Hydrogen', 'P': 'Phosphorus', 'Os': 'Osmium', 'Es': 'Einsteinium', 'Hg': 'Mercury', 'Ge': 'Germanium', 'Gd': 'Gadolinium', 'Ga': 'Gallium', 'Pr': 'Praseodymium', 'Pt': 'Platinum', 'Pu': 'Plutonium', 'C': 'Carbon', 'Pb': 'Lead', 'Pa': 'Protactinium', 'Pd': 'Palladium', 'Cd': 'Cadmium', 'Po': 'Polonium', 'Pm': 'Promethium', 'Hs': 'Hassium', 'Uup': 'Ununpentium', 'Uus': 'Ununseptium', 'Uuo': 'Ununoctium', 'Ho': 'Holmium', 'Hf': 'Hafnium', 'K': 'Potassium', 'He': 'Helium', 'Md': 'Mendelevium', 'Mg': 'Magnesium', 'Mo': 'Molybdenum', 'Mn': 'Manganese', 'O': 'Oxygen', 'Mt': 'Meitnerium', 'S': 'Sulfur', 'W': 'Tungsten', 'Zn': 'Zinc', 'Eu': 'Europium', 'Zr': 'Zirconium', 'Er': 'Erbium', 'Ni': 'Nickel', 'No': 'Nobelium', 'Na': 'Sodium', 'Nb': 'Niobium', 'Nd': 'Neodymium', 'Ne': 'Neon', 'Np': 'Neptunium', 'Fr': 'Francium', 'Fe': 'Iron', 'Fl': 'Flerovium', 'Fm': 'Fermium', 'B': 'Boron', 'F': 'Fluorine', 'Sr': 'Strontium', 'N': 'Nitrogen', 'Kr': 'Krypton', 'Si': 'Silicon', 'Sn': 'Tin', 'Sm': 'Samarium', 'V': 'Vanadium', 'Sc': 'Scandium', 'Sb': 'Antimony', 'Sg': 'Seaborgium', 'Se': 'Selenium', 'Co': 'Cobalt', 'Cn': 'Copernicium', 'Cm': 'Curium', 'Cl': 'Chlorine', 'Ca': 'Calcium', 'Cf': 'Californium', 'Ce': 'Cerium', 'Xe': 'Xenon', 'Lu': 'Lutetium', 'Cs': 'Caesium', 'Cr': 'Chromium', 'Cu': 'Copper', 'La': 'Lanthanum', 'Li': 'Lithium', 'Lv': 'Livermorium', 'Tl': 'Thallium', 'Tm': 'Thulium', 'Lr': 'Lawrencium', 'Th': 'Thorium', 'Ti': 'Titanium', 'Te': 'Tellurium', 'Tb': 'Terbium', 'Tc': 'Technetium', 'Ta': 'Tantalum', 'Yb': 'Ytterbium', 'Db': 'Dubnium', 'Dy': 'Dysprosium', 'Ds': 'Darmstadtium', 'I': 'Iodine', 'U': 'Uranium', 'Y': 'Yttrium', 'Ac': 'Actinium', 'Ag': 'Silver', 'Uut': 'Ununtrium', 'Ir': 'Iridium', 'Am': 'Americium', 'Al': 'Aluminium', 'As': 'Arsenic', 'Ar': 'Argon', 'Au': 'Gold', 'At': 'Astatine', 'In': 'Indium'}
p = wx.Panel(self)
hbox1= wx.BoxSizer(wx.VERTICAL)
self.t1= wx.TextCtrl (p,0,value="",size=(120,30),style=wx.TE_READONLY)
hbox1.Add(self.t1,proportion=0,flag=wx.CENTER)
gs = wx.GridSizer(11, 18, 5, 5)
A = [ "H"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", "He", "Li", "Be"," "," "," "," "," "," "," "," "," "," ", "B" , "C", "N", "O", "F" , "Ne", "Na", "Mg"," "," "," "," "," "," "," "," "," "," ", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca","Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru","Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "" , "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "", "Rf", "Db", "Sg", "Bh", "Hs","Mt", "Ds", "Rg", "Cn", "Nh", "Fl", "Mc", "Lv", "Ts", "Og"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", " ", " "," ", " ", " ", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm","Yb", "Lu"," ", " ", " ","Ac", "Th" , "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk","Cf", "Es", "Fm", "Md" , "No", "Lr"," "," "," "," "," "," "," "," "," " ," "," "," "," "," "," "," "," "," "]
for element in A:
btn = wx.Button(p, -1, element, (10,20)) #buttons are added
btn.name = element
gs.Add(btn,0,)
self.Bind(wx.EVT_BUTTON, self.OnClick, btn)
hbox1.Add(gs,proportion=0)
p.SetSizer(hbox1)
def OnClick(self, event): #When the button is clicked
name = event.GetEventObject().name
try:
element = self.elements[name]
except:
element = name
self.t1.SetValue(element)
app = wx.App()
Example(None, title = 'Element Grid')
app.MainLoop()
This is now the third time that I have asked you to read how StackOverflow works, please read the tour pages. Ultimately, this is for your own good.
Related
How can I store/transfer information from my ShinyApp to a dataframe in my global environment via an action button?
Good afternoon, I am a beginner creating ShinyApps and I would really appreciate if someone could help me to solve the following problem: The purpose of the App is to store the information that a football scout fills on the reports. Every time a scout fills out the different items of the report, I would like to store/transfer this information in a new dataframe on my global environment in R Studio via the action button below called "Guardar". Any idea? My e-mail is ivandiazramis8#gmail.com for any in inquiry. Thank you! library(shinyWidgets) library(shinydashboard) library(shinyauthr) library(shinyjs) library(sodium) library(tibble) library(dplyr) library(DT) #----------UI---------- ui <- dashboardPage(title = "Herramienta Scouting TFM", skin = "blue", dashboardHeader(title = "Herramienta Scouting TFM", titleWidth = "300px"), dashboardSidebar(width = "300px", sidebarMenu(menuItem(text = "Informe Tipo", icon = icon(name = "file-contract", lib = "font-awesome"), menuSubItem("Informe", tabName = "Informe_Tipo", icon = icon("futbol"))))), dashboardBody( tabItems( tabItem(tabName = "Informe_Tipo", h1("INFORME TIPO"), br(), fluidRow( column(width = 4, box(title = "INFORMACIÓN DEL SCOUT ", background = "light-blue", width = 12), box(status = "primary", width = 12, textInput(inputId = "Scout_1", label = "Nombre Completo: ", value = character(0)), dateInput(inputId = "Fecha_Informe_1", label = "Fecha de Realización del Informe: ", value = Sys.Date(), min = Sys.Date(), max = Sys.Date(), weekstart = 1, language = "es")), box(title = "INFORMACIÓN DEL JUGADOR ", background = "light-blue", width = 12), box(status = "primary", width = 12, selectInput(inputId = "Competicion_1", label = "Competición: ", choices = c("Bundesliga 2", "Championship", "Liga Smartbank", "Ligue 2", "Serie B")), selectInput(inputId = "Equipo_1", label = "Equipo: ", choices = c("Jahn Regensburg", "Dynamo Dresden", "Nürnberg", "Ingolstadt", "Hamburger SV", "Fortuna Düsseldorf", "Holstein Kiel", "Paderborn", "Werder Bremen", "Heidenheim", "Darmstadt 98", "Schalke 04", "Karlsruher SC", "Hannover 96", "Hansa Rostock", "Erzgebirge Aue", "Sandhausen", "St, Pauli", "Nürnberg II", "Hatayspor", "Borussia Dortmund II", "Werder Bremen U19", "Fortuna Düsseldorf II", "Schalke 04 II", "Apollon Smirnis", "Hamburger SV U19", "Karlsruher SC U17", "Antwerp", "Hallescher FC", "Union Berlin", "Freiburg", "Holstein Kiel II", "Darmstadt 98 U19", "Verl", "Arminia Bielefeld", "Karlsruher SC U19", "Vissel Kobe", "Werder Bremen II", "Norwich City", "Schalke 04 U19", "Ingolstadt U19", "Waldhof Mannheim", "Hannover 96 II", "Mallorca", "Sheffield United", "Swansea City", "West Bromwich Albion", "Blackburn Rovers", "Arsenal", "Cardiff City", "Millwall", "Barnsley", "Nottingham Forest", "Coventry City", "Blackpool", "Peterborough United", "Birmingham City", "Bristol City", "Preston North End", "Queens Park Rangers", "Hull City", "Luton Town", "Stoke City U23", "Stoke City", "Middlesbrough", "Reading", "Derby County", "Middlesbrough U23", "Huddersfield Town", "Reading U23", "Fulham", "Bournemouth", "Birmingham City U23", "Swindon Town", "Derby County U23", "Portsmouth", "Guiseley", "Sheffield United U23", "Cardiff City U23", "Northampton Town", "Hearts", "Club Brugge", "Chelsea U23", "Nottingham Forest U23", "Notts County", "West Bromwich Albion U23", "Barnsley U23", "Napoli", "PAOK", "Grimsby Town", "Cesena", "Derby County U18", "Fleetwood Town", "Accrington Stanley", "Fulham U23", "Hull City U18", "Huddersfield Town B", "Olympiacos Piraeus", "Lincoln City", "Coventry City U23", "Ipswich Town", "Shrewsbury Town", "Cheltenham Town", "Swansea City U18", "Portimonense", "Charlton Athletic", "Hibernian", "Bristol City U23", "Millwall U23", "Hull City U23", "Aris", "Gillingham", "Pisa", "Blackburn Rovers U23", "Preston North End U18", "Oxford United", "Sheffield United U18", "Millwall U18", "Ponferradina", "Girona", "Ibiza", "Burgos", "Brentford", "Real Zaragoza", "Las Palmas", "Eibar", "Real Sociedad B", "Huesca", "Leganés", "Alcorcón", "Málaga", "Fuenlabrada", "Sporting Gijón", "Almería", "Lugo", "Real Oviedo", "Real Valladolid", "Tenerife", "Cartagena", "Amorebieta", "Mirandés", "Real Sociedad", "Real Sociedad III", "Las Palmas Atlético", "CD Calahorra", NA, "Sporting Gijón B", "Tenerife B", "Cartagena B", "Girona II", "Valladolid Promesas", "Getafe", "Real Oviedo Vetusta", "Málaga CF U17", "Alcorcón B", "Racing Santander", "Fuenlabrada B", "Cádiz", "Elche", "Leganés B", "Huesca B", "Dnipro-1", "Charlotte Independence", "Deportivo Alavés", "Valencia", "Real Zaragoza B", "Barcelona", "Mirandés B", "Sabadell", "Dunkerque", "Pau", "Young Boys", "Ajaccio", "Grenoble", "Dijon", "Nancy", "Auxerre", "Guingamp", "Paris", "Bastia", "Valenciennes", "Nîmes", "Rodez ", "Toulouse", "Nancy II", "Le Havre", "Sochaux", "Niort", "Quevilly Rouen", "Amiens SC", "Caen", "Guingamp II", "Le Havre U19", "Nîmes II", "Rizespor", "Dijon U19", "Lecce", "Caen II", "Brescia", "Lech Poznan", "Besiktas", "Parma", "Paris II", "Famalicão", "Dunkerque II", "Manisa BBSK", "Niort II", "Kayserispor", "Ajaccio U19", "Quevilly Rouen II", "Dijon II", "Paris U19", "Bayer Leverkusen", "Le Havre U17", "Nancy U18", "Paris U17", "Spezia", "Warta Poznan", "Montpellier", "Valenciennes U19", "U Craiova 1948", "Valenciennes II", "Sochaux U19", "Cosenza", "Ternana", "Reggina", "Benevento", "SPAL", "Alessandria", "Como", "Ascoli", "Cittadella", "Monza", "Frosinone", "Pordenone", "Crotone", "Perugia", "Cremonese", "Vicenza", "Parma U19", "Renate", "Frosinone U19", "Vålerenga", "ACN Siena", "Reggina U17", "Carrarese", "Salernitana", "Imolese", "SPAL U19", "Pordenone U17", "Pisa U19", "Triestina", "Pordenone U19", "Yeni Malatyaspor", "FeralpiSalò", "Vicenza U19", "Alessandria U19", "Reggina U19", "Empoli", "Ascoli U19", "Crotone U19", "Cosenza U19", "Benevento U19")), selectInput(inputId = "Demarcación_1", label = "Demarcación: ", choices = c("Portero", "Central", "Lateral", "Mediocentro", "Extremo", "Delantero")), selectInput(inputId = "Nacionalidad_1", label = "Nacionalidad: ", choices = c("Germany", "Russia", "Austria", "Czech Republic", "Denmark", "Sweden", "Bosnia and Herzegovina", "Poland", "Spain", "United States", "Romania", "Finland", "Belgium", "France", "Switzerland", "England", "Croatia", "Japan", "Slovenia", "Norway", "Mexico", "Serbia", "Senegal", "Canada", "North Macedonia", "Georgia", "Nigeria", "Brazil", "Netherlands", "Kosovo", "Curaçao", "Ghana", "Azerbaijan", "Korea Republic", "Cameroon", "Dominican Republic", "Bulgaria", "Australia", "Albania", "Luxembourg", "Slovakia", "Italy", "Iceland", "Gambia", "Ukraine", "Sierra Leone", "Côte d'Ivoire", "Congo DR", "New Zealand", "Sudan", "Guinea", "Congo", "Wales", "Scotland", "Estonia", "Montenegro", "Republic of Ireland", "Argentina", "Northern Ireland", "Portugal", "Saudi Arabia", "Namibia", "Iran", "Paraguay", "Jamaica", "Guinea-Bissau", "Colombia", "Kenya", "Cuba", "Angola", "Bermuda", "Ecuador", "Uruguay", "Morocco", "Equatorial Guinea", "Venezuela", "Peru", "Panama", "Mali", "Egypt", "Israel", "French Guiana", "Benin", "Gabon", "Cape Verde Islands", "Guadeloupe", "Tunisia", "Haiti", "Comoros", "Réunion", "Martinique", "Algeria", "Turkey", "South Africa", "Burkina Faso", "New Caledonia", "Togo", "Zambia", "Lithuania", "Greece", "Hungary", "Uganda", "Cyprus", "Moldova", "Madagascar", "Malta", "Chile", "Honduras", "Latvia")), selectInput(inputId = "Pie_Dominante_1", label = "Pie Dominante: ", choices = c("derecho", "izquierdo", "ambidiestro", NA, "unknown")), sliderInput(inputId = "Edad_1", label = "Edad: ", min = 15, max = 40, value = 15, ticks = FALSE)), box(title = "INFORMACIÓN DEL PARTIDO ", background = "light-blue", width = 12), box(status = "primary", width = 12, textInput(inputId = "Partido_1", label = "Partido (Equipo Local) (X) - (X) (Equipo Visitante): ", value = character(0)), pickerInput(inputId = "Demarcación_Partido_1", label = "Demarcación en el Partido: ", choices = c("Portero", "Central", "Lateral", "Mediocentro", "Extremo", "Delantero"), selected = character(0), multiple = TRUE, options = list(`actions-box` = TRUE)), sliderInput(inputId = "Minutos_Partido_1", label = "Minutos Jugados: ", min = 0, max = 90, value = 0, ticks = FALSE))), column(width = 8, box(title = "VALORACIÓN DE LOS ÍTEMS ", background = "light-blue", width = 12), box(title = "Capacidad de jugar con los pies: ", status = "primary", width = 12, radioGroupButtons(inputId = "1_Valoración_1", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE), textInput(inputId = "1_Comentario_1", label = "Comentarios: ")), box(title = "Capacidad de salida en balones divididos: ", status = "primary", width = 12, radioGroupButtons(inputId = "1_Valoración_2", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE), textInput(inputId = "1_Comentario_2", label = "Comentarios: ")), box(title = "Reflejos: ", status = "primary", width = 12, radioGroupButtons(inputId = "1_Valoración_3", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE), textInput(inputId = "1_Comentario_3", label = "Comentarios: ")), box(title = "Dominio del juego aéreo: ", status = "primary", width = 12, radioGroupButtons(inputId = "1_Valoración_4", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE), textInput(inputId = "1_Comentario_4", label = "Comentarios: ")), box(title = "Capacidad de comunicación: ", status = "primary", width = 12, radioGroupButtons(inputId = "1_Valoración_5", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE), textInput(inputId = "1_Comentario_5", label = "Comentarios: ")))), actionBttn(inputId = "boton", label = "Guardar", icon = icon("save", lib = "font-awesome"), style = "jelly", color = "primary", size = "md"))) ) ) #----------SERVER---------- server <- function(input, output){} #----------SHINYAPP---------- shinyApp(ui, server)
Although we could use the function assign to save a df into the .globalEnv. R session will still be busy (a shiny application is running), so the df will appear in the global environment only when the app stops. We can use downloadHandler instead. Don't worry too much about what map/set_names and exec functions mean, I only used them here to avoid typing manually a data frame one input at a time. e.g data.frame(Nacionalidad_1 = input$Nacionalidad_1) Now everytime the button "guardar" is pressed, a csv is downloaded that we can later read into R with read_csv. #vector with the names of all the inputs in the app inpt_nms <- c( "sidebarItemExpanded", "1_Valoración_2", "1_Valoración_1", "Nacionalidad_1", "1_Comentario_4", "1_Valoración_5", "1_Valoración_3", "Partido_1", "1_Comentario_1", "1_Comentario_2", "Equipo_1", "1_Comentario_3", "Competicion_1", "Pie_Dominante_1", "Minutos_Partido_1", "sidebarCollapsed", "Scout_1", "Demarcación_Partido_1", "1_Comentario_5", "1_Valoración_4", "boton", "Fecha_Informe_1", "Demarcación_1", "Edad_1" ) #server code with download handler server <- function(input, output) { output$boton <- downloadHandler( filename = function() { paste0("df_", input$Scout_1, ".csv") }, content = function(file) { map(inpt_nms, ~ input[[.x]]) %>% set_names(inpt_nms) %>% { exec("tibble", !!!.) } %>% write_csv(file) } ) } Full app: library(shiny) library(shinyWidgets) library(shinydashboard) library(shinyauthr) library(shinyjs) library(sodium) library(tidyverse) library(DT) inpt_nms <- c( "sidebarItemExpanded", "1_Valoración_2", "1_Valoración_1", "Nacionalidad_1", "1_Comentario_4", "1_Valoración_5", "1_Valoración_3", "Partido_1", "1_Comentario_1", "1_Comentario_2", "Equipo_1", "1_Comentario_3", "Competicion_1", "Pie_Dominante_1", "Minutos_Partido_1", "sidebarCollapsed", "Scout_1", "Demarcación_Partido_1", "1_Comentario_5", "1_Valoración_4", "boton", "Fecha_Informe_1", "Demarcación_1", "Edad_1" ) #----------UI---------- ui <- dashboardPage( title = "Herramienta Scouting TFM", skin = "blue", dashboardHeader( title = "Herramienta Scouting TFM", titleWidth = "300px" ), dashboardSidebar( width = "300px", sidebarMenu(menuItem( text = "Informe Tipo", icon = icon(name = "file-contract", lib = "font-awesome"), menuSubItem("Informe", tabName = "Informe_Tipo", icon = shiny::icon("futbol") ) )) ), dashboardBody( tabItems( tabItem( tabName = "Informe_Tipo", h1("INFORME TIPO"), br(), fluidRow( column( width = 4, box( title = "INFORMACIÓN DEL SCOUT ", background = "light-blue", width = 12 ), box( status = "primary", width = 12, textInput( inputId = "Scout_1", label = "Nombre Completo: ", value = character(0) ), dateInput( inputId = "Fecha_Informe_1", label = "Fecha de Realización del Informe: ", value = Sys.Date(), min = Sys.Date(), max = Sys.Date(), weekstart = 1, language = "es" ) ), box( title = "INFORMACIÓN DEL JUGADOR ", background = "light-blue", width = 12 ), box( status = "primary", width = 12, selectInput( inputId = "Competicion_1", label = "Competición: ", choices = c( "Bundesliga 2", "Championship", "Liga Smartbank", "Ligue 2", "Serie B" ) ), selectInput( inputId = "Equipo_1", label = "Equipo: ", choices = c( "Jahn Regensburg", "Dynamo Dresden", "Nürnberg", "Ingolstadt", "Hamburger SV", "Fortuna Düsseldorf", "Holstein Kiel", "Paderborn", "Werder Bremen", "Heidenheim", "Darmstadt 98", "Schalke 04", "Karlsruher SC", "Hannover 96", "Hansa Rostock", "Erzgebirge Aue", "Sandhausen", "St, Pauli", "Nürnberg II", "Hatayspor", "Borussia Dortmund II", "Werder Bremen U19", "Fortuna Düsseldorf II", "Schalke 04 II", "Apollon Smirnis", "Hamburger SV U19", "Karlsruher SC U17", "Antwerp", "Hallescher FC", "Union Berlin", "Freiburg", "Holstein Kiel II", "Darmstadt 98 U19", "Verl", "Arminia Bielefeld", "Karlsruher SC U19", "Vissel Kobe", "Werder Bremen II", "Norwich City", "Schalke 04 U19", "Ingolstadt U19", "Waldhof Mannheim", "Hannover 96 II", "Mallorca", "Sheffield United", "Swansea City", "West Bromwich Albion", "Blackburn Rovers", "Arsenal", "Cardiff City", "Millwall", "Barnsley", "Nottingham Forest", "Coventry City", "Blackpool", "Peterborough United", "Birmingham City", "Bristol City", "Preston North End", "Queens Park Rangers", "Hull City", "Luton Town", "Stoke City U23", "Stoke City", "Middlesbrough", "Reading", "Derby County", "Middlesbrough U23", "Huddersfield Town", "Reading U23", "Fulham", "Bournemouth", "Birmingham City U23", "Swindon Town", "Derby County U23", "Portsmouth", "Guiseley", "Sheffield United U23", "Cardiff City U23", "Northampton Town", "Hearts", "Club Brugge", "Chelsea U23", "Nottingham Forest U23", "Notts County", "West Bromwich Albion U23", "Barnsley U23", "Napoli", "PAOK", "Grimsby Town", "Cesena", "Derby County U18", "Fleetwood Town", "Accrington Stanley", "Fulham U23", "Hull City U18", "Huddersfield Town B", "Olympiacos Piraeus", "Lincoln City", "Coventry City U23", "Ipswich Town", "Shrewsbury Town", "Cheltenham Town", "Swansea City U18", "Portimonense", "Charlton Athletic", "Hibernian", "Bristol City U23", "Millwall U23", "Hull City U23", "Aris", "Gillingham", "Pisa", "Blackburn Rovers U23", "Preston North End U18", "Oxford United", "Sheffield United U18", "Millwall U18", "Ponferradina", "Girona", "Ibiza", "Burgos", "Brentford", "Real Zaragoza", "Las Palmas", "Eibar", "Real Sociedad B", "Huesca", "Leganés", "Alcorcón", "Málaga", "Fuenlabrada", "Sporting Gijón", "Almería", "Lugo", "Real Oviedo", "Real Valladolid", "Tenerife", "Cartagena", "Amorebieta", "Mirandés", "Real Sociedad", "Real Sociedad III", "Las Palmas Atlético", "CD Calahorra", NA, "Sporting Gijón B", "Tenerife B", "Cartagena B", "Girona II", "Valladolid Promesas", "Getafe", "Real Oviedo Vetusta", "Málaga CF U17", "Alcorcón B", "Racing Santander", "Fuenlabrada B", "Cádiz", "Elche", "Leganés B", "Huesca B", "Dnipro-1", "Charlotte Independence", "Deportivo Alavés", "Valencia", "Real Zaragoza B", "Barcelona", "Mirandés B", "Sabadell", "Dunkerque", "Pau", "Young Boys", "Ajaccio", "Grenoble", "Dijon", "Nancy", "Auxerre", "Guingamp", "Paris", "Bastia", "Valenciennes", "Nîmes", "Rodez ", "Toulouse", "Nancy II", "Le Havre", "Sochaux", "Niort", "Quevilly Rouen", "Amiens SC", "Caen", "Guingamp II", "Le Havre U19", "Nîmes II", "Rizespor", "Dijon U19", "Lecce", "Caen II", "Brescia", "Lech Poznan", "Besiktas", "Parma", "Paris II", "Famalicão", "Dunkerque II", "Manisa BBSK", "Niort II", "Kayserispor", "Ajaccio U19", "Quevilly Rouen II", "Dijon II", "Paris U19", "Bayer Leverkusen", "Le Havre U17", "Nancy U18", "Paris U17", "Spezia", "Warta Poznan", "Montpellier", "Valenciennes U19", "U Craiova 1948", "Valenciennes II", "Sochaux U19", "Cosenza", "Ternana", "Reggina", "Benevento", "SPAL", "Alessandria", "Como", "Ascoli", "Cittadella", "Monza", "Frosinone", "Pordenone", "Crotone", "Perugia", "Cremonese", "Vicenza", "Parma U19", "Renate", "Frosinone U19", "Vålerenga", "ACN Siena", "Reggina U17", "Carrarese", "Salernitana", "Imolese", "SPAL U19", "Pordenone U17", "Pisa U19", "Triestina", "Pordenone U19", "Yeni Malatyaspor", "FeralpiSalò", "Vicenza U19", "Alessandria U19", "Reggina U19", "Empoli", "Ascoli U19", "Crotone U19", "Cosenza U19", "Benevento U19" ) ), selectInput( inputId = "Demarcación_1", label = "Demarcación: ", choices = c( "Portero", "Central", "Lateral", "Mediocentro", "Extremo", "Delantero" ) ), selectInput( inputId = "Nacionalidad_1", label = "Nacionalidad: ", choices = c( "Germany", "Russia", "Austria", "Czech Republic", "Denmark", "Sweden", "Bosnia and Herzegovina", "Poland", "Spain", "United States", "Romania", "Finland", "Belgium", "France", "Switzerland", "England", "Croatia", "Japan", "Slovenia", "Norway", "Mexico", "Serbia", "Senegal", "Canada", "North Macedonia", "Georgia", "Nigeria", "Brazil", "Netherlands", "Kosovo", "Curaçao", "Ghana", "Azerbaijan", "Korea Republic", "Cameroon", "Dominican Republic", "Bulgaria", "Australia", "Albania", "Luxembourg", "Slovakia", "Italy", "Iceland", "Gambia", "Ukraine", "Sierra Leone", "Côte d'Ivoire", "Congo DR", "New Zealand", "Sudan", "Guinea", "Congo", "Wales", "Scotland", "Estonia", "Montenegro", "Republic of Ireland", "Argentina", "Northern Ireland", "Portugal", "Saudi Arabia", "Namibia", "Iran", "Paraguay", "Jamaica", "Guinea-Bissau", "Colombia", "Kenya", "Cuba", "Angola", "Bermuda", "Ecuador", "Uruguay", "Morocco", "Equatorial Guinea", "Venezuela", "Peru", "Panama", "Mali", "Egypt", "Israel", "French Guiana", "Benin", "Gabon", "Cape Verde Islands", "Guadeloupe", "Tunisia", "Haiti", "Comoros", "Réunion", "Martinique", "Algeria", "Turkey", "South Africa", "Burkina Faso", "New Caledonia", "Togo", "Zambia", "Lithuania", "Greece", "Hungary", "Uganda", "Cyprus", "Moldova", "Madagascar", "Malta", "Chile", "Honduras", "Latvia" ) ), selectInput( inputId = "Pie_Dominante_1", label = "Pie Dominante: ", choices = c("derecho", "izquierdo", "ambidiestro", NA, "unknown") ), sliderInput( inputId = "Edad_1", label = "Edad: ", min = 15, max = 40, value = 15, ticks = FALSE ) ), box( title = "INFORMACIÓN DEL PARTIDO ", background = "light-blue", width = 12 ), box( status = "primary", width = 12, textInput( inputId = "Partido_1", label = "Partido (Equipo Local) (X) - (X) (Equipo Visitante): ", value = character(0) ), pickerInput( inputId = "Demarcación_Partido_1", label = "Demarcación en el Partido: ", choices = c( "Portero", "Central", "Lateral", "Mediocentro", "Extremo", "Delantero" ), selected = character(0), multiple = TRUE, options = list(`actions-box` = TRUE) ), sliderInput( inputId = "Minutos_Partido_1", label = "Minutos Jugados: ", min = 0, max = 90, value = 0, ticks = FALSE ) ) ), column( width = 8, box( title = "VALORACIÓN DE LOS ÍTEMS ", background = "light-blue", width = 12 ), box( title = "Capacidad de jugar con los pies: ", status = "primary", width = 12, radioGroupButtons( inputId = "1_Valoración_1", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE ), textInput( inputId = "1_Comentario_1", label = "Comentarios: " ) ), box( title = "Capacidad de salida en balones divididos: ", status = "primary", width = 12, radioGroupButtons( inputId = "1_Valoración_2", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE ), textInput( inputId = "1_Comentario_2", label = "Comentarios: " ) ), box( title = "Reflejos: ", status = "primary", width = 12, radioGroupButtons( inputId = "1_Valoración_3", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE ), textInput( inputId = "1_Comentario_3", label = "Comentarios: " ) ), box( title = "Dominio del juego aéreo: ", status = "primary", width = 12, radioGroupButtons( inputId = "1_Valoración_4", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE ), textInput( inputId = "1_Comentario_4", label = "Comentarios: " ) ), box( title = "Capacidad de comunicación: ", status = "primary", width = 12, radioGroupButtons( inputId = "1_Valoración_5", label = "Valoración: ", choices = c("1", "2", "3", "4"), selected = character(0), status = "primary", justified = TRUE ), textInput( inputId = "1_Comentario_5", label = "Comentarios: " ) ) ) ), downloadButton( outputId = "boton", label = "Guardar", icon = icon("save", lib = "font-awesome"), style = "jelly", color = "primary", size = "md" ) ) ) ) ) #----------SERVER---------- server <- function(input, output) { output$boton <- downloadHandler( filename = function() { paste0("df_", input$Scout_1, ".csv") }, content = function(file) { map(inpt_nms, ~ input[[.x]]) %>% set_names(inpt_nms) %>% { exec("tibble", !!!.) } %>% write_csv(file) } ) } #----------SHINYAPP---------- shinyApp(ui, server)
How can I print out a list?
I have this dictionary: ANIMALS = { "a": "ape", "k": "kangaroo", "#": "cat", "h": "horse", "l": "lamb" } and this list: pelto = [ [" ", "a", " ", " ", "l"], [" ", "k", "#", "k", " "], ["h", " ", "a", "k", " "] ] I need to go through the list and find the indexes of every string in there. After that I'd need to print everything out to something like this: In (1, 0) there's an ape In (4, 0) there's a lamb In (1, 1) there's a kangaroo In (2, 1) there's a cat In (3, 1) there's a kangaroo In (0, 2) there's a horse In (2, 2) there's an ape In (3, 2) there's a kangaroo Any ideas?
well the easy way to do this, is using the .index() in python (I am assuming this is python because of the dictionary), so the code that does that printing is this: ANIMALS = { "a": "ape", "k": "kangaroo", "#": "cat", "h": "horse", "l": "lamb" } pelto = [ [" ", "a", " ", " ", "l"], [" ", "k", "#", "k", " "], ["h", " ", "a", "k", " "] ] for list in pelto: for item in list: if item is not " ": print(f'In ({list.index(item)}, {pelto.index(list)}) there\'s an {ANIMALS[item]}') This is the result that you are waiting for: In (1, 0) there's an ape In (4, 0) there's an lamb In (1, 1) there's an kangaroo In (2, 1) there's an cat In (1, 1) there's an kangaroo In (0, 2) there's an horse In (2, 2) there's an ape In (3, 2) there's an kangaroo
How to get event_data for clicked slices in R plotly's sunburst plot
When using plotly R package to create a sunburst pie chart in Shiny app, the user can click on the plot to zoom in/out dynamically. We would want to be able to download some data for current selected/centered piece. However we cannot find this information from all the possible eventdata options. There are hover events but that's not enough, as user can click a piece then mouse move around to hover on other pieces without clicking it. There is no clicking event with zoom in/out. And there is no relayout event. I think there must be some js event fired with zoom in/out, but that is not captured with existing eventdata function. Update: It seemed there is selectedPath property for js chart, however I don't know how to access this data in Shiny. Update2: Thanks for the answer which solved the problem. Also it turned out to be a missing feature in plotly R package, and it has been addd in most recent commit.
Currently plotly_click only provides data for the root and the leafs of a sunburst plot. However you can pass the plotly_hover event_data to a reactiveVal once the plot was clicked. As you haven't provided any example please see the following - using onclick() from library(shinyjs) for the workaround. library(plotly) library(shinyjs) DF <- structure(list(labels = c("total", "A", "C", "B", "F", "E", "F", "E", "D", "E", "D", "D", "F", "G", "H", "H", "G", "H", "G", "H", "H", "G", "I", "G", "I", "H", "G", "I", "I", "G", "G", "I", "H", "H", "I", "I", "I", "H", "I", "G"), values = c(100L, 36L, 29L, 35L, 12L, 14L, 10L, 14L, 8L, 18L, 5L, 10L, 9L, 6L, 5L, 4L, 3L, 7L, 4L, 2L, 6L, 3L, 8L, 3L, 2L, 4L, 4L, 4L, 4L, 4L, 3L, 2L, 5L, 5L, 2L, 2L, 1L, 1L, 1L, 5L), parents = c(NA, "total", "total", "total", "total - A", "total - C", "total - C", "total - A", "total - B", "total - B", "total - C", "total - A", "total - B", "total - A - F", "total - C - E", "total - C - F", "total - A - E", "total - A - E", "total - B - D", "total - B - D", "total - B - E", "total - C - D", "total - B - E", "total - A - D", "total - B - D", "total - B - F", "total - C - F", "total - A - E", "total - C - E", "total - B - E", "total - B - F", "total - A - D", "total - A - D", "total - A - F", "total - B - F", "total - C - F", "total - C - D", "total - C - D", "total - A - F", "total - C - E"), ids = c( "total", "total - A", "total - C", "total - B", "total - A - F", "total - C - E", "total - C - F", "total - A - E", "total - B - D", "total - B - E", "total - C - D", "total - A - D", "total - B - F", "total - A - F - G", "total - C - E - H", "total - C - F - H", "total - A - E - G", "total - A - E - H", "total - B - D - G", "total - B - D - H", "total - B - E - H", "total - C - D - G", "total - B - E - I", "total - A - D - G", "total - B - D - I", "total - B - F - H", "total - C - F - G", "total - A - E - I", "total - C - E - I", "total - B - E - G", "total - B - F - G", "total - A - D - I", "total - A - D - H", "total - A - F - H", "total - B - F - I", "total - C - F - I", "total - C - D - I", "total - C - D - H", "total - A - F - I", "total - C - E - G" )), row.names = c(NA,-40L), class = "data.frame") ui <- fluidPage( useShinyjs(), plotlyOutput("sunburst"), htmlOutput("hoverDataOut"), htmlOutput("clickDataOut") ) server <- function(input, output, session) { output$sunburst <- renderPlotly({ plot_ly(data = DF, source = "sunSource", customdata = ~ids, ids = ~ids, labels= ~labels, parents = ~parents, values= ~values, type='sunburst', branchvalues = 'total') }) hoverData <- reactive({ currentEventData <- unlist(event_data(event = "plotly_hover", source = "sunSource", priority = "event")) }) clickData <- reactiveVal() observe({ clickData(unlist(event_data(event = "plotly_click", source = "sunSource", priority = "event"))) }) onclick(id = "sunburst", expr = {clickData(hoverData())}) output$hoverDataOut <- renderText({ paste("Hover data:", paste(names(hoverData()), unlist(hoverData()), sep = ": ", collapse = " | ")) }) output$clickDataOut <- renderText({ paste("Click data:", paste(names(clickData()), unlist(clickData()), sep = ": ", collapse = " | ")) }) } shinyApp(ui, server) I've created a GitHub issue to get some more information about this behaviour. You might also be interested in this post. Update: After the latest commit in reaction to this plotly_sunburstclick can be used as follows: # install latest r-plotly dev version: # devtools::install_github("ropensci/plotly") library(plotly) library(shinyjs) DF <- structure(list(labels = c("total", "A", "C", "B", "F", "E", "F", "E", "D", "E", "D", "D", "F", "G", "H", "H", "G", "H", "G", "H", "H", "G", "I", "G", "I", "H", "G", "I", "I", "G", "G", "I", "H", "H", "I", "I", "I", "H", "I", "G"), values = c(100L, 36L, 29L, 35L, 12L, 14L, 10L, 14L, 8L, 18L, 5L, 10L, 9L, 6L, 5L, 4L, 3L, 7L, 4L, 2L, 6L, 3L, 8L, 3L, 2L, 4L, 4L, 4L, 4L, 4L, 3L, 2L, 5L, 5L, 2L, 2L, 1L, 1L, 1L, 5L), parents = c(NA, "total", "total", "total", "total - A", "total - C", "total - C", "total - A", "total - B", "total - B", "total - C", "total - A", "total - B", "total - A - F", "total - C - E", "total - C - F", "total - A - E", "total - A - E", "total - B - D", "total - B - D", "total - B - E", "total - C - D", "total - B - E", "total - A - D", "total - B - D", "total - B - F", "total - C - F", "total - A - E", "total - C - E", "total - B - E", "total - B - F", "total - A - D", "total - A - D", "total - A - F", "total - B - F", "total - C - F", "total - C - D", "total - C - D", "total - A - F", "total - C - E"), ids = c( "total", "total - A", "total - C", "total - B", "total - A - F", "total - C - E", "total - C - F", "total - A - E", "total - B - D", "total - B - E", "total - C - D", "total - A - D", "total - B - F", "total - A - F - G", "total - C - E - H", "total - C - F - H", "total - A - E - G", "total - A - E - H", "total - B - D - G", "total - B - D - H", "total - B - E - H", "total - C - D - G", "total - B - E - I", "total - A - D - G", "total - B - D - I", "total - B - F - H", "total - C - F - G", "total - A - E - I", "total - C - E - I", "total - B - E - G", "total - B - F - G", "total - A - D - I", "total - A - D - H", "total - A - F - H", "total - B - F - I", "total - C - F - I", "total - C - D - I", "total - C - D - H", "total - A - F - I", "total - C - E - G" )), row.names = c(NA,-40L), class = "data.frame") ui <- fluidPage( useShinyjs(), plotlyOutput("sunburst"), htmlOutput("hoverDataOut"), htmlOutput("clickDataOut") ) server <- function(input, output, session) { output$sunburst <- renderPlotly({ plot_ly(data = DF, source = "sunSource", customdata = ~ids, ids = ~ids, labels= ~labels, parents = ~parents, values= ~values, type='sunburst', branchvalues = 'total') }) hoverData <- reactive({ currentEventData <- unlist(event_data(event = "plotly_hover", source = "sunSource", priority = "event")) }) clickData <- reactive({ currentEventData <- unlist(event_data(event = "plotly_sunburstclick", source = "sunSource", priority = "event")) }) output$hoverDataOut <- renderText({ paste("Hover data:", paste(names(hoverData()), unlist(hoverData()), sep = ": ", collapse = " | ")) }) output$clickDataOut <- renderText({ paste("Click data:", paste(names(clickData()), unlist(clickData()), sep = ": ", collapse = " | ")) }) } shinyApp(ui, server)
Match with multiple conditions in $OR
In MongoDB I have 2 conditions First condition: "\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}"; Second condition: "\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}"; I need to OR condition on this statement so what I did is: matchquery = matchquery + "\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}"+["%OR:"]+"\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}"; but of course that did not work. How can I achieve this?
Use the Or Operator & create it like this : var condition1 = "\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}"; var condition2 = "\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}"; var matchquery = "{ \"$or\" : [ " + condition1 + "," + condition2 +" ]}"
Use the $or operator. You essentially want to create a query which has the form var matchquery = { '$or': [ { 'userfullname': { '$regex': \filtertext\, '$options': 'i' } }, { 'email': { '$regex': \filtertext\, '$options': 'i' } } ] } If filtertext is a variable then you can use RegExp constructor which creates a regular expression object for matching text with a pattern. For example: var filtertext = "foo"; var rgx = new RegExp(filtertext, "i"); var matchquery = { "$or": [ { "userfullname": rgx }, { "email": rgx } ] }; To stringify the query, you could try: var filtertext = "foo"; var rgx = new RegExp(filtertext, "i"); var matchquery = '{ "$or":[{ "userfullname": {"$regex": '+ rgx.toString() +'} },{ "email":{ "$regex": '+ rgx.toString() + '} }] } }';
Base64Encode for AWS not matching Amazon Example
I seem to be failing at the first hurdle in my quest for Amazon S3 Browser-Based Uploads. Using Amazon's example shown here : http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html Using Groovy/Java, I'm unable to encode the example post policy and produce the same encoding as Amazon. { "expiration": "2015-12-30T12:00:00.000Z", "conditions": [ {"bucket": "sigv4examplebucket"}, ["starts-with", "$key", "user/user1/"], {"acl": "public-read"}, {"success_action_redirect": "http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html"}, ["starts-with", "$Content-Type", "image/"], {"x-amz-meta-uuid": "14365123651274"}, {"x-amz-server-side-encryption": "AES256"}, ["starts-with", "$x-amz-meta-tag", ""], {"x-amz-credential": "AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request"}, {"x-amz-algorithm": "AWS4-HMAC-SHA256"}, {"x-amz-date": "20151229T000000Z" } ] } I have this defined as a Groovy multi line string: String policy_document = ''' { "expiration": "2015-12-30T12:00:00.000Z", "conditions": [ {"bucket": "sigv4examplebucket"}, ["starts-with", "$key", "user/user1/"], {"acl": "public-read"}, {"success_action_redirect": "http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html"}, ["starts-with", "$Content-Type", "image/"], {"x-amz-meta-uuid": "14365123651274"}, {"x-amz-server-side-encryption": "AES256"}, ["starts-with", "$x-amz-meta-tag", ""], {"x-amz-credential": "AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request"}, {"x-amz-algorithm": "AWS4-HMAC-SHA256"}, {"x-amz-date": "20151229T000000Z" } ] } ''' I'm then encoding and verifying with an assert which fails. String base64Policy = (new BASE64Encoder()).encode(policy_document.replaceAll("\n", "").replaceAll("\r", "").getBytes("UTF-8")) assert 'eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJzaWd2NGV4YW1wbGVidWNrZXQifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwNCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCJ9LA0KICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL3NpZ3Y0ZXhhbXBsZWJ1Y2tldC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sDQogICAgeyJ4LWFtei1tZXRhLXV1aWQiOiAiMTQzNjUxMjM2NTEyNzQifSwNCiAgICB7IngtYW16LXNlcnZlci1zaWRlLWVuY3J5cHRpb24iOiAiQUVTMjU2In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sDQoNCiAgICB7IngtYW16LWNyZWRlbnRpYWwiOiAiQUtJQUlPU0ZPRE5ON0VYQU1QTEUvMjAxNTEyMjkvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LA0KICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwNCiAgICB7IngtYW16LWRhdGUiOiAiMjAxNTEyMjlUMDAwMDAwWiIgfQ0KICBdDQp9' == base64Policy Just to help with readability, when I encode I get : eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLCAgImNvbmRpdGlvbnMiOiBbICAgIHsiYnVja2V0IjogInNpZ3Y0ZXhhbXBsZWJ1Y2tldCJ9LCAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwgICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwgICAgeyJzdWNjZXNzX2FjdGlvbl9yZWRpcmVjdCI6ICJodHRwOi8vc2lndjRleGFtcGxlYnVja2V0LnMzLmFtYXpvbmF3cy5jb20vc3VjY2Vzc2Z1bF91cGxvYWQuaHRtbCJ9LCAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sICAgIHsieC1hbXotbWV0YS11dWlkIjogIjE0MzY1MTIzNjUxMjc0In0sICAgIHsieC1hbXotc2VydmVyLXNpZGUtZW5jcnlwdGlvbiI6ICJBRVMyNTYifSwgICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sICAgIHsieC1hbXotY3JlZGVudGlhbCI6ICJBS0lBSU9TRk9ETk43RVhBTVBMRS8yMDE1MTIyOS91cy1lYXN0LTEvczMvYXdzNF9yZXF1ZXN0In0sICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwgICAgeyJ4LWFtei1kYXRlIjogIjIwMTUxMjI5VDAwMDAwMFoiIH0gIF19 But I should be getting : eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJzaWd2NGV4YW1wbGVidWNrZXQifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwNCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCJ9LA0KICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL3NpZ3Y0ZXhhbXBsZWJ1Y2tldC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sDQogICAgeyJ4LWFtei1tZXRhLXV1aWQiOiAiMTQzNjUxMjM2NTEyNzQifSwNCiAgICB7IngtYW16LXNlcnZlci1zaWRlLWVuY3J5cHRpb24iOiAiQUVTMjU2In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sDQoNCiAgICB7IngtYW16LWNyZWRlbnRpYWwiOiAiQUtJQUlPU0ZPRE5ON0VYQU1QTEUvMjAxNTEyMjkvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LA0KICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwNCiAgICB7IngtYW16LWRhdGUiOiAiMjAxNTEyMjlUMDAwMDAwWiIgfQ0KICBdDQp9 I'm hoping a fresh set of eyes will point me in the direction. Many thanks for any advice that can be offered.
The following worked for me in Java. Leave the carriage return and line feeds in place. String policy_document = "{ \"expiration\": \"2015-12-30T12:00:00.000Z\",\n" + " \"conditions\": [\n" + " {\"bucket\": \"sigv4examplebucket\"},\n" + " [\"starts-with\", \"$key\", \"user/user1/\"],\n" + " {\"acl\": \"public-read\"},\n" + " {\"success_action_redirect\": \"http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html\"},\n" + " [\"starts-with\", \"$Content-Type\", \"image/\"],\n" + " {\"x-amz-meta-uuid\": \"14365123651274\"},\n" + " {\"x-amz-server-side-encryption\": \"AES256\"},\n" + " [\"starts-with\", \"$x-amz-meta-tag\", \"\"],\n" + "\n" + " {\"x-amz-credential\": \"AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request\"},\n" + " {\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"},\n" + " {\"x-amz-date\": \"20151229T000000Z\" }\n" + " ]\n" + "}"; String base64Policy = (new BASE64Encoder()).encode(policy_document.getBytes());
Thanks for pointing me in the right direction. The final solution was to add \r\n in that order at the end of each line. String policy_document = "{ \"expiration\": \"2015-12-30T12:00:00.000Z\",\r\n" + " \"conditions\": [\r\n" + " {\"bucket\": \"sigv4examplebucket\"},\r\n" + " [\"starts-with\", \"$key\", \"user/user1/\"],\r\n" + " {\"acl\": \"public-read\"},\r\n" + " {\"success_action_redirect\": \"http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html\"},\r\n" + " [\"starts-with\", \"$Content-Type\", \"image/\"],\r\n" + " {\"x-amz-meta-uuid\": \"14365123651274\"},\r\n" + " {\"x-amz-server-side-encryption\": \"AES256\"},\r\n" + " [\"starts-with\", \"$x-amz-meta-tag\", \"\"],\r\n" + "\r\n" + " {\"x-amz-credential\": \"AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request\"},\r\n" + " {\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"},\r\n" + " {\"x-amz-date\": \"20151229T000000Z\" }\r\n" + " ]\r\n" + "}"; It's unfortunate that it needs to be implemented so rigidly and that using a Groovy multi line string cannot accomplish this to keep the markup cleaner.