prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): pr<|fim_middle|> <|fim▁end|>
int (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : ht <|fim_middle|> elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
ml = self.get_main_page() self.wfile.write(bytes(html,'utf8'))
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': ev <|fim_middle|> elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
ents = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8'))
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': ev <|fim_middle|> elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
ents = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8'))
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: dr <|fim_middle|> elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
ug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8'))
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: co <|fim_middle|> return <|fim▁end|>
m_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8'))
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def ge<|fim_middle|>elf): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
t_main_page(s
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def ge<|fim_middle|>elf,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
t_med(s
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def ge<|fim_middle|>elf,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
t_medicinalproduct(s
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def ge<|fim_middle|>elf): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
t_event(s
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def ge<|fim_middle|>elf, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
t_drug(s
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def ge<|fim_middle|>elf, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
t_com_num(s
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def dr<|fim_middle|>elf,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do_GET(self): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
ug_page(s
<|file_name|>web.py<|end_file_name|><|fim▁begin|># Copyright [2017] [name of copyright owner] # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. # Author : Álvaro Román Royo ([email protected]) import http.server import http.client import json import socketserver class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body> <h1>OpenFDA Client</h1> <form method='get' action='receivedrug'> <input type='submit' value='Enviar a OpenFDA'> </input> </form> <form method='get' action='searchmed'> <input type='text' name='drug'></input> <input type='submit' value='Buscar Medicamento'></input> </form> <form method='get' action='receivecompany'> <input type='submit' value='Find companies'></input> </form> <form method='get' action='searchcom'> <input type='text' name='drug'></input> <input type='submit' value='Buscar medicinalproduct'></input> </form> </body> </html> ''' return html def get_med(self,drug): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=patient.drug.medicinalproduct:'+drug+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_drug(self, events): medicamentos=[] for event in events['results']: medicamentos+=[event['patient']['drug'][0]['medicinalproduct']] return medicamentos def get_com_num(self, events): com_num=[] for event in events['results']: com_num+=[event['companynumb']] return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> </body> </html>''' %(s) return html def do<|fim_middle|>elf): print (self.path) #print (self.path) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() if self.path == '/' : html = self.get_main_page() self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivedrug?': events = self.get_event() medicamentos = self.get_drug(events) html = self.drug_page(medicamentos) self.wfile.write(bytes(html,'utf8')) elif self.path == '/receivecompany?': events = self.get_event() com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchmed' in self.path: drug=self.path.split('=')[1] print (drug) events = self.get_med(drug) com_num = self.get_com_num(events) html = self.drug_page(com_num) self.wfile.write(bytes(html,'utf8')) elif 'searchcom' in self.path: com_num = self.path.split('=')[1] print (com_num) events = self.get_medicinalproduct(com_num) medicinalproduct = self.get_drug(events) html = self.drug_page(medicinalproduct) self.wfile.write(bytes(html,'utf8')) return <|fim▁end|>
_GET(s
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important <|fim▁hole|>class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning<|fim▁end|>
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): <|fim_middle|> class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node]
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): <|fim_middle|> class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node]
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): <|fim_middle|> class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
required_arguments = 1 node_class = nodes.admonition
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): <|fim_middle|> class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
node_class = nodes.attention
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): <|fim_middle|> class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
node_class = nodes.caution
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): <|fim_middle|> class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
node_class = nodes.danger
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): <|fim_middle|> class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
node_class = nodes.error
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): <|fim_middle|> class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
node_class = nodes.hint
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): <|fim_middle|> class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
node_class = nodes.important
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): <|fim_middle|> class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
node_class = nodes.note
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): <|fim_middle|> class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
node_class = nodes.tip
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): <|fim_middle|> <|fim▁end|>
node_class = nodes.warning
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: <|fim_middle|> self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)]
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: <|fim_middle|> self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)]
<|file_name|>admonitions.py<|end_file_name|><|fim▁begin|># $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def <|fim_middle|>(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning <|fim▁end|>
run
<|file_name|>serial_ports.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial<|fim▁hole|> :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports())<|fim▁end|>
def serial_ports(): """ Lists serial port names
<|file_name|>serial_ports.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): <|fim_middle|> if __name__ == '__main__': print(serial_ports()) <|fim▁end|>
""" Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result
<|file_name|>serial_ports.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): <|fim_middle|> elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports()) <|fim▁end|>
ports = ['COM%s' % (i + 1) for i in range(256)]
<|file_name|>serial_ports.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" <|fim_middle|> elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports()) <|fim▁end|>
ports = glob.glob('/dev/cu[A-Za-z]*')
<|file_name|>serial_ports.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): <|fim_middle|> else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports()) <|fim▁end|>
ports = glob.glob('/dev/cu.*')
<|file_name|>serial_ports.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: <|fim_middle|> result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports()) <|fim▁end|>
raise EnvironmentError('Unsupported platform')
<|file_name|>serial_ports.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
print(serial_ports())
<|file_name|>serial_ports.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def <|fim_middle|>(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports()) <|fim▁end|>
serial_ports
<|file_name|>update.py<|end_file_name|><|fim▁begin|>from __future__ import print_function """ Deprecated. Use ``update-tld-names`` command instead. """ __title__ = 'tld.update' __author__ = 'Artur Barseghyan' __copyright__ = '2013-2015 Artur Barseghyan'<|fim▁hole|>_ = lambda x: x if __name__ == '__main__': update_tld_names() print(_("Local TLD names file has been successfully updated!"))<|fim▁end|>
__license__ = 'GPL 2.0/LGPL 2.1' from tld.utils import update_tld_names
<|file_name|>update.py<|end_file_name|><|fim▁begin|>from __future__ import print_function """ Deprecated. Use ``update-tld-names`` command instead. """ __title__ = 'tld.update' __author__ = 'Artur Barseghyan' __copyright__ = '2013-2015 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' from tld.utils import update_tld_names _ = lambda x: x if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
update_tld_names() print(_("Local TLD names file has been successfully updated!"))
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """)<|fim▁hole|> if __name__ == '__main__': unittest.main()<|fim▁end|>
result = spell_checker.check(paragraph)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): <|fim_middle|> <|fim▁end|>
def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main()
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): <|fim_middle|> def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
pass
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): <|fim_middle|> assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?')
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 <|fim_middle|> 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragra<|fim_middle|> "으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
ph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있<|fim_middle|> <|fim▁end|>
습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main()
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim_middle|> <|fim▁end|>
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def <|fim_middle|>(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
setUp
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def <|fim_middle|>(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_basic_check
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert res<|fim_middle|> == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
ult.errors
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' <|fim_middle|>est_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
def t
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.') assert result.errors == 4 assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.' def test_words(self): result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?') assert result.errors == 4 items = result.words assert items[u'한'] == CheckResult.WRONG_SPACING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert items[u'그만하게'] == CheckResult.PASSED assert items[u'할까?'] == CheckResult.WRONG_SPELLING def test_list(self): results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다. 등록 후에는 "https://ubit.info/별칭"으로 자신의 개인<|fim_middle|>를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다. 이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요. 등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다. """) result = spell_checker.check(paragraph) if __name__ == '__main__': unittest.main() <|fim▁end|>
페이지가 생성되며 이 주소(별칭)
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): self.robot.light[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']:<|fim▁hole|><|fim▁end|>
raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine)
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): <|fim_middle|> def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine) <|fim▁end|>
def setup(self): self.robot.light[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed)
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): <|fim_middle|> def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine) <|fim▁end|>
self.robot.light[0].units = "SCALED"
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): self.robot.light[0].units = "SCALED" def step(self): <|fim_middle|> def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine) <|fim▁end|>
leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed)
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): self.robot.light[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): <|fim_middle|> <|fim▁end|>
if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine)
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): self.robot.light[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: <|fim_middle|> return Vehicle('Braitenberg2a', engine) <|fim▁end|>
raise "Robot should have light sensors!"
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def <|fim_middle|>(self): self.robot.light[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine) <|fim▁end|>
setup
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): self.robot.light[0].units = "SCALED" def <|fim_middle|>(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine) <|fim▁end|>
step
<|file_name|>BraitenbergVehicle2b.py<|end_file_name|><|fim▁begin|>""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): self.robot.light[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def <|fim_middle|>(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine) <|fim▁end|>
INIT
<|file_name|>arm_32_arm_capstone.py<|end_file_name|><|fim▁begin|># ScratchABit - interactive disassembler #<|fim▁hole|># Copyright (c) 2018 Paul Sokolovsky # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import capstone import _any_capstone dis = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM) def PROCESSOR_ENTRY(): return _any_capstone.Processor("arm_32", dis)<|fim▁end|>
<|file_name|>arm_32_arm_capstone.py<|end_file_name|><|fim▁begin|># ScratchABit - interactive disassembler # # Copyright (c) 2018 Paul Sokolovsky # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import capstone import _any_capstone dis = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM) def PROCESSOR_ENTRY(): <|fim_middle|> <|fim▁end|>
return _any_capstone.Processor("arm_32", dis)
<|file_name|>arm_32_arm_capstone.py<|end_file_name|><|fim▁begin|># ScratchABit - interactive disassembler # # Copyright (c) 2018 Paul Sokolovsky # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import capstone import _any_capstone dis = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM) def <|fim_middle|>(): return _any_capstone.Processor("arm_32", dis) <|fim▁end|>
PROCESSOR_ENTRY
<|file_name|>foursquares.py<|end_file_name|><|fim▁begin|><|fim▁hole|>""" File: foursquares.py Draws squares in the corners of a turtle window. One square is black, another is gray, and the remaining two are in random colors. """ from turtlegraphics import Turtle import random def drawSquare(turtle, x, y, length): turtle.up() turtle.move(x, y) turtle.setDirection(270) turtle.down() for count in xrange(4): turtle.move(length) turtle.turn(90) def main(): turtle = Turtle() #turtle.setWidth(1) # Length of square length = 40 # Relative distances to corners from origin width = turtle.getWidth() / 2 height = turtle.getHeight() / 2 # Black turtle.setColor(0, 0, 0) # Upper left corner drawSquare(turtle, -width, height, length) # Gray turtle.setColor(127, 127, 127) # Lower left corner drawSquare(turtle, -width, length - height, length) # First random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Upper right corner drawSquare(turtle, width - length, height, length) # Second random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Lower right corner drawSquare(turtle, width - length, length - height, length) main()<|fim▁end|>
<|file_name|>foursquares.py<|end_file_name|><|fim▁begin|>""" File: foursquares.py Draws squares in the corners of a turtle window. One square is black, another is gray, and the remaining two are in random colors. """ from turtlegraphics import Turtle import random def drawSquare(turtle, x, y, length): <|fim_middle|> def main(): turtle = Turtle() #turtle.setWidth(1) # Length of square length = 40 # Relative distances to corners from origin width = turtle.getWidth() / 2 height = turtle.getHeight() / 2 # Black turtle.setColor(0, 0, 0) # Upper left corner drawSquare(turtle, -width, height, length) # Gray turtle.setColor(127, 127, 127) # Lower left corner drawSquare(turtle, -width, length - height, length) # First random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Upper right corner drawSquare(turtle, width - length, height, length) # Second random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Lower right corner drawSquare(turtle, width - length, length - height, length) main() <|fim▁end|>
turtle.up() turtle.move(x, y) turtle.setDirection(270) turtle.down() for count in xrange(4): turtle.move(length) turtle.turn(90)
<|file_name|>foursquares.py<|end_file_name|><|fim▁begin|>""" File: foursquares.py Draws squares in the corners of a turtle window. One square is black, another is gray, and the remaining two are in random colors. """ from turtlegraphics import Turtle import random def drawSquare(turtle, x, y, length): turtle.up() turtle.move(x, y) turtle.setDirection(270) turtle.down() for count in xrange(4): turtle.move(length) turtle.turn(90) def main(): <|fim_middle|> main() <|fim▁end|>
turtle = Turtle() #turtle.setWidth(1) # Length of square length = 40 # Relative distances to corners from origin width = turtle.getWidth() / 2 height = turtle.getHeight() / 2 # Black turtle.setColor(0, 0, 0) # Upper left corner drawSquare(turtle, -width, height, length) # Gray turtle.setColor(127, 127, 127) # Lower left corner drawSquare(turtle, -width, length - height, length) # First random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Upper right corner drawSquare(turtle, width - length, height, length) # Second random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Lower right corner drawSquare(turtle, width - length, length - height, length)
<|file_name|>foursquares.py<|end_file_name|><|fim▁begin|>""" File: foursquares.py Draws squares in the corners of a turtle window. One square is black, another is gray, and the remaining two are in random colors. """ from turtlegraphics import Turtle import random def <|fim_middle|>(turtle, x, y, length): turtle.up() turtle.move(x, y) turtle.setDirection(270) turtle.down() for count in xrange(4): turtle.move(length) turtle.turn(90) def main(): turtle = Turtle() #turtle.setWidth(1) # Length of square length = 40 # Relative distances to corners from origin width = turtle.getWidth() / 2 height = turtle.getHeight() / 2 # Black turtle.setColor(0, 0, 0) # Upper left corner drawSquare(turtle, -width, height, length) # Gray turtle.setColor(127, 127, 127) # Lower left corner drawSquare(turtle, -width, length - height, length) # First random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Upper right corner drawSquare(turtle, width - length, height, length) # Second random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Lower right corner drawSquare(turtle, width - length, length - height, length) main() <|fim▁end|>
drawSquare
<|file_name|>foursquares.py<|end_file_name|><|fim▁begin|>""" File: foursquares.py Draws squares in the corners of a turtle window. One square is black, another is gray, and the remaining two are in random colors. """ from turtlegraphics import Turtle import random def drawSquare(turtle, x, y, length): turtle.up() turtle.move(x, y) turtle.setDirection(270) turtle.down() for count in xrange(4): turtle.move(length) turtle.turn(90) def <|fim_middle|>(): turtle = Turtle() #turtle.setWidth(1) # Length of square length = 40 # Relative distances to corners from origin width = turtle.getWidth() / 2 height = turtle.getHeight() / 2 # Black turtle.setColor(0, 0, 0) # Upper left corner drawSquare(turtle, -width, height, length) # Gray turtle.setColor(127, 127, 127) # Lower left corner drawSquare(turtle, -width, length - height, length) # First random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Upper right corner drawSquare(turtle, width - length, height, length) # Second random color turtle.setColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # Lower right corner drawSquare(turtle, width - length, length - height, length) main() <|fim▁end|>
main
<|file_name|>google.py<|end_file_name|><|fim▁begin|>import json import urllib import urllib2 def shorten(url):<|fim▁hole|> req.add_header('User-Agent','toolbar') results = json.load(urllib2.urlopen(req)) return results['short_url']<|fim▁end|>
gurl = 'http://goo.gl/api/url?url=%s' % urllib.quote(url) req = urllib2.Request(gurl, data='')
<|file_name|>google.py<|end_file_name|><|fim▁begin|>import json import urllib import urllib2 def shorten(url): <|fim_middle|> <|fim▁end|>
gurl = 'http://goo.gl/api/url?url=%s' % urllib.quote(url) req = urllib2.Request(gurl, data='') req.add_header('User-Agent','toolbar') results = json.load(urllib2.urlopen(req)) return results['short_url']
<|file_name|>google.py<|end_file_name|><|fim▁begin|>import json import urllib import urllib2 def <|fim_middle|>(url): gurl = 'http://goo.gl/api/url?url=%s' % urllib.quote(url) req = urllib2.Request(gurl, data='') req.add_header('User-Agent','toolbar') results = json.load(urllib2.urlopen(req)) return results['short_url']<|fim▁end|>
shorten
<|file_name|>dev.py<|end_file_name|><|fim▁begin|><|fim▁hole|> class Dev(Common): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'ffrpg.sql', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } }<|fim▁end|>
from settings.common import Common
<|file_name|>dev.py<|end_file_name|><|fim▁begin|>from settings.common import Common class Dev(Common): <|fim_middle|> <|fim▁end|>
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'ffrpg.sql', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } }
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
default_app_config = 'providers.com.dailyssrn.apps.AppConfig'
<|file_name|>Prob3.py<|end_file_name|><|fim▁begin|># Declaring a Function def recurPowerNew(base, exp): # Base case is when exp = 0 if exp <= 0:<|fim▁hole|> # Recursive Call elif exp % 2 == 0: return recurPowerNew(base*base, exp/2) return base * recurPowerNew(base, exp - 1)<|fim▁end|>
return 1
<|file_name|>Prob3.py<|end_file_name|><|fim▁begin|># Declaring a Function def recurPowerNew(base, exp): # Base case is when exp = 0 <|fim_middle|> <|fim▁end|>
if exp <= 0: return 1 # Recursive Call elif exp % 2 == 0: return recurPowerNew(base*base, exp/2) return base * recurPowerNew(base, exp - 1)
<|file_name|>Prob3.py<|end_file_name|><|fim▁begin|># Declaring a Function def recurPowerNew(base, exp): # Base case is when exp = 0 if exp <= 0: <|fim_middle|> # Recursive Call elif exp % 2 == 0: return recurPowerNew(base*base, exp/2) return base * recurPowerNew(base, exp - 1) <|fim▁end|>
return 1
<|file_name|>Prob3.py<|end_file_name|><|fim▁begin|># Declaring a Function def recurPowerNew(base, exp): # Base case is when exp = 0 if exp <= 0: return 1 # Recursive Call elif exp % 2 == 0: <|fim_middle|> return base * recurPowerNew(base, exp - 1) <|fim▁end|>
return recurPowerNew(base*base, exp/2)
<|file_name|>Prob3.py<|end_file_name|><|fim▁begin|># Declaring a Function def <|fim_middle|>(base, exp): # Base case is when exp = 0 if exp <= 0: return 1 # Recursive Call elif exp % 2 == 0: return recurPowerNew(base*base, exp/2) return base * recurPowerNew(base, exp - 1) <|fim▁end|>
recurPowerNew
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python<|fim▁hole|> from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict<|fim▁end|>
multiprocessing pool with the specified number of threads. """ if mpi:
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): <|fim_middle|> def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): <|fim_middle|> def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
return
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): <|fim_middle|> def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
return map(*args, **kwargs)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): <|fim_middle|> def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
""" Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): <|fim_middle|> class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
""" Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): <|fim_middle|> def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): <|fim_middle|> def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): <|fim_middle|> def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
gui, backend = self.shell.enable_matplotlib(self.new_backend)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): <|fim_middle|> def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
gui, backend = self.shell.enable_matplotlib(self.old_backend)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): <|fim_middle|> class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): <|fim_middle|> <|fim▁end|>
def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): <|fim_middle|> def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
self._dict = dict(somedict) # make a copy self._hash = None
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): <|fim_middle|> def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
return self._dict[key]
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): <|fim_middle|> def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
return len(self._dict)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): <|fim_middle|> def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
return iter(self._dict)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): <|fim_middle|> def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): <|fim_middle|> <|fim▁end|>
return self._dict == other._dict
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: <|fim_middle|> elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...")