max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
scripts/vhdl_gen.py | tpcorrea/hdltools | 0 | 6622251 | <filename>scripts/vhdl_gen.py
#################################################################################
# Copyright 2020 <NAME>
# 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.
#################################################################################
import sys
import os
#TODO:
#process
#Functions
#Procedures
#Custom Custom
#Block
try:
x = tabsize
except NameError:
tabsize = 2
def indent(value):
txt = ""
if value > 0:
for j in range(tabsize * value):
txt = txt + " "
return txt;
def VHDLenum(list):
hdl_code = ""
i = 0
for j in list:
i = i+1
if (i == len(list)):
hdl_code = hdl_code + list[j].code().replace(";","")
else:
hdl_code = hdl_code + list[j].code()
return hdl_code
def DictCode(DictInput):
hdl_code = ""
for j in DictInput:
hdl_code = hdl_code + DictInput[j].code()
return hdl_code
class PackageObj:
def __init__(self, name, *args):
self.source = "File Location Unknown."
self.name = name
if args:
self.operator = args[0]
else:
self.operator = "all"
class PackageList(dict):
def add(self, name, *args):
self[name] = PackageObj(name)
if args:
self[name].operator = arg[0]
class libraryObj:
def __init__(self, name, *args):
self.name = name
self.package = PackageList()
def code(self):
hdl_code = ""
hdl_code = hdl_code + indent(0) + ("library %s;\r\n" % self.name)
for j in self.package:
hdl_code = hdl_code + indent(1) + ("use %s.%s.%s;\r\n" % (self.name, j, self.package[j].operator))
return hdl_code
class libraryList(dict):
def add(self, name):
self[name] = libraryObj(name)
def code(self):
return DictCode(self) + "\r\n"
class GenericObj:
def __init__(self, name, type, init_value):
self.name = name
self.init_value = init_value
self.type = type
def code(self):
hdl_code = indent(2) + ("%s : %s := %s;\r\n" % (self.name, self.type, self.init_value))
return hdl_code
class PortObj:
def __init__(self, name, direction, type):
self.name = name
self.direction = direction
self.type = type
def code(self):
hdl_code = indent(2) + ("%s : %s %s;\r\n" % (self.name, self.direction, self.type))
return hdl_code
class GenericList(dict):
def add(self, name, type, init):
self[name] = GenericObj(name,type,init)
def code(self):
return VHDLenum(self)
class PortList(dict):
def add(self, name, direction, type):
self[name] = PortObj(name, direction, type)
def code(self):
return VHDLenum(self)
class ConstantObj:
def __init__(self, name, type, init):
self.name = name
self.type = type
self.init = init
def code(self):
return indent(1) + "constant %s : %s := %s;\r\n" % (self.name, self.type, self.init)
class SignalObj:
def __init__(self, name, type, *args):
self.name = name
self.type = type
if args:
self.init = args[0]
else:
self.init = "undefined"
def code(self):
if self.init != "undefined":
return indent(1) + ("signal %s : %s := %s;\r\n" % (self.name, self.type, self.init))
else:
return indent(1) + ("signal %s : %s;\r\n" % (self.name, self.type))
class VariableObj:
def __init__(self, name, type, *args):
self.name = name
self.type = type
if args:
self.init = args[0]
else:
self.init = "undefined"
def code(self):
if self.init != "undefined":
return indent(1) + ("variable %s : %s := %s;\r\n" % (self.name, self.type, self.init))
else:
return indent(1) + ("variable %s : %s;\r\n" % (self.name, self.type))
class constantList(dict):
def add(self,name,type,init):
self[name] = ConstantObj(name,type,init)
def code(self):
return DictCode(self)
class signalList(dict):
def add(self,name,type,*args):
self[name] = SignalObj(name,type,*args)
def code(self):
return DictCode(self)
class VariableList(dict):
def add(self,name,type,*args):
self[name] = VariableObj(name,type,*args)
def code(self):
return DictCode(self)
class genericCodeBlock:
def __init__(self, indent):
self.list = []
self.indent = indent
def add(self,text):
self.list.append(text)
def code(self):
hdl_code = ""
for j in self.list:
hdl_code = hdl_code + indent(self.indent) + str(j) + "\r\n"
return hdl_code
class componentObj:
def __init__(self, name):
self.name = name
self.generic = GenericList()
self.port = PortList()
self.filename = ""
def code(self):
hdl_code = indent(0) + ("component %s is\r\n" % self.name)
if (self.generic):
hdl_code = hdl_code + indent(1) + ("generic (\r\n")
hdl_code = hdl_code + self.generic.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
else:
hdl_code = hdl_code + indent(1) + ("--generic (\r\n")
hdl_code = hdl_code + indent(2) + ("--generic_declaration_tag\r\n")
hdl_code = hdl_code + indent(1) + ("--);\r\n")
if (self.port):
hdl_code = hdl_code + indent(1) + ("port (\r\n")
hdl_code = hdl_code + self.port.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
else:
hdl_code = hdl_code + indent(1) + ("--port (\r\n")
hdl_code = hdl_code + indent(2) + ("--port_declaration_tag\r\n")
hdl_code = hdl_code + indent(1) + ("--);\r\n")
hdl_code = hdl_code + indent(0) + ("end component;\r\n")
hdl_code = hdl_code + "\r\n"
return hdl_code
class componentList(dict):
def add(self,name):
self[name] = componentObj(name)
def code(self):
hdl_code = ""
for j in self.list:
hdl_code = hdl_code + self.list[j].code()
return hdl_code
class InstanceObj:
def __init__(self, name, value):
self.name = name
self.value = ""
def code(self):
hdl_code = indent(2) + ("%s => %s,\r\n" % (self.name, self.value))
return hdl_code
class InstanceObjList(dict):
def add(self, name, type, value):
self[name] = InstanceObj(name,value)
def code(self):
return VHDLenum(self)
class componentInstanceObj:
def __init__(self, instance_name, component_name):
self.instance_name = instance_name
self.component_name = component_name
self.generic = InstanceObjList()
self.port = InstanceObjList()
self.filename = ""
def code(self):
hdl_code = indent(0) + ("%s : %s\r\n" % (self.instance_name, self.component_name))
if (self.generic):
hdl_code = hdl_code + indent(1) + ("generic map(\r\n")
hdl_code = hdl_code + self.generic.code()
hdl_code = hdl_code + indent(1) + (")\r\n")
if (self.port):
hdl_code = hdl_code + indent(1) + ("port map(\r\n")
hdl_code = hdl_code + self.port.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
hdl_code = hdl_code + "\r\n"
return hdl_code
class componentInstanceList(dict):
def add(self,name):
self[name] = componentInstanceObj(name)
def code(self):
hdl_code = ""
for j in self.list:
hdl_code = hdl_code + self.list[j].code()
return hdl_code
class Entity:
def __init__(self, name):
self.name = name
self.generic = GenericList()
self.port = PortList()
def code(self):
hdl_code = indent(0) + ("entity %s is\r\n" % self.name)
if (self.generic):
hdl_code = hdl_code + indent(1) + ("generic (\r\n")
hdl_code = hdl_code + self.generic.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
else:
hdl_code = hdl_code + indent(1) + ("--generic (\r\n")
hdl_code = hdl_code + indent(2) + ("--generic_declaration_tag\r\n")
hdl_code = hdl_code + indent(1) + ("--);\r\n")
if (self.port):
hdl_code = hdl_code + indent(1) + ("port (\r\n")
hdl_code = hdl_code + self.port.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
else:
hdl_code = hdl_code + indent(1) + ("--port (\r\n")
hdl_code = hdl_code + indent(2) + ("--port_declaration_tag\r\n")
hdl_code = hdl_code + indent(1) + ("--);\r\n")
hdl_code = hdl_code + indent(0) + ("end %s;\r\n" % self.name)
hdl_code = hdl_code + "\r\n"
return hdl_code
class architecture:
def __init__(self, name, entity_name):
self.Name = name
self.EntityName = entity_name
self.Signal = signalList()
self.Constant = constantList()
self.component = componentList()
self.Functions = ""
self.Procedures = ""
self.customTypes = genericCodeBlock(1)
self.declarationHeader = genericCodeBlock(1)
self.declarationFooter = genericCodeBlock(1)
self.bodyCodeHeader = genericCodeBlock(1)
self.instances = ""
self.blocks = ""
self.process = ""
self.bodyCodeFooter = genericCodeBlock(1)
def code(self):
hdl_code = ""
hdl_code = indent(0) + ("architecture %s of %s is\r\n" % (self.Name, self.EntityName))
hdl_code = hdl_code + "\r\n"
if (self.declarationHeader):
hdl_code = hdl_code + self.declarationHeader.code()
hdl_code = hdl_code + "\r\n"
if (self.component):
hdl_code = hdl_code + self.component.code()
hdl_code = hdl_code + "\r\n"
if (self.Constant):
hdl_code = hdl_code + self.Constant.code()
hdl_code = hdl_code + "\r\n"
if (self.Signal):
hdl_code = hdl_code + self.Signal.code()
hdl_code = hdl_code + "\r\n"
hdl_code = hdl_code + indent(1) + ("--architecture_declaration_tag\r\n")
hdl_code = hdl_code + "\r\n"
hdl_code = hdl_code + indent(0) + ("begin\r\n")
hdl_code = hdl_code + "\r\n"
if (self.bodyCodeHeader):
hdl_code = hdl_code + self.bodyCodeHeader.code()
hdl_code = hdl_code + "\r\n"
hdl_code = hdl_code + indent(1) + ("--architecture_body_tag.\r\n")
hdl_code = hdl_code + "\r\n"
if (self.bodyCodeHeader):
hdl_code = hdl_code + self.bodyCodeFooter.code()
hdl_code = hdl_code + "\r\n"
hdl_code = hdl_code + indent(0) + ("end %s;\r\n" % self.Name)
hdl_code = hdl_code + "\r\n"
return hdl_code
class basicVHDL:
def __init__(self, entity_name, architecture_name):
self.library = libraryList()
self.entity = Entity(entity_name)
self.architecture = architecture(architecture_name, entity_name)
def instance(self, instance_name, generic_list, port_list):
self.tmpinst = componentInstanceObj()
for j in self.entity.generic.list:
self.tmpinst.generic.add(j.name,j.value)
for j in generic_list:
self.tmpinst.generic[j.name].value = [j.name]
for j in self.entity.port.list:
self.tmpinst.port.add(j.name,j.value)
for j in port_list:
self.tmpinst.generic[j.name].value = [j.name]
return self.tmpinst.code()
def write_file(self):
hdl_code = self.code()
if (not os.path.exists("output")):
os.makedirs("output")
output_file_name = "output/"+self.entity.name+".vhd"
#to do: check if file exists. If so, emit a warning and
#check if must clear it.
output_file = open(output_file_name,"w+")
for line in hdl_code:
output_file.write(line)
output_file.close()
return True;
def code(self):
hdl_code = ""
hdl_code = hdl_code + self.library.code()
hdl_code = hdl_code + self.entity.code()
hdl_code = hdl_code + self.architecture.code()
return hdl_code
| <filename>scripts/vhdl_gen.py
#################################################################################
# Copyright 2020 <NAME>
# 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.
#################################################################################
import sys
import os
#TODO:
#process
#Functions
#Procedures
#Custom Custom
#Block
try:
x = tabsize
except NameError:
tabsize = 2
def indent(value):
txt = ""
if value > 0:
for j in range(tabsize * value):
txt = txt + " "
return txt;
def VHDLenum(list):
hdl_code = ""
i = 0
for j in list:
i = i+1
if (i == len(list)):
hdl_code = hdl_code + list[j].code().replace(";","")
else:
hdl_code = hdl_code + list[j].code()
return hdl_code
def DictCode(DictInput):
hdl_code = ""
for j in DictInput:
hdl_code = hdl_code + DictInput[j].code()
return hdl_code
class PackageObj:
def __init__(self, name, *args):
self.source = "File Location Unknown."
self.name = name
if args:
self.operator = args[0]
else:
self.operator = "all"
class PackageList(dict):
def add(self, name, *args):
self[name] = PackageObj(name)
if args:
self[name].operator = arg[0]
class libraryObj:
def __init__(self, name, *args):
self.name = name
self.package = PackageList()
def code(self):
hdl_code = ""
hdl_code = hdl_code + indent(0) + ("library %s;\r\n" % self.name)
for j in self.package:
hdl_code = hdl_code + indent(1) + ("use %s.%s.%s;\r\n" % (self.name, j, self.package[j].operator))
return hdl_code
class libraryList(dict):
def add(self, name):
self[name] = libraryObj(name)
def code(self):
return DictCode(self) + "\r\n"
class GenericObj:
def __init__(self, name, type, init_value):
self.name = name
self.init_value = init_value
self.type = type
def code(self):
hdl_code = indent(2) + ("%s : %s := %s;\r\n" % (self.name, self.type, self.init_value))
return hdl_code
class PortObj:
def __init__(self, name, direction, type):
self.name = name
self.direction = direction
self.type = type
def code(self):
hdl_code = indent(2) + ("%s : %s %s;\r\n" % (self.name, self.direction, self.type))
return hdl_code
class GenericList(dict):
def add(self, name, type, init):
self[name] = GenericObj(name,type,init)
def code(self):
return VHDLenum(self)
class PortList(dict):
def add(self, name, direction, type):
self[name] = PortObj(name, direction, type)
def code(self):
return VHDLenum(self)
class ConstantObj:
def __init__(self, name, type, init):
self.name = name
self.type = type
self.init = init
def code(self):
return indent(1) + "constant %s : %s := %s;\r\n" % (self.name, self.type, self.init)
class SignalObj:
def __init__(self, name, type, *args):
self.name = name
self.type = type
if args:
self.init = args[0]
else:
self.init = "undefined"
def code(self):
if self.init != "undefined":
return indent(1) + ("signal %s : %s := %s;\r\n" % (self.name, self.type, self.init))
else:
return indent(1) + ("signal %s : %s;\r\n" % (self.name, self.type))
class VariableObj:
def __init__(self, name, type, *args):
self.name = name
self.type = type
if args:
self.init = args[0]
else:
self.init = "undefined"
def code(self):
if self.init != "undefined":
return indent(1) + ("variable %s : %s := %s;\r\n" % (self.name, self.type, self.init))
else:
return indent(1) + ("variable %s : %s;\r\n" % (self.name, self.type))
class constantList(dict):
def add(self,name,type,init):
self[name] = ConstantObj(name,type,init)
def code(self):
return DictCode(self)
class signalList(dict):
def add(self,name,type,*args):
self[name] = SignalObj(name,type,*args)
def code(self):
return DictCode(self)
class VariableList(dict):
def add(self,name,type,*args):
self[name] = VariableObj(name,type,*args)
def code(self):
return DictCode(self)
class genericCodeBlock:
def __init__(self, indent):
self.list = []
self.indent = indent
def add(self,text):
self.list.append(text)
def code(self):
hdl_code = ""
for j in self.list:
hdl_code = hdl_code + indent(self.indent) + str(j) + "\r\n"
return hdl_code
class componentObj:
def __init__(self, name):
self.name = name
self.generic = GenericList()
self.port = PortList()
self.filename = ""
def code(self):
hdl_code = indent(0) + ("component %s is\r\n" % self.name)
if (self.generic):
hdl_code = hdl_code + indent(1) + ("generic (\r\n")
hdl_code = hdl_code + self.generic.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
else:
hdl_code = hdl_code + indent(1) + ("--generic (\r\n")
hdl_code = hdl_code + indent(2) + ("--generic_declaration_tag\r\n")
hdl_code = hdl_code + indent(1) + ("--);\r\n")
if (self.port):
hdl_code = hdl_code + indent(1) + ("port (\r\n")
hdl_code = hdl_code + self.port.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
else:
hdl_code = hdl_code + indent(1) + ("--port (\r\n")
hdl_code = hdl_code + indent(2) + ("--port_declaration_tag\r\n")
hdl_code = hdl_code + indent(1) + ("--);\r\n")
hdl_code = hdl_code + indent(0) + ("end component;\r\n")
hdl_code = hdl_code + "\r\n"
return hdl_code
class componentList(dict):
def add(self,name):
self[name] = componentObj(name)
def code(self):
hdl_code = ""
for j in self.list:
hdl_code = hdl_code + self.list[j].code()
return hdl_code
class InstanceObj:
def __init__(self, name, value):
self.name = name
self.value = ""
def code(self):
hdl_code = indent(2) + ("%s => %s,\r\n" % (self.name, self.value))
return hdl_code
class InstanceObjList(dict):
def add(self, name, type, value):
self[name] = InstanceObj(name,value)
def code(self):
return VHDLenum(self)
class componentInstanceObj:
def __init__(self, instance_name, component_name):
self.instance_name = instance_name
self.component_name = component_name
self.generic = InstanceObjList()
self.port = InstanceObjList()
self.filename = ""
def code(self):
hdl_code = indent(0) + ("%s : %s\r\n" % (self.instance_name, self.component_name))
if (self.generic):
hdl_code = hdl_code + indent(1) + ("generic map(\r\n")
hdl_code = hdl_code + self.generic.code()
hdl_code = hdl_code + indent(1) + (")\r\n")
if (self.port):
hdl_code = hdl_code + indent(1) + ("port map(\r\n")
hdl_code = hdl_code + self.port.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
hdl_code = hdl_code + "\r\n"
return hdl_code
class componentInstanceList(dict):
def add(self,name):
self[name] = componentInstanceObj(name)
def code(self):
hdl_code = ""
for j in self.list:
hdl_code = hdl_code + self.list[j].code()
return hdl_code
class Entity:
def __init__(self, name):
self.name = name
self.generic = GenericList()
self.port = PortList()
def code(self):
hdl_code = indent(0) + ("entity %s is\r\n" % self.name)
if (self.generic):
hdl_code = hdl_code + indent(1) + ("generic (\r\n")
hdl_code = hdl_code + self.generic.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
else:
hdl_code = hdl_code + indent(1) + ("--generic (\r\n")
hdl_code = hdl_code + indent(2) + ("--generic_declaration_tag\r\n")
hdl_code = hdl_code + indent(1) + ("--);\r\n")
if (self.port):
hdl_code = hdl_code + indent(1) + ("port (\r\n")
hdl_code = hdl_code + self.port.code()
hdl_code = hdl_code + indent(1) + (");\r\n")
else:
hdl_code = hdl_code + indent(1) + ("--port (\r\n")
hdl_code = hdl_code + indent(2) + ("--port_declaration_tag\r\n")
hdl_code = hdl_code + indent(1) + ("--);\r\n")
hdl_code = hdl_code + indent(0) + ("end %s;\r\n" % self.name)
hdl_code = hdl_code + "\r\n"
return hdl_code
class architecture:
def __init__(self, name, entity_name):
self.Name = name
self.EntityName = entity_name
self.Signal = signalList()
self.Constant = constantList()
self.component = componentList()
self.Functions = ""
self.Procedures = ""
self.customTypes = genericCodeBlock(1)
self.declarationHeader = genericCodeBlock(1)
self.declarationFooter = genericCodeBlock(1)
self.bodyCodeHeader = genericCodeBlock(1)
self.instances = ""
self.blocks = ""
self.process = ""
self.bodyCodeFooter = genericCodeBlock(1)
def code(self):
hdl_code = ""
hdl_code = indent(0) + ("architecture %s of %s is\r\n" % (self.Name, self.EntityName))
hdl_code = hdl_code + "\r\n"
if (self.declarationHeader):
hdl_code = hdl_code + self.declarationHeader.code()
hdl_code = hdl_code + "\r\n"
if (self.component):
hdl_code = hdl_code + self.component.code()
hdl_code = hdl_code + "\r\n"
if (self.Constant):
hdl_code = hdl_code + self.Constant.code()
hdl_code = hdl_code + "\r\n"
if (self.Signal):
hdl_code = hdl_code + self.Signal.code()
hdl_code = hdl_code + "\r\n"
hdl_code = hdl_code + indent(1) + ("--architecture_declaration_tag\r\n")
hdl_code = hdl_code + "\r\n"
hdl_code = hdl_code + indent(0) + ("begin\r\n")
hdl_code = hdl_code + "\r\n"
if (self.bodyCodeHeader):
hdl_code = hdl_code + self.bodyCodeHeader.code()
hdl_code = hdl_code + "\r\n"
hdl_code = hdl_code + indent(1) + ("--architecture_body_tag.\r\n")
hdl_code = hdl_code + "\r\n"
if (self.bodyCodeHeader):
hdl_code = hdl_code + self.bodyCodeFooter.code()
hdl_code = hdl_code + "\r\n"
hdl_code = hdl_code + indent(0) + ("end %s;\r\n" % self.Name)
hdl_code = hdl_code + "\r\n"
return hdl_code
class basicVHDL:
def __init__(self, entity_name, architecture_name):
self.library = libraryList()
self.entity = Entity(entity_name)
self.architecture = architecture(architecture_name, entity_name)
def instance(self, instance_name, generic_list, port_list):
self.tmpinst = componentInstanceObj()
for j in self.entity.generic.list:
self.tmpinst.generic.add(j.name,j.value)
for j in generic_list:
self.tmpinst.generic[j.name].value = [j.name]
for j in self.entity.port.list:
self.tmpinst.port.add(j.name,j.value)
for j in port_list:
self.tmpinst.generic[j.name].value = [j.name]
return self.tmpinst.code()
def write_file(self):
hdl_code = self.code()
if (not os.path.exists("output")):
os.makedirs("output")
output_file_name = "output/"+self.entity.name+".vhd"
#to do: check if file exists. If so, emit a warning and
#check if must clear it.
output_file = open(output_file_name,"w+")
for line in hdl_code:
output_file.write(line)
output_file.close()
return True;
def code(self):
hdl_code = ""
hdl_code = hdl_code + self.library.code()
hdl_code = hdl_code + self.entity.code()
hdl_code = hdl_code + self.architecture.code()
return hdl_code
| en | 0.603935 | ################################################################################# # Copyright 2020 <NAME> # 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. ################################################################################# #TODO: #process #Functions #Procedures #Custom Custom #Block #to do: check if file exists. If so, emit a warning and #check if must clear it. | 2.405687 | 2 |
cli_taxo.py | ali5ter/cli_taxo | 6 | 6622252 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Parse CLI help and pretty print command taxonomy
# @author <NAME> <<EMAIL>>
from __future__ import print_function
import sys
import os
import getopt
import subprocess
from colorama import Fore, Back, Style
import string
import re
from enum import Enum
from collections import defaultdict
INIT_CMD = ''
HELP_OPT = '-h'
HELP_OPT_POSITIONS = Enum('HELP_OPT_POSITIONS', 'before after')
HELP_OPT_POSITION = HELP_OPT_POSITIONS.after.name
OPTIONS_TOKEN_RE = '^Options:'
OPTIONS_RE = '^\s+?(-.+?)\s\s'
COMMANDS_TOKEN_RE = '^(Commands:)|^(Management Commands:)'
COMMANDS_RE = '^\s+(\w+?)\s+'
SHOW_OPTIONS = False
SHOW_COMMANDS = True
EXCLUDE_HELP_OPTS = False
OUTPUT_FORMATS = Enum('OUTPUT_FORMATS', 'tree csv table bash zsh')
OUTPUT_FORMAT = OUTPUT_FORMATS.tree.name
TABLE_COLS = 6
COMPLETION_CMDS = defaultdict(list)
MAX_DEPTH = 3
_DEBUG=False
# If usage description returned is a man page, make sure it
# - returned with out a pager
# - returned with no formatting control chars
os.environ['MANPAGER'] = 'col -b'
def usage():
print('Parse CLI command usage description to Pretty print a CLI '
"command taxonomy")
print("\nUsage:")
print(" cli_taxo <command_name> [--help-opt <string>] "
"[--help-opt-position before|after] "
"[--commands-filter <reg_ex>] "
"[--commands-token <reg_ex>] "
"[--options-filters <reg_ex>] "
"[--options-token <reg_ex>] "
"[--exclude-help] "
"[-o tree|csv|table|bash|zsh | --output tree|csv|table|bash|zsh] "
"[-O | --show-opts] "
"[--depth <number>} "
"[-D]")
print(" cli_taxo -h | --help")
print("\nOptions:")
print(" -h, --help Show this usage description")
print(" --help-opt The command option string used to show the "
"usage description text. Defaults to: ", HELP_OPT)
print(" --help-opt-position Placement of the command option string used to show the "
"usage description text. Typically the help command option is used after a "
"subcommand but sometime, a CLI requires it before. Defaults to: ", HELP_OPT_POSITION)
print(" --commands-filter The regular expression to extract the command "
"from the description text. Defaults to: ", COMMANDS_RE)
print(" --commands-token The regular expression to find the line after "
"which the CLI commands are found in the description text. "
"Defaults to: ", COMMANDS_TOKEN_RE)
print(" --options-filter The regular expression to extract the option "
"from the description text. Defaults to: ", OPTIONS_RE)
print(" --options-token The regular expression to find the line after "
"which the CLI options are found in the description text. "
"Defaults to: ", OPTIONS_TOKEN_RE)
print(" --exclude-help Exclude any help options from the output.")
print(" -o tree|csv|table|bash|zsh, --output tree|csv|table|bash|zsh "
"Defaults to: ", OUTPUT_FORMAT)
print(" -O, --show-opts Include options in the output")
print(" -d, --depth Limit the depth of command to parse. Defaults to: ", MAX_DEPTH)
print(" -D Display debug information to STDERR")
print("\nExamples:")
print("Generate an ASCII tree of the docker CLI commands with no options: ")
print(" cli_taxo.py docker")
print("\nGenerate a tree of the kubectl CLI command and options: ")
print(" cli_taxo.py kubectl \\")
print(" --commands-token 'Commands\s\(\S+\):|Commands:' \\")
print(" --commands-filter '^\s\s((?!#)\S+)\s+[A-Z]' \\")
print(" --options-token '^Options:' \\")
print(" --options-filter '^\s+?(-.+?):' \\")
print(" --show-opts")
print("\nIt is useful to run cli_taxo in debug mode when constructing the ")
print("regualr expressions to filter on the CLI commands and options.")
print("\nThe output formats include an ASCII tree, comma seperated values, a ")
print("very simple wiki/markdown table, and a bash autocompletion script ")
print("\nExamples of using the autocompletion output: ")
print(" cli_taxo.py docker --show-opts --output bash > ~/.docker/completion.bash.inc")
print(" printf \"\\n# Docker shell completion\\nsource '$HOME/.docker/completion.bash.inc'\\n\" >> $HOME/.bash_profile")
print(" source $HOME/.bash_profile")
print("\nTo apply the bash autocompletion to the current shell: ")
print(" source <(cli_taxo.py docker --show-opts --output bash)")
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return iter(p.stdout.readline, '')
def parse_options_and_commands(command, depth=-1):
depth += 1
if depth > MAX_DEPTH : return
if _DEBUG:
eprint("\n{:s}Parsing: {:s}{:s}".format(
' '*depth+Fore.GREEN,
' '.join(map(str, command)),
Fore.RESET))
if OPTIONS_TOKEN_RE:
found_options = False
else:
found_options = True
if COMMANDS_TOKEN_RE:
found_commands = False
else:
found_commands = True
for _line in run_command(command):
line = _line.strip('\n')
if not line or line.isspace(): continue
# line = line.decode('utf-8')
# line = "".join(i for i in line if 31 < ord(i) < 127)
if _DEBUG:
eprint("\n{:s}[{:s}{:s}] Line >>{:s}<<{:s}".format(
' '*depth+Style.DIM,
'C✓' if found_commands else 'C ',
'O✓' if found_options else 'O ',
line, Style.RESET_ALL))
if _OPTIONS_TOKEN_RE.search(line) and not found_options:
found_options = True
if _OPTIONS_RE.search(line) and SHOW_OPTIONS and found_options:
for match in _OPTIONS_RE.search(line).groups():
if _DEBUG:
eprint('{:s} Opt match: >>{:s}<<'.format(
' '*depth, match))
if match and not (_HELP_RE.search(match)
and EXCLUDE_HELP_OPTS):
content = format_item(depth, command, match)
if content is not None:
print(content)
if _COMMANDS_TOKEN_RE.search(line) and not found_commands:
found_commands = True
if _COMMANDS_RE.search(line) and SHOW_COMMANDS and found_commands:
for match in _COMMANDS_RE.search(line).groups():
if _DEBUG:
eprint('{:s} Cmd match: >>{:s}<<'.format(
' '*depth, match))
if match and not (_HELP_RE.search(match)
and EXCLUDE_HELP_OPTS):
content = format_item(depth, command, match)
if content is not None:
print(content)
_command = command[:-1]
if HELP_OPT_POSITION == HELP_OPT_POSITIONS.after.name:
_command.extend([match, HELP_OPT])
elif HELP_OPT_POSITION == HELP_OPT_POSITIONS.before.name:
_command.extend([HELP_OPT, match])
parse_options_and_commands(_command, depth)
depth -= 1
def format_item(depth, command, item):
_command = command[:-1]
item = item.strip()
if OUTPUT_FORMAT == OUTPUT_FORMATS.csv.name:
item = string.replace(item, ',', ' | ')
return ','.join(_command) + ',' + item
elif OUTPUT_FORMAT == OUTPUT_FORMATS.table.name:
return '| '*2 +'| '*depth + item +' |'*(TABLE_COLS-1-depth)
elif OUTPUT_FORMAT == OUTPUT_FORMATS.bash.name or OUTPUT_FORMAT == OUTPUT_FORMATS.zsh.name:
COMPLETION_CMDS[command[depth]].append(item)
return
else: # OUTPUT_FORMATS.tree
if depth == 0:
prefix = '└── '
else:
prefix = '│ '*depth + '└── '
return prefix + item
def create_bash_completion_script():
with open(os.path.dirname(sys.argv[0]) +'/bash_completion.tmpl', 'r') as file:
content = file.read()
content = content.replace('%CMD%', INIT_CMD)
parts = content.partition('%COMPLETIONS%')
content = parts[0]
top_level_commands = []
for command, subcommands in COMPLETION_CMDS.iteritems():
top_level_commands.append(command)
content = content +" "+ command +") cmds=\""+ ' '.join(subcommands) +"\";;\n"
content = content +" *) cmds=\""+ ' '.join(top_level_commands) +'";;'
content = content + parts[2]
print(content)
def create_zsh_completion_script():
print('Generate the bash completion to a file, then run the following to enable it...')
print("\tautoload bashcompinit")
print("\tbashcompinit")
print("\tsource /path/to/your/bash_completion_file")
def main(argv):
try:
opts, non_opts = getopt.gnu_getopt(argv, "ho:d:OD", [
'help-opt=',
'help-opt-position=',
'commands-filter=',
'commands-token=',
'options-filter=',
'options-token=',
'exclude-help',
'show-opts',
'output=',
'depth=',
'help'])
except getopt.GetoptError:
usage()
sys.exit()
if not non_opts:
print("\033[31;1mError: \033[0mPlease provide the command name\n")
usage()
sys.exit()
else:
global INIT_CMD
INIT_CMD = non_opts[0]
for opt, arg in opts:
if opt == '--help-opt':
global HELP_OPT
HELP_OPT = arg
if opt == '--help-opt-position':
global HELP_OPT_POSITION
if arg in HELP_OPT_POSITIONS.__members__:
HELP_OPT_POSITION = arg
else:
print("\033[31;1mError: \033[0mPlease use the correct help option position\n")
usage()
sys.exit()
elif opt == '--commands-filter':
global COMMANDS_RE
COMMANDS_RE = arg
elif opt == '--commands-token':
global COMMANDS_TOKEN_RE
COMMANDS_TOKEN_RE = arg
elif opt == '--options-filter':
global OPTIONS_RE
OPTIONS_RE = arg
elif opt == '--options-token':
global OPTIONS_TOKEN_RE
OPTIONS_TOKEN_RE = arg
elif opt == '--exclude-help':
global EXCLUDE_HELP_OPTS
EXCLUDE_HELP_OPTS = True
elif opt in ('-o', '--output'):
global OUTPUT_FORMAT
if arg in OUTPUT_FORMATS.__members__:
OUTPUT_FORMAT = arg
else:
print("\033[31;1mError: \033[0mPlease use the correct output format\n")
usage()
sys.exit()
elif opt in ('-O', '--show_opts'):
global SHOW_OPTIONS
SHOW_OPTIONS = True
elif opt in ('-d', '--depth'):
global MAX_DEPTH
MAX_DEPTH = arg
elif opt == '-D':
global _DEBUG
_DEBUG = True
elif opt in ('-h', '--help'):
usage()
sys.exit()
if _DEBUG:
eprint('INT_CMD:', INIT_CMD)
eprint('HELP_OPT:', HELP_OPT)
eprint('HELP_OPT_POSITION:', HELP_OPT_POSITION)
eprint('OPTIONS_TOKEN_RE:', OPTIONS_TOKEN_RE)
eprint('OPTIONS_RE:', OPTIONS_RE)
eprint('COMMANDS_TOKEN_RE:', COMMANDS_TOKEN_RE)
eprint('COMMANDS_RE:', COMMANDS_RE)
eprint('SHOW_OPTIONS:', SHOW_OPTIONS)
eprint('SHOW_COMMANDS:', SHOW_COMMANDS)
eprint('EXCLUDE_HELP_OPTS:', EXCLUDE_HELP_OPTS)
eprint('OUTPUT_FORMAT:', OUTPUT_FORMAT)
global _OPTIONS_TOKEN_RE
_OPTIONS_TOKEN_RE = re.compile(r""+OPTIONS_TOKEN_RE)
global _OPTIONS_RE
_OPTIONS_RE = re.compile(r""+OPTIONS_RE)
global _COMMANDS_TOKEN_RE
_COMMANDS_TOKEN_RE = re.compile(r""+COMMANDS_TOKEN_RE)
global _COMMANDS_RE
_COMMANDS_RE = re.compile(r""+COMMANDS_RE)
global _HELP_RE
_HELP_RE = re.compile(r'help')
if OUTPUT_FORMAT == OUTPUT_FORMATS.table.name:
print('| '+ INIT_CMD +' |'*(TABLE_COLS))
elif OUTPUT_FORMAT == OUTPUT_FORMATS.bash.name or OUTPUT_FORMAT == OUTPUT_FORMATS.zsh.name:
pass
else:
print(INIT_CMD)
parse_options_and_commands([INIT_CMD, HELP_OPT])
if OUTPUT_FORMAT == OUTPUT_FORMATS.bash.name:
create_bash_completion_script()
elif OUTPUT_FORMAT == OUTPUT_FORMATS.zsh.name:
create_zsh_completion_script()
del os.environ['MANPAGER']
if __name__ == "__main__":
main(sys.argv[1:])
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Parse CLI help and pretty print command taxonomy
# @author <NAME> <<EMAIL>>
from __future__ import print_function
import sys
import os
import getopt
import subprocess
from colorama import Fore, Back, Style
import string
import re
from enum import Enum
from collections import defaultdict
INIT_CMD = ''
HELP_OPT = '-h'
HELP_OPT_POSITIONS = Enum('HELP_OPT_POSITIONS', 'before after')
HELP_OPT_POSITION = HELP_OPT_POSITIONS.after.name
OPTIONS_TOKEN_RE = '^Options:'
OPTIONS_RE = '^\s+?(-.+?)\s\s'
COMMANDS_TOKEN_RE = '^(Commands:)|^(Management Commands:)'
COMMANDS_RE = '^\s+(\w+?)\s+'
SHOW_OPTIONS = False
SHOW_COMMANDS = True
EXCLUDE_HELP_OPTS = False
OUTPUT_FORMATS = Enum('OUTPUT_FORMATS', 'tree csv table bash zsh')
OUTPUT_FORMAT = OUTPUT_FORMATS.tree.name
TABLE_COLS = 6
COMPLETION_CMDS = defaultdict(list)
MAX_DEPTH = 3
_DEBUG=False
# If usage description returned is a man page, make sure it
# - returned with out a pager
# - returned with no formatting control chars
os.environ['MANPAGER'] = 'col -b'
def usage():
print('Parse CLI command usage description to Pretty print a CLI '
"command taxonomy")
print("\nUsage:")
print(" cli_taxo <command_name> [--help-opt <string>] "
"[--help-opt-position before|after] "
"[--commands-filter <reg_ex>] "
"[--commands-token <reg_ex>] "
"[--options-filters <reg_ex>] "
"[--options-token <reg_ex>] "
"[--exclude-help] "
"[-o tree|csv|table|bash|zsh | --output tree|csv|table|bash|zsh] "
"[-O | --show-opts] "
"[--depth <number>} "
"[-D]")
print(" cli_taxo -h | --help")
print("\nOptions:")
print(" -h, --help Show this usage description")
print(" --help-opt The command option string used to show the "
"usage description text. Defaults to: ", HELP_OPT)
print(" --help-opt-position Placement of the command option string used to show the "
"usage description text. Typically the help command option is used after a "
"subcommand but sometime, a CLI requires it before. Defaults to: ", HELP_OPT_POSITION)
print(" --commands-filter The regular expression to extract the command "
"from the description text. Defaults to: ", COMMANDS_RE)
print(" --commands-token The regular expression to find the line after "
"which the CLI commands are found in the description text. "
"Defaults to: ", COMMANDS_TOKEN_RE)
print(" --options-filter The regular expression to extract the option "
"from the description text. Defaults to: ", OPTIONS_RE)
print(" --options-token The regular expression to find the line after "
"which the CLI options are found in the description text. "
"Defaults to: ", OPTIONS_TOKEN_RE)
print(" --exclude-help Exclude any help options from the output.")
print(" -o tree|csv|table|bash|zsh, --output tree|csv|table|bash|zsh "
"Defaults to: ", OUTPUT_FORMAT)
print(" -O, --show-opts Include options in the output")
print(" -d, --depth Limit the depth of command to parse. Defaults to: ", MAX_DEPTH)
print(" -D Display debug information to STDERR")
print("\nExamples:")
print("Generate an ASCII tree of the docker CLI commands with no options: ")
print(" cli_taxo.py docker")
print("\nGenerate a tree of the kubectl CLI command and options: ")
print(" cli_taxo.py kubectl \\")
print(" --commands-token 'Commands\s\(\S+\):|Commands:' \\")
print(" --commands-filter '^\s\s((?!#)\S+)\s+[A-Z]' \\")
print(" --options-token '^Options:' \\")
print(" --options-filter '^\s+?(-.+?):' \\")
print(" --show-opts")
print("\nIt is useful to run cli_taxo in debug mode when constructing the ")
print("regualr expressions to filter on the CLI commands and options.")
print("\nThe output formats include an ASCII tree, comma seperated values, a ")
print("very simple wiki/markdown table, and a bash autocompletion script ")
print("\nExamples of using the autocompletion output: ")
print(" cli_taxo.py docker --show-opts --output bash > ~/.docker/completion.bash.inc")
print(" printf \"\\n# Docker shell completion\\nsource '$HOME/.docker/completion.bash.inc'\\n\" >> $HOME/.bash_profile")
print(" source $HOME/.bash_profile")
print("\nTo apply the bash autocompletion to the current shell: ")
print(" source <(cli_taxo.py docker --show-opts --output bash)")
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return iter(p.stdout.readline, '')
def parse_options_and_commands(command, depth=-1):
depth += 1
if depth > MAX_DEPTH : return
if _DEBUG:
eprint("\n{:s}Parsing: {:s}{:s}".format(
' '*depth+Fore.GREEN,
' '.join(map(str, command)),
Fore.RESET))
if OPTIONS_TOKEN_RE:
found_options = False
else:
found_options = True
if COMMANDS_TOKEN_RE:
found_commands = False
else:
found_commands = True
for _line in run_command(command):
line = _line.strip('\n')
if not line or line.isspace(): continue
# line = line.decode('utf-8')
# line = "".join(i for i in line if 31 < ord(i) < 127)
if _DEBUG:
eprint("\n{:s}[{:s}{:s}] Line >>{:s}<<{:s}".format(
' '*depth+Style.DIM,
'C✓' if found_commands else 'C ',
'O✓' if found_options else 'O ',
line, Style.RESET_ALL))
if _OPTIONS_TOKEN_RE.search(line) and not found_options:
found_options = True
if _OPTIONS_RE.search(line) and SHOW_OPTIONS and found_options:
for match in _OPTIONS_RE.search(line).groups():
if _DEBUG:
eprint('{:s} Opt match: >>{:s}<<'.format(
' '*depth, match))
if match and not (_HELP_RE.search(match)
and EXCLUDE_HELP_OPTS):
content = format_item(depth, command, match)
if content is not None:
print(content)
if _COMMANDS_TOKEN_RE.search(line) and not found_commands:
found_commands = True
if _COMMANDS_RE.search(line) and SHOW_COMMANDS and found_commands:
for match in _COMMANDS_RE.search(line).groups():
if _DEBUG:
eprint('{:s} Cmd match: >>{:s}<<'.format(
' '*depth, match))
if match and not (_HELP_RE.search(match)
and EXCLUDE_HELP_OPTS):
content = format_item(depth, command, match)
if content is not None:
print(content)
_command = command[:-1]
if HELP_OPT_POSITION == HELP_OPT_POSITIONS.after.name:
_command.extend([match, HELP_OPT])
elif HELP_OPT_POSITION == HELP_OPT_POSITIONS.before.name:
_command.extend([HELP_OPT, match])
parse_options_and_commands(_command, depth)
depth -= 1
def format_item(depth, command, item):
_command = command[:-1]
item = item.strip()
if OUTPUT_FORMAT == OUTPUT_FORMATS.csv.name:
item = string.replace(item, ',', ' | ')
return ','.join(_command) + ',' + item
elif OUTPUT_FORMAT == OUTPUT_FORMATS.table.name:
return '| '*2 +'| '*depth + item +' |'*(TABLE_COLS-1-depth)
elif OUTPUT_FORMAT == OUTPUT_FORMATS.bash.name or OUTPUT_FORMAT == OUTPUT_FORMATS.zsh.name:
COMPLETION_CMDS[command[depth]].append(item)
return
else: # OUTPUT_FORMATS.tree
if depth == 0:
prefix = '└── '
else:
prefix = '│ '*depth + '└── '
return prefix + item
def create_bash_completion_script():
with open(os.path.dirname(sys.argv[0]) +'/bash_completion.tmpl', 'r') as file:
content = file.read()
content = content.replace('%CMD%', INIT_CMD)
parts = content.partition('%COMPLETIONS%')
content = parts[0]
top_level_commands = []
for command, subcommands in COMPLETION_CMDS.iteritems():
top_level_commands.append(command)
content = content +" "+ command +") cmds=\""+ ' '.join(subcommands) +"\";;\n"
content = content +" *) cmds=\""+ ' '.join(top_level_commands) +'";;'
content = content + parts[2]
print(content)
def create_zsh_completion_script():
print('Generate the bash completion to a file, then run the following to enable it...')
print("\tautoload bashcompinit")
print("\tbashcompinit")
print("\tsource /path/to/your/bash_completion_file")
def main(argv):
try:
opts, non_opts = getopt.gnu_getopt(argv, "ho:d:OD", [
'help-opt=',
'help-opt-position=',
'commands-filter=',
'commands-token=',
'options-filter=',
'options-token=',
'exclude-help',
'show-opts',
'output=',
'depth=',
'help'])
except getopt.GetoptError:
usage()
sys.exit()
if not non_opts:
print("\033[31;1mError: \033[0mPlease provide the command name\n")
usage()
sys.exit()
else:
global INIT_CMD
INIT_CMD = non_opts[0]
for opt, arg in opts:
if opt == '--help-opt':
global HELP_OPT
HELP_OPT = arg
if opt == '--help-opt-position':
global HELP_OPT_POSITION
if arg in HELP_OPT_POSITIONS.__members__:
HELP_OPT_POSITION = arg
else:
print("\033[31;1mError: \033[0mPlease use the correct help option position\n")
usage()
sys.exit()
elif opt == '--commands-filter':
global COMMANDS_RE
COMMANDS_RE = arg
elif opt == '--commands-token':
global COMMANDS_TOKEN_RE
COMMANDS_TOKEN_RE = arg
elif opt == '--options-filter':
global OPTIONS_RE
OPTIONS_RE = arg
elif opt == '--options-token':
global OPTIONS_TOKEN_RE
OPTIONS_TOKEN_RE = arg
elif opt == '--exclude-help':
global EXCLUDE_HELP_OPTS
EXCLUDE_HELP_OPTS = True
elif opt in ('-o', '--output'):
global OUTPUT_FORMAT
if arg in OUTPUT_FORMATS.__members__:
OUTPUT_FORMAT = arg
else:
print("\033[31;1mError: \033[0mPlease use the correct output format\n")
usage()
sys.exit()
elif opt in ('-O', '--show_opts'):
global SHOW_OPTIONS
SHOW_OPTIONS = True
elif opt in ('-d', '--depth'):
global MAX_DEPTH
MAX_DEPTH = arg
elif opt == '-D':
global _DEBUG
_DEBUG = True
elif opt in ('-h', '--help'):
usage()
sys.exit()
if _DEBUG:
eprint('INT_CMD:', INIT_CMD)
eprint('HELP_OPT:', HELP_OPT)
eprint('HELP_OPT_POSITION:', HELP_OPT_POSITION)
eprint('OPTIONS_TOKEN_RE:', OPTIONS_TOKEN_RE)
eprint('OPTIONS_RE:', OPTIONS_RE)
eprint('COMMANDS_TOKEN_RE:', COMMANDS_TOKEN_RE)
eprint('COMMANDS_RE:', COMMANDS_RE)
eprint('SHOW_OPTIONS:', SHOW_OPTIONS)
eprint('SHOW_COMMANDS:', SHOW_COMMANDS)
eprint('EXCLUDE_HELP_OPTS:', EXCLUDE_HELP_OPTS)
eprint('OUTPUT_FORMAT:', OUTPUT_FORMAT)
global _OPTIONS_TOKEN_RE
_OPTIONS_TOKEN_RE = re.compile(r""+OPTIONS_TOKEN_RE)
global _OPTIONS_RE
_OPTIONS_RE = re.compile(r""+OPTIONS_RE)
global _COMMANDS_TOKEN_RE
_COMMANDS_TOKEN_RE = re.compile(r""+COMMANDS_TOKEN_RE)
global _COMMANDS_RE
_COMMANDS_RE = re.compile(r""+COMMANDS_RE)
global _HELP_RE
_HELP_RE = re.compile(r'help')
if OUTPUT_FORMAT == OUTPUT_FORMATS.table.name:
print('| '+ INIT_CMD +' |'*(TABLE_COLS))
elif OUTPUT_FORMAT == OUTPUT_FORMATS.bash.name or OUTPUT_FORMAT == OUTPUT_FORMATS.zsh.name:
pass
else:
print(INIT_CMD)
parse_options_and_commands([INIT_CMD, HELP_OPT])
if OUTPUT_FORMAT == OUTPUT_FORMATS.bash.name:
create_bash_completion_script()
elif OUTPUT_FORMAT == OUTPUT_FORMATS.zsh.name:
create_zsh_completion_script()
del os.environ['MANPAGER']
if __name__ == "__main__":
main(sys.argv[1:]) | en | 0.561526 | #!/usr/bin/env python # -*- coding: utf-8 -*- # Parse CLI help and pretty print command taxonomy # @author <NAME> <<EMAIL>> # If usage description returned is a man page, make sure it # - returned with out a pager # - returned with no formatting control chars #)\S+)\s+[A-Z]' \\") # Docker shell completion\\nsource '$HOME/.docker/completion.bash.inc'\\n\" >> $HOME/.bash_profile") # line = line.decode('utf-8') # line = "".join(i for i in line if 31 < ord(i) < 127) # OUTPUT_FORMATS.tree | 2.422898 | 2 |
sei_py/base/__init__.py | xh4zr/sei_py | 1 | 6622253 | from sei_py.base.page import Page
from sei_py.base.providers import UrlProvider
from sei_py.base.exception import SeiException
| from sei_py.base.page import Page
from sei_py.base.providers import UrlProvider
from sei_py.base.exception import SeiException
| none | 1 | 1.145393 | 1 | |
datahub/dbmaintenance/test/commands/test_update_order_sector.py | Staberinde/data-hub-api | 6 | 6622254 | from io import BytesIO
import factory
import pytest
from django.core.management import call_command
from reversion.models import Version
from datahub.metadata.test.factories import SectorFactory
from datahub.omis.order.test.factories import OrderFactory
pytestmark = pytest.mark.django_db
def test_happy_path(s3_stubber):
"""Test that the command updates the specified records."""
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk}
{orders[2].pk},{old_sectors[2].pk},{new_sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
for order in orders:
order.refresh_from_db()
assert [order.sector for order in orders] == new_sectors
def test_non_existent_order(s3_stubber, caplog):
"""Test that the command logs an error when the order PK does not exist."""
caplog.set_level('ERROR')
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk}
00000000-0000-0000-0000-000000000000,{old_sectors[2].pk},{new_sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
for order in orders:
order.refresh_from_db()
assert 'Order matching query does not exist' in caplog.text
assert len(caplog.records) == 1
assert [order.sector for order in orders] == [
new_sectors[0], new_sectors[1], old_sectors[2],
]
def test_non_existent_sector(s3_stubber, caplog):
"""Test that the command logs an error when the sector PK does not exist."""
caplog.set_level('ERROR')
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk}
{orders[2].pk},{old_sectors[2].pk},00000000-0000-0000-0000-000000000000
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
for order in orders:
order.refresh_from_db()
assert 'Sector matching query does not exist' in caplog.text
assert len(caplog.records) == 1
assert [order.sector for order in orders] == [
new_sectors[0], new_sectors[1], old_sectors[2],
]
def test_no_change(s3_stubber, caplog):
"""Test that the command ignores records that haven't changed
or records with incorrect current values.
"""
caplog.set_level('WARNING')
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{old_sectors[1].pk}
{orders[2].pk},00000000-0000-0000-0000-000000000000,{new_sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
for order in orders:
order.refresh_from_db()
assert f'Not updating order {orders[1]} as its sector has not changed' in caplog.text
assert f'Not updating order {orders[2]} as its sector has not changed' in caplog.text
assert len(caplog.records) == 2
assert [order.sector for order in orders] == [
new_sectors[0], old_sectors[1], old_sectors[2],
]
def test_simulate(s3_stubber):
"""Test that the command simulates updates if --simulate is passed in."""
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk}
{orders[2].pk},{old_sectors[2].pk},{new_sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key, simulate=True)
for order in orders:
order.refresh_from_db()
assert [order.sector for order in orders] == old_sectors
def test_audit_log(s3_stubber):
"""Test that reversion revisions are created."""
sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1', 'sector_2', 'sector_3']),
)
order_without_change = OrderFactory(
reference='order_1',
sector_id=sectors[0].pk,
)
order_with_change = OrderFactory(
reference='order_2',
sector_id=sectors[1].pk,
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{order_without_change.pk},{sectors[0].pk},{sectors[0].pk}
{order_with_change.pk},{sectors[1].pk},{sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
versions = Version.objects.get_for_object(order_without_change)
assert versions.count() == 0
versions = Version.objects.get_for_object(order_with_change)
assert versions.count() == 1
assert versions[0].revision.get_comment() == 'Order sector correction.'
| from io import BytesIO
import factory
import pytest
from django.core.management import call_command
from reversion.models import Version
from datahub.metadata.test.factories import SectorFactory
from datahub.omis.order.test.factories import OrderFactory
pytestmark = pytest.mark.django_db
def test_happy_path(s3_stubber):
"""Test that the command updates the specified records."""
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk}
{orders[2].pk},{old_sectors[2].pk},{new_sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
for order in orders:
order.refresh_from_db()
assert [order.sector for order in orders] == new_sectors
def test_non_existent_order(s3_stubber, caplog):
"""Test that the command logs an error when the order PK does not exist."""
caplog.set_level('ERROR')
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk}
00000000-0000-0000-0000-000000000000,{old_sectors[2].pk},{new_sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
for order in orders:
order.refresh_from_db()
assert 'Order matching query does not exist' in caplog.text
assert len(caplog.records) == 1
assert [order.sector for order in orders] == [
new_sectors[0], new_sectors[1], old_sectors[2],
]
def test_non_existent_sector(s3_stubber, caplog):
"""Test that the command logs an error when the sector PK does not exist."""
caplog.set_level('ERROR')
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk}
{orders[2].pk},{old_sectors[2].pk},00000000-0000-0000-0000-000000000000
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
for order in orders:
order.refresh_from_db()
assert 'Sector matching query does not exist' in caplog.text
assert len(caplog.records) == 1
assert [order.sector for order in orders] == [
new_sectors[0], new_sectors[1], old_sectors[2],
]
def test_no_change(s3_stubber, caplog):
"""Test that the command ignores records that haven't changed
or records with incorrect current values.
"""
caplog.set_level('WARNING')
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{old_sectors[1].pk}
{orders[2].pk},00000000-0000-0000-0000-000000000000,{new_sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
for order in orders:
order.refresh_from_db()
assert f'Not updating order {orders[1]} as its sector has not changed' in caplog.text
assert f'Not updating order {orders[2]} as its sector has not changed' in caplog.text
assert len(caplog.records) == 2
assert [order.sector for order in orders] == [
new_sectors[0], old_sectors[1], old_sectors[2],
]
def test_simulate(s3_stubber):
"""Test that the command simulates updates if --simulate is passed in."""
old_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_old', 'sector_2_old', 'sector_3_old']),
)
orders = OrderFactory.create_batch(
3,
reference=factory.Iterator(['order_1', 'order_2', 'order_3']),
sector_id=factory.Iterator([sector.pk for sector in old_sectors]),
)
new_sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1_new', 'sector_2_new', 'sector_3_new']),
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk}
{orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk}
{orders[2].pk},{old_sectors[2].pk},{new_sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key, simulate=True)
for order in orders:
order.refresh_from_db()
assert [order.sector for order in orders] == old_sectors
def test_audit_log(s3_stubber):
"""Test that reversion revisions are created."""
sectors = SectorFactory.create_batch(
3,
segment=factory.Iterator(['sector_1', 'sector_2', 'sector_3']),
)
order_without_change = OrderFactory(
reference='order_1',
sector_id=sectors[0].pk,
)
order_with_change = OrderFactory(
reference='order_2',
sector_id=sectors[1].pk,
)
bucket = 'test_bucket'
object_key = 'test_key'
csv_content = f"""id,old_sector_id,new_sector_id
{order_without_change.pk},{sectors[0].pk},{sectors[0].pk}
{order_with_change.pk},{sectors[1].pk},{sectors[2].pk}
"""
s3_stubber.add_response(
'get_object',
{
'Body': BytesIO(csv_content.encode(encoding='utf-8')),
},
expected_params={
'Bucket': bucket,
'Key': object_key,
},
)
call_command('update_order_sector', bucket, object_key)
versions = Version.objects.get_for_object(order_without_change)
assert versions.count() == 0
versions = Version.objects.get_for_object(order_with_change)
assert versions.count() == 1
assert versions[0].revision.get_comment() == 'Order sector correction.'
| en | 0.260559 | Test that the command updates the specified records. id,old_sector_id,new_sector_id {orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk} {orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk} {orders[2].pk},{old_sectors[2].pk},{new_sectors[2].pk} Test that the command logs an error when the order PK does not exist. id,old_sector_id,new_sector_id {orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk} {orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk} 00000000-0000-0000-0000-000000000000,{old_sectors[2].pk},{new_sectors[2].pk} Test that the command logs an error when the sector PK does not exist. id,old_sector_id,new_sector_id {orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk} {orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk} {orders[2].pk},{old_sectors[2].pk},00000000-0000-0000-0000-000000000000 Test that the command ignores records that haven't changed or records with incorrect current values. id,old_sector_id,new_sector_id {orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk} {orders[1].pk},{old_sectors[1].pk},{old_sectors[1].pk} {orders[2].pk},00000000-0000-0000-0000-000000000000,{new_sectors[2].pk} Test that the command simulates updates if --simulate is passed in. id,old_sector_id,new_sector_id {orders[0].pk},{old_sectors[0].pk},{new_sectors[0].pk} {orders[1].pk},{old_sectors[1].pk},{new_sectors[1].pk} {orders[2].pk},{old_sectors[2].pk},{new_sectors[2].pk} Test that reversion revisions are created. id,old_sector_id,new_sector_id {order_without_change.pk},{sectors[0].pk},{sectors[0].pk} {order_with_change.pk},{sectors[1].pk},{sectors[2].pk} | 1.987566 | 2 |
enthought/mayavi/tools/probe_data.py | enthought/etsproxy | 3 | 6622255 | <filename>enthought/mayavi/tools/probe_data.py
# proxy module
from __future__ import absolute_import
from mayavi.tools.probe_data import *
| <filename>enthought/mayavi/tools/probe_data.py
# proxy module
from __future__ import absolute_import
from mayavi.tools.probe_data import *
| es | 0.125187 | # proxy module | 1.000334 | 1 |
src/extra/urls.py | LokotamaTheMastermind/website-portfolio-django-project | 0 | 6622256 | from django.urls import path
from .views import *
app_name = 'policies'
urlpatterns = [
path('privacy/', privacy, name='privacy-policy'),
path('terms-conditions/', terms_conditions, name='terms-and-conditions')
]
| from django.urls import path
from .views import *
app_name = 'policies'
urlpatterns = [
path('privacy/', privacy, name='privacy-policy'),
path('terms-conditions/', terms_conditions, name='terms-and-conditions')
]
| none | 1 | 1.536335 | 2 | |
docs/components_page/components/index/simple.py | glsdown/dash-bootstrap-components | 776 | 6622257 | # 1. Import Dash
import dash
import dash_bootstrap_components as dbc
# 2. Create a Dash app instance
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
# 3. Add the example to the app's layout
# First we copy the snippet from the docs
badge = dbc.Button(
[
"Notifications",
dbc.Badge("4", color="light", text_color="primary", className="ms-1"),
],
color="primary",
)
# Then we incorporate the snippet into our layout.
# This example keeps it simple and just wraps it in a Container
app.layout = dbc.Container(badge, fluid=True)
# 5. Start the Dash server
if __name__ == "__main__":
app.run_server()
| # 1. Import Dash
import dash
import dash_bootstrap_components as dbc
# 2. Create a Dash app instance
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
# 3. Add the example to the app's layout
# First we copy the snippet from the docs
badge = dbc.Button(
[
"Notifications",
dbc.Badge("4", color="light", text_color="primary", className="ms-1"),
],
color="primary",
)
# Then we incorporate the snippet into our layout.
# This example keeps it simple and just wraps it in a Container
app.layout = dbc.Container(badge, fluid=True)
# 5. Start the Dash server
if __name__ == "__main__":
app.run_server()
| en | 0.731728 | # 1. Import Dash # 2. Create a Dash app instance # 3. Add the example to the app's layout # First we copy the snippet from the docs # Then we incorporate the snippet into our layout. # This example keeps it simple and just wraps it in a Container # 5. Start the Dash server | 2.900667 | 3 |
jira_pert/model/cycle_detector_dfs.py | unitatem/jira-pert | 0 | 6622258 | from jira_pert.model.pert_graph import PertGraph
class CycleDetectorDFS(object):
def __init__(self, graph: PertGraph):
self._graph = graph
self._cycle = []
def is_cyclic(self):
self._cycle = []
visited = dict()
recursion_stack = dict()
for key in self._graph.get_graph().keys():
visited[key] = False
recursion_stack[key] = False
for key in self._graph.get_graph().keys():
if self._is_cyclic(key, visited, recursion_stack):
self._cycle.append(key)
return True
return False
def _is_cyclic(self, key, visited, recursion_stack):
if not visited[key]:
visited[key] = True
recursion_stack[key] = True
for dependency_key in self._graph.get_graph()[key].dependencies:
if not visited[dependency_key] and self._is_cyclic(dependency_key, visited, recursion_stack):
self._cycle.append(dependency_key)
return True
elif recursion_stack[dependency_key]:
self._cycle.append(dependency_key)
return True
recursion_stack[key] = False
return False
def get_cycle(self):
return self._cycle
| from jira_pert.model.pert_graph import PertGraph
class CycleDetectorDFS(object):
def __init__(self, graph: PertGraph):
self._graph = graph
self._cycle = []
def is_cyclic(self):
self._cycle = []
visited = dict()
recursion_stack = dict()
for key in self._graph.get_graph().keys():
visited[key] = False
recursion_stack[key] = False
for key in self._graph.get_graph().keys():
if self._is_cyclic(key, visited, recursion_stack):
self._cycle.append(key)
return True
return False
def _is_cyclic(self, key, visited, recursion_stack):
if not visited[key]:
visited[key] = True
recursion_stack[key] = True
for dependency_key in self._graph.get_graph()[key].dependencies:
if not visited[dependency_key] and self._is_cyclic(dependency_key, visited, recursion_stack):
self._cycle.append(dependency_key)
return True
elif recursion_stack[dependency_key]:
self._cycle.append(dependency_key)
return True
recursion_stack[key] = False
return False
def get_cycle(self):
return self._cycle
| none | 1 | 2.700523 | 3 | |
core-python/Core_Python/stackoverflow/UniqueRandomNameList.py | theumang100/tutorials-1 | 9 | 6622259 | <filename>core-python/Core_Python/stackoverflow/UniqueRandomNameList.py
import random
print("Random Name Picker")
input_string = input("Input names: ")
if input_string == "exit":
exit()
name_list = input_string.split()
print("Our contestants for this round are:", name_list)
s = int(input("Enter a Positive Sample Size : "))
print("Our winners are:", random.sample(name_list,k=s) if s <= len(name_list) else "Sample larger than population or is negative") | <filename>core-python/Core_Python/stackoverflow/UniqueRandomNameList.py
import random
print("Random Name Picker")
input_string = input("Input names: ")
if input_string == "exit":
exit()
name_list = input_string.split()
print("Our contestants for this round are:", name_list)
s = int(input("Enter a Positive Sample Size : "))
print("Our winners are:", random.sample(name_list,k=s) if s <= len(name_list) else "Sample larger than population or is negative") | none | 1 | 3.600216 | 4 | |
app.py | dreamInCoDeforlife/AWSHackathon | 2 | 6622260 | <gh_stars>1-10
import hashlib
import json
from time import time
from urllib.parse import urlparse
from uuid import uuid4
from flask_cors import CORS
import requests
from flask import Flask, jsonify, request
import boto3
import ast
import decimal
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
from sentiment_analyzer import compare_price
app = Flask(__name__)
CORS(app)
s3 = boto3.resource('s3')
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.Table('products')
sage_client = boto3.client('sagemaker-runtime', region_name='us-east-1')
@app.route('/')
def index():
return '''<form method=POST enctype=multipart/form-data action="upload">
<input type=file name=myfile>
<input type=submit>
</form>
'''
@app.route('/create_new_product', methods=["POST"])
def create_new_product():
new_uuid = str(uuid4())
# s3.Bucket('thirdparty-image-bucket').put_object(new_uuid+"/")
table.put_item(Item={
'product_description': "Add Product Description",
'username': 'admin',
'product_id': new_uuid,
'product_name': "Add Product Name",
'product_price': 0,
'is_used_product': True,
'barcode': -00000000,
'stat': "In progress",
'images': []
})
return jsonify({"product_id": new_uuid}), new_uuid
@app.route('/update/<id_>', methods=['POST'])
def update_product(id_):
product_id = id_
val = request.get_data()
dict_str = val.decode("UTF-8")
values = json.loads(dict_str)
# values = ast.literal_eval(dict_str)
required = ['product_name', 'product_price', 'is_used_product',
'barcode', 'product_description', 'stat']
if not all(k in values for k in required):
return 'Missing values', 400
try:
retrieve = table.update_item(
Key={'username': 'admin', 'product_id': product_id},
UpdateExpression="set product_name = :r, product_price=:p, is_used_product=:a, barcode=:l, product_description=:t, stat=:stat",
ExpressionAttributeValues={
':r': values['product_name'],
':p': decimal.Decimal(str(values['product_price'])),
':a': values["is_used_product"],
':l': values["barcode"],
":t": values["product_description"],
":stat": values["stat"]
},
ReturnValues="UPDATED_NEW"
)
return "Done", 200
except ClientError as e:
print(e.response['Error']['Message'])
return "Server error", 500
def removeEmptyString(dic):
if isinstance(dic, str):
if dic == "":
return None
else:
return dic
for e in dic:
if isinstance(dic[e], dict):
dic[e] = removeEmptyString(dic[e])
if (isinstance(dic[e], str) and dic[e] == ""):
dic[e] = None
if isinstance(dic[e], list):
for entry in dic[e]:
removeEmptyString(entry)
return dic
def update_from_barcode(dict_values, id_):
dict_values = removeEmptyString(dict_values)
product_id = id_
update_expression = 'SET {}'.format(
','.join(f'#{k}=:{k}' for k in dict_values))
expression_attribute_values = {f':{k}': v for k, v in dict_values.items()}
expression_attribute_names = {f'#{k}': k for k in dict_values}
response = table.update_item(
Key={'username': 'admin', 'product_id': product_id},
UpdateExpression=update_expression,
ExpressionAttributeValues=expression_attribute_values,
ExpressionAttributeNames=expression_attribute_names,
ReturnValues='UPDATED_NEW',
)
# todo
@app.route('/delete/<id_>', methods=["POST"])
def delete_item(id_):
image_list = request.get_data()
dict_str = image_list.decode("UTF-8")
values = ast.literal_eval(dict_str)
required = ['image_list']
if not all(k in values for k in required):
return 'Missing values', 400
for url in values["image_list"]:
key = url.split("https://thirdparty-image-bucket.s3.amazonaws.com/")[1]
# s3.Bucket('thirdparty-image-bucket').delete_key(key)
s3.Object('thirdparty-image-bucket', key).delete()
return "Done", 200
@app.route("/scan_barcode", methods=["POST"])
def scan_barcode():
val = []
send_, id_ = create_new_product()
# id_ = uuid4()
for filename, file in request.files.items():
# print(file.filename)
response = sage_client.invoke_endpoint(
EndpointName='barcode-reader-rat',
Body=file,
ContentType='image/jpeg',
Accept='application/json'
)
# print(response["Body"].read().decode("utf-8"))
val = response["Body"].read().decode("utf-8")
val = ast.literal_eval(val)
if len(list(val.keys())) == 1:
barcode = list(val.keys())[0]
value = {}
val = requests.get(
"https://api.barcodelookup.com/v2/products?barcode=" + barcode + "&formatted=y&key=<KEY>")
dict_str = val.content.decode("UTF-8")
if dict_str != "\n":
values = ast.literal_eval(dict_str)
json_body = values["products"][0]
value = {}
if "barcode_number" in json_body:
value["barcode"] = int(json_body["barcode_number"])
if "product_name" in json_body:
value["product_name"] = json_body["product_name"]
if "description" in json_body:
value['product_description'] = json_body['description']
if len(json_body["stores"]) > 1:
expensive = json_body["stores"][-1]["store_price"]
cheap = json_body["stores"][0]["store_price"]
value["expensive_version"] = expensive
value["cheap_version"] = cheap
elif len(json_body["stores"]) == 1:
value["version_in_market"] = json_body["stores"][0][
"store_price"]
value["parse_product"] = json_body
# print(value)
update_from_barcode(value, id_)
# return send_, 200
price = 0
if "cheap_version" in value:
price = value["cheap_version"]
elif "expensive_version" in value:
price = value["expensive_version"]
elif "version_in_market" in value:
price = value["version_in_market"]
return jsonify({"product_id": id_, "barcode": value["barcode"], "price": price, "product_name": value["parse_product"]["product_name"]}), 200
else:
return "Error Reading Barcode Please try again at another time", 400
else:
return "Unacceptable Input", 400
@app.route('/retrieve/<id_>', methods=["POST"])
def retrieve(id_):
folder_id = id_
my_bucket = s3.Bucket('thirdparty-image-bucket')
image_list = []
dynamodb_items = []
for object_summary in my_bucket.objects.filter(
Prefix=folder_id + "/"):
val = "https://thirdparty-image-bucket.s3.amazonaws.com/" + object_summary.key
image_list.append(val)
try:
response = table.get_item(
Key={'username': 'admin', 'product_id': folder_id},
)
dynamodb_items = response
# print(dynamodb_items)
except ClientError as e:
print(e.response['Error']['Message'])
return "Error Occured", 400
return jsonify({'image_list': image_list, "item_info": dynamodb_items}), 200
def retrieve_regular(id_):
folder_id = id_
my_bucket = s3.Bucket('thirdparty-image-bucket')
image_list = []
dynamodb_items = []
for object_summary in my_bucket.objects.filter(
Prefix=folder_id + "/"):
val = "https://thirdparty-image-bucket.s3.amazonaws.com/" + object_summary.key
image_list.append(val)
try:
response = table.get_item(
Key={'username': 'admin', 'product_id': folder_id},
)
dynamodb_items = response
# print(dynamodb_items)
except ClientError as e:
print(e.response['Error']['Message'])
return "Error Occured", 400
return {'image_list': image_list, "item_info": dynamodb_items}
@app.route('/send_for_review/<id_>', methods=['POST'])
def send_for_review(id_):
json_format = retrieve_regular(id_)["item_info"]["Item"]
val = ""
if "version_in_market" in json_format:
actual_price = json_format["version_in_market"]
third_party_price = json_format["product_price"]
val = compare_price(decimal.Decimal(actual_price),
third_party_price, json_format)
elif "expensive_version" in json_format:
actual_price = json_format["expensive_version"]
third_party_price = json_format["product_price"]
val = compare_price(decimal.Decimal(actual_price),
decimal.Decimal(third_party_price), json_format)
return jsonify(val), 200
@app.route('/upload/<id_>', methods=['POST'])
def upload(id_):
for filename, file in request.files.items():
filePath = id_ + "/" + file.filename
fileURL = 'https://thirdparty-image-bucket.s3.amazonaws.com/' + filePath
contentType = file.content_type
s3.Bucket('thirdparty-image-bucket').put_object(Key=filePath,
Body=file,
ContentType=contentType)
s3Client = boto3.client("s3", region_name="us-east-1")
object_acl = s3.ObjectAcl(
"thirdparty-image-bucket", id_+"/"+file.filename)
response = object_acl.put(ACL='public-read')
try:
retrieve = table.update_item(
Key={'username': 'admin', 'product_id': id_},
UpdateExpression="set images = list_append(images, :i)",
ExpressionAttributeValues={
':i': [fileURL],
},
ReturnValues="UPDATED_NEW"
)
return "Done", 200
except ClientError as e:
print(e.response['Error']['Message'])
return "Server error", 500
return jsonify({'url': fileURL}), 200
@app.route('/get_item_list', methods=['POST'])
def return_index():
try:
response = table.query(
KeyConditionExpression=Key('username').eq('admin')
)
# print(response)
response = response["Items"]
array = []
for i in response:
# print(response)
val = {}
val["product_id"] = i["product_id"]
val["status"] = i["stat"]
val["product_name"] = i['product_name']
val["images"] = i["images"]
array.append(val)
# print(array)
# print(response)
return jsonify({"list_items": array}), 200
except ClientError as e:
print(e.response['Error']['Message'])
return "Error Occured", 400
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-p', '--port', default=5000, type=int,
help='port to listen on')
args = parser.parse_args()
port = args.port
app.run(host='0.0.0.0', port=port)
| import hashlib
import json
from time import time
from urllib.parse import urlparse
from uuid import uuid4
from flask_cors import CORS
import requests
from flask import Flask, jsonify, request
import boto3
import ast
import decimal
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
from sentiment_analyzer import compare_price
app = Flask(__name__)
CORS(app)
s3 = boto3.resource('s3')
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.Table('products')
sage_client = boto3.client('sagemaker-runtime', region_name='us-east-1')
@app.route('/')
def index():
return '''<form method=POST enctype=multipart/form-data action="upload">
<input type=file name=myfile>
<input type=submit>
</form>
'''
@app.route('/create_new_product', methods=["POST"])
def create_new_product():
new_uuid = str(uuid4())
# s3.Bucket('thirdparty-image-bucket').put_object(new_uuid+"/")
table.put_item(Item={
'product_description': "Add Product Description",
'username': 'admin',
'product_id': new_uuid,
'product_name': "Add Product Name",
'product_price': 0,
'is_used_product': True,
'barcode': -00000000,
'stat': "In progress",
'images': []
})
return jsonify({"product_id": new_uuid}), new_uuid
@app.route('/update/<id_>', methods=['POST'])
def update_product(id_):
product_id = id_
val = request.get_data()
dict_str = val.decode("UTF-8")
values = json.loads(dict_str)
# values = ast.literal_eval(dict_str)
required = ['product_name', 'product_price', 'is_used_product',
'barcode', 'product_description', 'stat']
if not all(k in values for k in required):
return 'Missing values', 400
try:
retrieve = table.update_item(
Key={'username': 'admin', 'product_id': product_id},
UpdateExpression="set product_name = :r, product_price=:p, is_used_product=:a, barcode=:l, product_description=:t, stat=:stat",
ExpressionAttributeValues={
':r': values['product_name'],
':p': decimal.Decimal(str(values['product_price'])),
':a': values["is_used_product"],
':l': values["barcode"],
":t": values["product_description"],
":stat": values["stat"]
},
ReturnValues="UPDATED_NEW"
)
return "Done", 200
except ClientError as e:
print(e.response['Error']['Message'])
return "Server error", 500
def removeEmptyString(dic):
if isinstance(dic, str):
if dic == "":
return None
else:
return dic
for e in dic:
if isinstance(dic[e], dict):
dic[e] = removeEmptyString(dic[e])
if (isinstance(dic[e], str) and dic[e] == ""):
dic[e] = None
if isinstance(dic[e], list):
for entry in dic[e]:
removeEmptyString(entry)
return dic
def update_from_barcode(dict_values, id_):
dict_values = removeEmptyString(dict_values)
product_id = id_
update_expression = 'SET {}'.format(
','.join(f'#{k}=:{k}' for k in dict_values))
expression_attribute_values = {f':{k}': v for k, v in dict_values.items()}
expression_attribute_names = {f'#{k}': k for k in dict_values}
response = table.update_item(
Key={'username': 'admin', 'product_id': product_id},
UpdateExpression=update_expression,
ExpressionAttributeValues=expression_attribute_values,
ExpressionAttributeNames=expression_attribute_names,
ReturnValues='UPDATED_NEW',
)
# todo
@app.route('/delete/<id_>', methods=["POST"])
def delete_item(id_):
image_list = request.get_data()
dict_str = image_list.decode("UTF-8")
values = ast.literal_eval(dict_str)
required = ['image_list']
if not all(k in values for k in required):
return 'Missing values', 400
for url in values["image_list"]:
key = url.split("https://thirdparty-image-bucket.s3.amazonaws.com/")[1]
# s3.Bucket('thirdparty-image-bucket').delete_key(key)
s3.Object('thirdparty-image-bucket', key).delete()
return "Done", 200
@app.route("/scan_barcode", methods=["POST"])
def scan_barcode():
val = []
send_, id_ = create_new_product()
# id_ = uuid4()
for filename, file in request.files.items():
# print(file.filename)
response = sage_client.invoke_endpoint(
EndpointName='barcode-reader-rat',
Body=file,
ContentType='image/jpeg',
Accept='application/json'
)
# print(response["Body"].read().decode("utf-8"))
val = response["Body"].read().decode("utf-8")
val = ast.literal_eval(val)
if len(list(val.keys())) == 1:
barcode = list(val.keys())[0]
value = {}
val = requests.get(
"https://api.barcodelookup.com/v2/products?barcode=" + barcode + "&formatted=y&key=<KEY>")
dict_str = val.content.decode("UTF-8")
if dict_str != "\n":
values = ast.literal_eval(dict_str)
json_body = values["products"][0]
value = {}
if "barcode_number" in json_body:
value["barcode"] = int(json_body["barcode_number"])
if "product_name" in json_body:
value["product_name"] = json_body["product_name"]
if "description" in json_body:
value['product_description'] = json_body['description']
if len(json_body["stores"]) > 1:
expensive = json_body["stores"][-1]["store_price"]
cheap = json_body["stores"][0]["store_price"]
value["expensive_version"] = expensive
value["cheap_version"] = cheap
elif len(json_body["stores"]) == 1:
value["version_in_market"] = json_body["stores"][0][
"store_price"]
value["parse_product"] = json_body
# print(value)
update_from_barcode(value, id_)
# return send_, 200
price = 0
if "cheap_version" in value:
price = value["cheap_version"]
elif "expensive_version" in value:
price = value["expensive_version"]
elif "version_in_market" in value:
price = value["version_in_market"]
return jsonify({"product_id": id_, "barcode": value["barcode"], "price": price, "product_name": value["parse_product"]["product_name"]}), 200
else:
return "Error Reading Barcode Please try again at another time", 400
else:
return "Unacceptable Input", 400
@app.route('/retrieve/<id_>', methods=["POST"])
def retrieve(id_):
folder_id = id_
my_bucket = s3.Bucket('thirdparty-image-bucket')
image_list = []
dynamodb_items = []
for object_summary in my_bucket.objects.filter(
Prefix=folder_id + "/"):
val = "https://thirdparty-image-bucket.s3.amazonaws.com/" + object_summary.key
image_list.append(val)
try:
response = table.get_item(
Key={'username': 'admin', 'product_id': folder_id},
)
dynamodb_items = response
# print(dynamodb_items)
except ClientError as e:
print(e.response['Error']['Message'])
return "Error Occured", 400
return jsonify({'image_list': image_list, "item_info": dynamodb_items}), 200
def retrieve_regular(id_):
folder_id = id_
my_bucket = s3.Bucket('thirdparty-image-bucket')
image_list = []
dynamodb_items = []
for object_summary in my_bucket.objects.filter(
Prefix=folder_id + "/"):
val = "https://thirdparty-image-bucket.s3.amazonaws.com/" + object_summary.key
image_list.append(val)
try:
response = table.get_item(
Key={'username': 'admin', 'product_id': folder_id},
)
dynamodb_items = response
# print(dynamodb_items)
except ClientError as e:
print(e.response['Error']['Message'])
return "Error Occured", 400
return {'image_list': image_list, "item_info": dynamodb_items}
@app.route('/send_for_review/<id_>', methods=['POST'])
def send_for_review(id_):
json_format = retrieve_regular(id_)["item_info"]["Item"]
val = ""
if "version_in_market" in json_format:
actual_price = json_format["version_in_market"]
third_party_price = json_format["product_price"]
val = compare_price(decimal.Decimal(actual_price),
third_party_price, json_format)
elif "expensive_version" in json_format:
actual_price = json_format["expensive_version"]
third_party_price = json_format["product_price"]
val = compare_price(decimal.Decimal(actual_price),
decimal.Decimal(third_party_price), json_format)
return jsonify(val), 200
@app.route('/upload/<id_>', methods=['POST'])
def upload(id_):
for filename, file in request.files.items():
filePath = id_ + "/" + file.filename
fileURL = 'https://thirdparty-image-bucket.s3.amazonaws.com/' + filePath
contentType = file.content_type
s3.Bucket('thirdparty-image-bucket').put_object(Key=filePath,
Body=file,
ContentType=contentType)
s3Client = boto3.client("s3", region_name="us-east-1")
object_acl = s3.ObjectAcl(
"thirdparty-image-bucket", id_+"/"+file.filename)
response = object_acl.put(ACL='public-read')
try:
retrieve = table.update_item(
Key={'username': 'admin', 'product_id': id_},
UpdateExpression="set images = list_append(images, :i)",
ExpressionAttributeValues={
':i': [fileURL],
},
ReturnValues="UPDATED_NEW"
)
return "Done", 200
except ClientError as e:
print(e.response['Error']['Message'])
return "Server error", 500
return jsonify({'url': fileURL}), 200
@app.route('/get_item_list', methods=['POST'])
def return_index():
try:
response = table.query(
KeyConditionExpression=Key('username').eq('admin')
)
# print(response)
response = response["Items"]
array = []
for i in response:
# print(response)
val = {}
val["product_id"] = i["product_id"]
val["status"] = i["stat"]
val["product_name"] = i['product_name']
val["images"] = i["images"]
array.append(val)
# print(array)
# print(response)
return jsonify({"list_items": array}), 200
except ClientError as e:
print(e.response['Error']['Message'])
return "Error Occured", 400
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-p', '--port', default=5000, type=int,
help='port to listen on')
args = parser.parse_args()
port = args.port
app.run(host='0.0.0.0', port=port) | en | 0.354635 | <form method=POST enctype=multipart/form-data action="upload"> <input type=file name=myfile> <input type=submit> </form> # s3.Bucket('thirdparty-image-bucket').put_object(new_uuid+"/") # values = ast.literal_eval(dict_str) # todo # s3.Bucket('thirdparty-image-bucket').delete_key(key) # id_ = uuid4() # print(file.filename) # print(response["Body"].read().decode("utf-8")) # print(value) # return send_, 200 # print(dynamodb_items) # print(dynamodb_items) # print(response) # print(response) # print(array) # print(response) | 1.726069 | 2 |
examples/get_suggestions.py | pranavgupta1234/ptrie | 0 | 6622261 | <reponame>pranavgupta1234/ptrie
import os, sys
sys.path.insert(0, os.path.join(os.getcwd(), "../pythontrie/"))
from pythontrie import trie
if __name__ == '__main__':
sample_trie = trie()
sample_strings = ['heyy', 'heyay', 'heyey', 'hyyy', 'yoyo', 'heeyy', 'hoeyy']
for sample_string in sample_strings:
sample_trie.insert(sample_string)
print(sample_trie.suggestions(prefix='he'))
print(sample_trie.size())
| import os, sys
sys.path.insert(0, os.path.join(os.getcwd(), "../pythontrie/"))
from pythontrie import trie
if __name__ == '__main__':
sample_trie = trie()
sample_strings = ['heyy', 'heyay', 'heyey', 'hyyy', 'yoyo', 'heeyy', 'hoeyy']
for sample_string in sample_strings:
sample_trie.insert(sample_string)
print(sample_trie.suggestions(prefix='he'))
print(sample_trie.size()) | none | 1 | 2.54036 | 3 | |
deltalanguage/test/test_real_node.py | riverlane/deltalanguage | 16 | 6622262 | <gh_stars>10-100
from collections import OrderedDict
import unittest
import numpy as np
from deltalanguage.wiring import RealNode, PyConstBody, DeltaGraph, InPort
class RealNodeEq(unittest.TestCase):
"""Tests for the definition of equality over real nodes.
"""
def test_eq(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 2, value=2)
n1 = RealNode(g1, [b1], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertEqual(n1, n1)
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertEqual(n1, n2)
def test_eq_multi_body(self):
g1 = DeltaGraph()
b1_a = PyConstBody(lambda: 2, value=2)
b1_b = PyConstBody(lambda: 3, value=3)
n1 = RealNode(g1, [b1_a, b1_b], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2_a = PyConstBody(lambda: 2, value=2)
b2_b = PyConstBody(lambda: 3, value=3)
n2 = RealNode(g2, [b2_a, b2_b], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertEqual(n1, n2)
def test_neq_body_diff(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 1, value=1)
n1 = RealNode(g1, [b1], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertNotEqual(n1, n2)
def test_neq_body_order(self):
g1 = DeltaGraph()
b1_a = PyConstBody(lambda: 2, value=2)
b1_b = PyConstBody(lambda: 3, value=3)
n1 = RealNode(g1, [b1_a, b1_b], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2_a = PyConstBody(lambda: 2, value=2)
b2_b = PyConstBody(lambda: 3, value=3)
n2 = RealNode(g2, [b2_b, b2_a], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertNotEqual(n1, n2)
def test_neq_name_diff(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 2, value=2)
n1 = RealNode(g1, [b1], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node_a')
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node_b')
self.assertNotEqual(n1, n2)
def test_neq_inputs_diff(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 2, value=2)
n1 = RealNode(g1, [b1], OrderedDict([('in_a', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in_b', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertNotEqual(n1, n2)
def test_neq_outputs_diff(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 2, value=2)
n1 = RealNode(g1, [b1], OrderedDict([('in_a', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in_b', int)]),
OrderedDict([('out', bool), ('out_2', bool)]),
name='test_node')
self.assertNotEqual(n1, n2)
class RealNodeAddOutPort(unittest.TestCase):
"""Test the behaviour of adding out ports to a real node.
"""
def test_add_out_port_order(self):
"""Ensure that no matter what order out ports are added, they end up
in the order specified in outputs.
This property needs to hold even when not all ports are added.
"""
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict(),
OrderedDict([('a', int), ('b', int),
('c', int), ('d', int)]),
name='test_node_out')
n2 = RealNode(g1, [],
OrderedDict([('a', int), ('b', int),
('c', int), ('d', int)]),
OrderedDict(),
name='test_node_in')
in_p_a = InPort('a', int, n2, 0)
in_p_b = InPort('b', int, n2, 0)
in_p_c = InPort('c', int, n2, 0)
in_p_d = InPort('d', int, n2, 0)
in_ports = [in_p_a, in_p_b, in_p_c, in_p_d]
# Add all ports in random order
for i in np.random.permutation(len(in_ports)):
n1.add_out_port(in_ports[i], in_ports[i].index)
# Check order is still correct
p_order = []
for out_port in n1.out_ports:
out_port_index = list(n1.outputs).index(out_port.index)
p_order.append(out_port_index)
self.assertTrue(all(p_order[i] <= p_order[i+1]
for i in range(len(p_order)-1)))
if __name__ == "__main__":
unittest.main()
| from collections import OrderedDict
import unittest
import numpy as np
from deltalanguage.wiring import RealNode, PyConstBody, DeltaGraph, InPort
class RealNodeEq(unittest.TestCase):
"""Tests for the definition of equality over real nodes.
"""
def test_eq(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 2, value=2)
n1 = RealNode(g1, [b1], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertEqual(n1, n1)
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertEqual(n1, n2)
def test_eq_multi_body(self):
g1 = DeltaGraph()
b1_a = PyConstBody(lambda: 2, value=2)
b1_b = PyConstBody(lambda: 3, value=3)
n1 = RealNode(g1, [b1_a, b1_b], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2_a = PyConstBody(lambda: 2, value=2)
b2_b = PyConstBody(lambda: 3, value=3)
n2 = RealNode(g2, [b2_a, b2_b], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertEqual(n1, n2)
def test_neq_body_diff(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 1, value=1)
n1 = RealNode(g1, [b1], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertNotEqual(n1, n2)
def test_neq_body_order(self):
g1 = DeltaGraph()
b1_a = PyConstBody(lambda: 2, value=2)
b1_b = PyConstBody(lambda: 3, value=3)
n1 = RealNode(g1, [b1_a, b1_b], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2_a = PyConstBody(lambda: 2, value=2)
b2_b = PyConstBody(lambda: 3, value=3)
n2 = RealNode(g2, [b2_b, b2_a], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertNotEqual(n1, n2)
def test_neq_name_diff(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 2, value=2)
n1 = RealNode(g1, [b1], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node_a')
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in', int)]),
OrderedDict([('out', bool)]),
name='test_node_b')
self.assertNotEqual(n1, n2)
def test_neq_inputs_diff(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 2, value=2)
n1 = RealNode(g1, [b1], OrderedDict([('in_a', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in_b', int)]),
OrderedDict([('out', bool)]),
name='test_node')
self.assertNotEqual(n1, n2)
def test_neq_outputs_diff(self):
g1 = DeltaGraph()
b1 = PyConstBody(lambda: 2, value=2)
n1 = RealNode(g1, [b1], OrderedDict([('in_a', int)]),
OrderedDict([('out', bool)]),
name='test_node')
g2 = DeltaGraph()
b2 = PyConstBody(lambda: 2, value=2)
n2 = RealNode(g2, [b2], OrderedDict([('in_b', int)]),
OrderedDict([('out', bool), ('out_2', bool)]),
name='test_node')
self.assertNotEqual(n1, n2)
class RealNodeAddOutPort(unittest.TestCase):
"""Test the behaviour of adding out ports to a real node.
"""
def test_add_out_port_order(self):
"""Ensure that no matter what order out ports are added, they end up
in the order specified in outputs.
This property needs to hold even when not all ports are added.
"""
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict(),
OrderedDict([('a', int), ('b', int),
('c', int), ('d', int)]),
name='test_node_out')
n2 = RealNode(g1, [],
OrderedDict([('a', int), ('b', int),
('c', int), ('d', int)]),
OrderedDict(),
name='test_node_in')
in_p_a = InPort('a', int, n2, 0)
in_p_b = InPort('b', int, n2, 0)
in_p_c = InPort('c', int, n2, 0)
in_p_d = InPort('d', int, n2, 0)
in_ports = [in_p_a, in_p_b, in_p_c, in_p_d]
# Add all ports in random order
for i in np.random.permutation(len(in_ports)):
n1.add_out_port(in_ports[i], in_ports[i].index)
# Check order is still correct
p_order = []
for out_port in n1.out_ports:
out_port_index = list(n1.outputs).index(out_port.index)
p_order.append(out_port_index)
self.assertTrue(all(p_order[i] <= p_order[i+1]
for i in range(len(p_order)-1)))
if __name__ == "__main__":
unittest.main() | en | 0.902673 | Tests for the definition of equality over real nodes. Test the behaviour of adding out ports to a real node. Ensure that no matter what order out ports are added, they end up in the order specified in outputs. This property needs to hold even when not all ports are added. # Add all ports in random order # Check order is still correct | 2.886222 | 3 |
scripts/download_calipso_data.py | lucien-sim/cloudsat-viz | 1 | 6622263 | #!/usr/bin/python3
import os
def download_ftp_calipso(ftp_url, dest_path):
"""Downloads the specified files via FTP.
PARAMETERS:
-----------
ftp_url: FTP address for directory that contains all the
CALIPSO files
dest_path: Path to directory to which the CALIPSO files will be saved.
OUTPUTS:
--------
None
"""
wget_cmd = 'wget -nc -nd -P '+dest_path+' '+ftp_url
os.system(wget_cmd)
return None
if __name__ == '__main__':
message1 = """
Before the download begins, you must order the CALIPSO files from
the CALIPSO Search and Subsetting web application:
https://subset.larc.nasa.gov/calipso/login.php
Instructions:
1. Set up an account (provides username and password)
2. Navigate to the following webpage:
https://subset.larc.nasa.gov/calipso/login.php
3. Log in from that page, then use the web application to
download the data.
You'll need to complete two orders:
One for the level one products:
Atmospheric,
1064 nm calibration/backscatter
And one for the level two products:
Vertical Feature Mask: Layer Information
When the ordered data becomes available, you will receive an
email for each order and will be ready to proceed. When
When you receive the emails with the download
details...
"""
message2 = "Great! Now you're ready to download the CALIPSO data."
message3 = """
The emails should have included links to the FTP directories that are
holding the data you ordered.
Example: ftp://xfr139.larc.nasa.gov/sflops/Distribution/2019183112143_43051
"""
from global_variables import data_path
print(message1)
input1 = input("Enter any letter and hit 'ENTER': ")
print(message2)
print(message3)
ftp_url1 = input("Enter the first link here: ")+'/*'
ftp_url2 = input("Enter the second link here: ")+'/*'
dest_path = os.path.join(data_path, 'calipso')
print("""
Downloading CALIPSO data from the first FTP directory!
Data will be saved to the following local directory:
""")
print(dest_path)
download_ftp_calipso(ftp_url1, dest_path)
print("""
Downloading CALIPSO data from the second FTP directory!
Data will be saved to the following local directory:
""")
print(dest_path)
download_ftp_calipso(ftp_url2, dest_path)
| #!/usr/bin/python3
import os
def download_ftp_calipso(ftp_url, dest_path):
"""Downloads the specified files via FTP.
PARAMETERS:
-----------
ftp_url: FTP address for directory that contains all the
CALIPSO files
dest_path: Path to directory to which the CALIPSO files will be saved.
OUTPUTS:
--------
None
"""
wget_cmd = 'wget -nc -nd -P '+dest_path+' '+ftp_url
os.system(wget_cmd)
return None
if __name__ == '__main__':
message1 = """
Before the download begins, you must order the CALIPSO files from
the CALIPSO Search and Subsetting web application:
https://subset.larc.nasa.gov/calipso/login.php
Instructions:
1. Set up an account (provides username and password)
2. Navigate to the following webpage:
https://subset.larc.nasa.gov/calipso/login.php
3. Log in from that page, then use the web application to
download the data.
You'll need to complete two orders:
One for the level one products:
Atmospheric,
1064 nm calibration/backscatter
And one for the level two products:
Vertical Feature Mask: Layer Information
When the ordered data becomes available, you will receive an
email for each order and will be ready to proceed. When
When you receive the emails with the download
details...
"""
message2 = "Great! Now you're ready to download the CALIPSO data."
message3 = """
The emails should have included links to the FTP directories that are
holding the data you ordered.
Example: ftp://xfr139.larc.nasa.gov/sflops/Distribution/2019183112143_43051
"""
from global_variables import data_path
print(message1)
input1 = input("Enter any letter and hit 'ENTER': ")
print(message2)
print(message3)
ftp_url1 = input("Enter the first link here: ")+'/*'
ftp_url2 = input("Enter the second link here: ")+'/*'
dest_path = os.path.join(data_path, 'calipso')
print("""
Downloading CALIPSO data from the first FTP directory!
Data will be saved to the following local directory:
""")
print(dest_path)
download_ftp_calipso(ftp_url1, dest_path)
print("""
Downloading CALIPSO data from the second FTP directory!
Data will be saved to the following local directory:
""")
print(dest_path)
download_ftp_calipso(ftp_url2, dest_path)
| en | 0.799905 | #!/usr/bin/python3 Downloads the specified files via FTP. PARAMETERS: ----------- ftp_url: FTP address for directory that contains all the CALIPSO files dest_path: Path to directory to which the CALIPSO files will be saved. OUTPUTS: -------- None Before the download begins, you must order the CALIPSO files from the CALIPSO Search and Subsetting web application: https://subset.larc.nasa.gov/calipso/login.php Instructions: 1. Set up an account (provides username and password) 2. Navigate to the following webpage: https://subset.larc.nasa.gov/calipso/login.php 3. Log in from that page, then use the web application to download the data. You'll need to complete two orders: One for the level one products: Atmospheric, 1064 nm calibration/backscatter And one for the level two products: Vertical Feature Mask: Layer Information When the ordered data becomes available, you will receive an email for each order and will be ready to proceed. When When you receive the emails with the download details... The emails should have included links to the FTP directories that are holding the data you ordered. Example: ftp://xfr139.larc.nasa.gov/sflops/Distribution/2019183112143_43051 Downloading CALIPSO data from the first FTP directory! Data will be saved to the following local directory: Downloading CALIPSO data from the second FTP directory! Data will be saved to the following local directory: | 3.747019 | 4 |
solutions/Ugly Number/solution.py | nilax97/leetcode-solutions | 3 | 6622264 | <reponame>nilax97/leetcode-solutions
class Solution:
def isUgly(self, num: int) -> bool:
def ugly(num):
if num <=0:
return False
if abs(num)<2:
return True
if num == 2 or num == 3 or num == 5:
return True
if num % 2 == 0:
return ugly(num // 2)
if num % 3 == 0:
return ugly(num // 3)
if num % 5 == 0:
return ugly(num // 5)
return False
return ugly(num)
| class Solution:
def isUgly(self, num: int) -> bool:
def ugly(num):
if num <=0:
return False
if abs(num)<2:
return True
if num == 2 or num == 3 or num == 5:
return True
if num % 2 == 0:
return ugly(num // 2)
if num % 3 == 0:
return ugly(num // 3)
if num % 5 == 0:
return ugly(num // 5)
return False
return ugly(num) | none | 1 | 3.704461 | 4 | |
urlcf/service.py | alkorgun/urlcf | 1 | 6622265 | <gh_stars>1-10
"""
Created on Jul 5, 2017
@author: alkorgun
"""
import os
import sys
from .wsgi import app
class UrlcfService(object):
pid_file = "/var/run/urlcf-service.pid"
default_pipe = "/dev/null"
default_folder = "/tmp"
def daemonize(self): # by <NAME>
"""
UNIX double-fork magic.
"""
pid = os.fork()
if pid:
sys.exit(0)
os.setsid()
os.chdir(self.default_folder)
os.umask(0)
pid = os.fork()
if pid:
sys.exit(0)
sys.stdout.flush()
sys.stderr.flush()
si = open(self.default_pipe, "r")
so = open(self.default_pipe, "a+")
se = open(self.default_pipe, "a+", 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
with open(self.pid_file, "w") as fp:
fp.write(str(os.getpid()))
def start(self):
self.daemonize()
self.run()
def run(self):
app.run(
host="0.0.0.0",
port=80
)
| """
Created on Jul 5, 2017
@author: alkorgun
"""
import os
import sys
from .wsgi import app
class UrlcfService(object):
pid_file = "/var/run/urlcf-service.pid"
default_pipe = "/dev/null"
default_folder = "/tmp"
def daemonize(self): # by <NAME>
"""
UNIX double-fork magic.
"""
pid = os.fork()
if pid:
sys.exit(0)
os.setsid()
os.chdir(self.default_folder)
os.umask(0)
pid = os.fork()
if pid:
sys.exit(0)
sys.stdout.flush()
sys.stderr.flush()
si = open(self.default_pipe, "r")
so = open(self.default_pipe, "a+")
se = open(self.default_pipe, "a+", 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
with open(self.pid_file, "w") as fp:
fp.write(str(os.getpid()))
def start(self):
self.daemonize()
self.run()
def run(self):
app.run(
host="0.0.0.0",
port=80
) | en | 0.734263 | Created on Jul 5, 2017 @author: alkorgun # by <NAME> UNIX double-fork magic. | 2.312815 | 2 |
fimath/geodesic.py | kalinkinisaac/modular | 0 | 6622266 | <gh_stars>0
from .field import Field
from .re_field import ReField
from .bases import BaseGeodesic
class Geodesic(BaseGeodesic):
__slots__ = ('_begin', '_end', '_left', '_right', '_top', '_bot', '_is_vertical', '_vertical_x', '_has_inf',
'_center', '_sq_radius')
def __new__(cls, begin, end):
self = super(Geodesic, cls).__new__(cls)
self._begin = Field(begin)
self._end = Field(end)
self._is_vertical = False
self._has_inf = False
if self._begin == self._end:
raise ValueError('geodesic begin can not be equal to end')
if self._begin.is_inf:
self._is_vertical = True
self._has_inf = True
self._vertical_x = self._end.real
self._left = self._end
self._right = self._begin
self._top = self._begin
self._bot = self._end
elif self._end.is_inf:
self._is_vertical = True
self._has_inf = True
self._vertical_x = self._begin.real
self._left = self._begin
self._right = self._end
self._top = self._end
self._bot = self._begin
else:
if self._begin.real == self._end.real:
self._is_vertical = True
self._vertical_x = self._begin.real
if self._begin.real < self._end.real:
self._left = self._begin
self._right = self._end
else:
self._left = self._end
self._right = self._begin
if self._begin.imag < self._end.imag:
self._top = self._end
self._bot = self._begin
else:
self._top = self._begin
self._bot = self._end
if self._bot.imag < 0:
raise ValueError('geodesic should not have point below real axis')
if not self._is_vertical:
self._center = ReField(0.5) * (self._begin.sq_abs() - self._end.sq_abs()) / (self._begin - self._end).real
self._sq_radius = (self._begin - self._center).sq_abs()
return self
@property
def begin(self):
return self._begin
@property
def end(self):
return self._end
@property
def left(self):
return self._left
@property
def right(self):
return self._right
@property
def top(self):
return self._top
@property
def bot(self):
return self._bot
@property
def is_vertical(self):
return self._is_vertical
@property
def has_inf(self):
return self._has_inf
@property
def vertical_x(self):
if not self._is_vertical:
raise NotImplementedError('geodesic is not vertical')
return self._vertical_x
@property
def center(self):
if self._is_vertical:
raise NotImplementedError('geodesic is vertical')
return self._center
@property
def sq_radius(self):
if self._is_vertical:
raise NotImplementedError('geodesic is vertical')
return self._sq_radius
def __repr__(self):
return f'{self.__class__.__name__}(from: {self._begin} to: {self._end})'
def __str__(self):
return f'Geodesic from {self.begin} to {self.end}>'
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
if type(other) == Geodesic:
return self.begin == other.begin and self.end == other.end
else:
return NotImplemented
def __reversed__(self):
return Geodesic(self.end, self.begin)
def undirected_eq(lhs, rhs):
return lhs == rhs or lhs == reversed(rhs)
__all__ = ['Geodesic', 'undirected_eq']
| from .field import Field
from .re_field import ReField
from .bases import BaseGeodesic
class Geodesic(BaseGeodesic):
__slots__ = ('_begin', '_end', '_left', '_right', '_top', '_bot', '_is_vertical', '_vertical_x', '_has_inf',
'_center', '_sq_radius')
def __new__(cls, begin, end):
self = super(Geodesic, cls).__new__(cls)
self._begin = Field(begin)
self._end = Field(end)
self._is_vertical = False
self._has_inf = False
if self._begin == self._end:
raise ValueError('geodesic begin can not be equal to end')
if self._begin.is_inf:
self._is_vertical = True
self._has_inf = True
self._vertical_x = self._end.real
self._left = self._end
self._right = self._begin
self._top = self._begin
self._bot = self._end
elif self._end.is_inf:
self._is_vertical = True
self._has_inf = True
self._vertical_x = self._begin.real
self._left = self._begin
self._right = self._end
self._top = self._end
self._bot = self._begin
else:
if self._begin.real == self._end.real:
self._is_vertical = True
self._vertical_x = self._begin.real
if self._begin.real < self._end.real:
self._left = self._begin
self._right = self._end
else:
self._left = self._end
self._right = self._begin
if self._begin.imag < self._end.imag:
self._top = self._end
self._bot = self._begin
else:
self._top = self._begin
self._bot = self._end
if self._bot.imag < 0:
raise ValueError('geodesic should not have point below real axis')
if not self._is_vertical:
self._center = ReField(0.5) * (self._begin.sq_abs() - self._end.sq_abs()) / (self._begin - self._end).real
self._sq_radius = (self._begin - self._center).sq_abs()
return self
@property
def begin(self):
return self._begin
@property
def end(self):
return self._end
@property
def left(self):
return self._left
@property
def right(self):
return self._right
@property
def top(self):
return self._top
@property
def bot(self):
return self._bot
@property
def is_vertical(self):
return self._is_vertical
@property
def has_inf(self):
return self._has_inf
@property
def vertical_x(self):
if not self._is_vertical:
raise NotImplementedError('geodesic is not vertical')
return self._vertical_x
@property
def center(self):
if self._is_vertical:
raise NotImplementedError('geodesic is vertical')
return self._center
@property
def sq_radius(self):
if self._is_vertical:
raise NotImplementedError('geodesic is vertical')
return self._sq_radius
def __repr__(self):
return f'{self.__class__.__name__}(from: {self._begin} to: {self._end})'
def __str__(self):
return f'Geodesic from {self.begin} to {self.end}>'
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
if type(other) == Geodesic:
return self.begin == other.begin and self.end == other.end
else:
return NotImplemented
def __reversed__(self):
return Geodesic(self.end, self.begin)
def undirected_eq(lhs, rhs):
return lhs == rhs or lhs == reversed(rhs)
__all__ = ['Geodesic', 'undirected_eq'] | none | 1 | 2.440275 | 2 | |
downloader.py | Starlord713/pynstaScraper | 0 | 6622267 | from selenium.webdriver.common import by as find
from urllib.error import HTTPError
import time as t
import os
from urllib import request
import csv
class Link:
def __init__(self, src, status):
self.src = src
self.status = status
def downloader(cdriverf, finder, directory):
find_a_term = finder
cdriverf.find_element(find.By.XPATH, "//*[@id='react-root']/section/nav/div[2]/div/div/div[2]/input").send_keys(find_a_term)
cdriverf.find_element(find.By.XPATH, '//a[contains(@class, "yCE8d")]').click()
lastHigh = 0
newHigh = 0
image_loaded = 0
image_counter = 0
srcList = []
trigger = 0
index = 0
#load state if exists
if not os.path.exists(finder+"savedState.csv"):
open(finder+"savedState.csv", "a+")
else:
srcList = loadState(finder)
print("loaded images")
for l in srcList:
print(l)
while checkbodyheight(lastHigh, newHigh) | image_loaded < 400:
newHigh = cdriverf.execute_script("return document.body.scrollHeight")
if image_loaded < 50:
cdriverf.execute_script("window.scrollTo(0, document.body.scrollHeight)")
t.sleep(3)
for i in cdriverf.find_elements_by_xpath('//img[contains(@class, "FFVAD")]'):
image_counter += 1
image_loaded = image_counter
print("image loaded number", image_loaded, "\n")
image_counter = 0
elif ((image_loaded == 50) & (trigger == 0)) | ((image_loaded == 51) & (trigger == 0)):
for i in cdriverf.find_elements_by_xpath('//img[contains(@class, "FFVAD")]'):
aux = i.get_attribute('src')
if any(link.src == aux for link in srcList):
print("src repeated, not loaded")
else:
auxLink = Link(aux, False)
srcList.append(auxLink)
image_loaded += 1
print("image loaded number ", image_loaded, "\n")
cdriverf.execute_script("window.scrollTo(0, document.body.scrollHeight)")
t.sleep(3)
trigger = 1
elif (image_loaded >= 50) & (trigger == 1):
cdriverf.execute_script("window.scrollTo(0, document.body.scrollHeight)")
t.sleep(3)
for i in cdriverf.find_elements_by_xpath('//img[contains(@class, "FFVAD")]'):
aux = i.get_attribute('src')
if any(link.src == aux for link in srcList):
print("src repeated, not loaded")
else:
auxLink = Link(aux, False)
srcList.append(auxLink)
image_loaded += 1
print("image loaded number ", image_loaded, "\n")
lastHigh = cdriverf.execute_script("return document.body.scrollHeight")
#save the state before download the images
for line in srcList:
print(line.src)
#downloading the images
for l in srcList:
try:
if(l.status == False):
jpgPath = os.path.join(directory, finder + str(index) + ".jpg")
request.urlretrieve(l.src, jpgPath)
l.status = True
index += 1
t.sleep(3)
print("download ok")
except TimeoutError:
print("timeout, cannot get the pic")
except HTTPError:
print("forbidden, cannot get the pic")
saveState(srcList, finder)
def checkbodyheight(lasth, newh):
if lasth == newh:
return False
else:
return True
def saveState(srclist, finder):
with open(finder+"savedState.csv", 'w') as csv_file:
file = csv.writer(csv_file, delimiter=",")
for link in srclist:
file.writerow([link.src, link.status])
def loadState(finder):
auxlist = []
with open(finder+"savedState.csv", 'r') as f:
readingCsv = csv.reader(f)
for link in readingCsv:
aux = Link(link[0], link[1])
auxlist.append(aux)
return auxlist
def createHashtagList(labList):
aux = []
index = 0
flag = True
while flag:
print("input Directory name")
aux.append(input())
print("input Hashtag name")
aux.append(input())
aux.append(index)
index += 1
labList.append(aux)
print("press 0 to scape")
keyEsc = input()
if keyEsc == '0':
flag = False
| from selenium.webdriver.common import by as find
from urllib.error import HTTPError
import time as t
import os
from urllib import request
import csv
class Link:
def __init__(self, src, status):
self.src = src
self.status = status
def downloader(cdriverf, finder, directory):
find_a_term = finder
cdriverf.find_element(find.By.XPATH, "//*[@id='react-root']/section/nav/div[2]/div/div/div[2]/input").send_keys(find_a_term)
cdriverf.find_element(find.By.XPATH, '//a[contains(@class, "yCE8d")]').click()
lastHigh = 0
newHigh = 0
image_loaded = 0
image_counter = 0
srcList = []
trigger = 0
index = 0
#load state if exists
if not os.path.exists(finder+"savedState.csv"):
open(finder+"savedState.csv", "a+")
else:
srcList = loadState(finder)
print("loaded images")
for l in srcList:
print(l)
while checkbodyheight(lastHigh, newHigh) | image_loaded < 400:
newHigh = cdriverf.execute_script("return document.body.scrollHeight")
if image_loaded < 50:
cdriverf.execute_script("window.scrollTo(0, document.body.scrollHeight)")
t.sleep(3)
for i in cdriverf.find_elements_by_xpath('//img[contains(@class, "FFVAD")]'):
image_counter += 1
image_loaded = image_counter
print("image loaded number", image_loaded, "\n")
image_counter = 0
elif ((image_loaded == 50) & (trigger == 0)) | ((image_loaded == 51) & (trigger == 0)):
for i in cdriverf.find_elements_by_xpath('//img[contains(@class, "FFVAD")]'):
aux = i.get_attribute('src')
if any(link.src == aux for link in srcList):
print("src repeated, not loaded")
else:
auxLink = Link(aux, False)
srcList.append(auxLink)
image_loaded += 1
print("image loaded number ", image_loaded, "\n")
cdriverf.execute_script("window.scrollTo(0, document.body.scrollHeight)")
t.sleep(3)
trigger = 1
elif (image_loaded >= 50) & (trigger == 1):
cdriverf.execute_script("window.scrollTo(0, document.body.scrollHeight)")
t.sleep(3)
for i in cdriverf.find_elements_by_xpath('//img[contains(@class, "FFVAD")]'):
aux = i.get_attribute('src')
if any(link.src == aux for link in srcList):
print("src repeated, not loaded")
else:
auxLink = Link(aux, False)
srcList.append(auxLink)
image_loaded += 1
print("image loaded number ", image_loaded, "\n")
lastHigh = cdriverf.execute_script("return document.body.scrollHeight")
#save the state before download the images
for line in srcList:
print(line.src)
#downloading the images
for l in srcList:
try:
if(l.status == False):
jpgPath = os.path.join(directory, finder + str(index) + ".jpg")
request.urlretrieve(l.src, jpgPath)
l.status = True
index += 1
t.sleep(3)
print("download ok")
except TimeoutError:
print("timeout, cannot get the pic")
except HTTPError:
print("forbidden, cannot get the pic")
saveState(srcList, finder)
def checkbodyheight(lasth, newh):
if lasth == newh:
return False
else:
return True
def saveState(srclist, finder):
with open(finder+"savedState.csv", 'w') as csv_file:
file = csv.writer(csv_file, delimiter=",")
for link in srclist:
file.writerow([link.src, link.status])
def loadState(finder):
auxlist = []
with open(finder+"savedState.csv", 'r') as f:
readingCsv = csv.reader(f)
for link in readingCsv:
aux = Link(link[0], link[1])
auxlist.append(aux)
return auxlist
def createHashtagList(labList):
aux = []
index = 0
flag = True
while flag:
print("input Directory name")
aux.append(input())
print("input Hashtag name")
aux.append(input())
aux.append(index)
index += 1
labList.append(aux)
print("press 0 to scape")
keyEsc = input()
if keyEsc == '0':
flag = False
| en | 0.546886 | #load state if exists #save the state before download the images #downloading the images | 3.039592 | 3 |
LLE_C.py | bobchengyang/SDP_RUN | 0 | 6622268 | <gh_stars>0
import torch
import torch.nn as nn
from torch.autograd import Variable
def LLE_C(feature,\
b_ind,\
lalel,\
n_feature,\
LLE_C_vec,\
n_train,\
metric_M_step,\
LLE_st,\
optimizer_LLE):
tril_idx=torch.tril_indices(n_train,n_train,-1)
LLE_C_matrix0=torch.zeros(n_train,n_train)
LLE_C_matrix0[tril_idx[0],tril_idx[1]]=LLE_C_vec
LLE_C_matrix=LLE_C_matrix0+LLE_C_matrix0.T
feature_train=feature[b_ind,:]
LLE_obj=torch.linalg.norm(feature_train-LLE_C_matrix@feature_train)**2
l1_before=torch.linalg.norm(LLE_C_matrix,ord=1)
LLE_obj.backward()
optimizer_LLE.step()
LLE_C_relu=nn.ReLU()
LLE_C_vec=LLE_C_relu(LLE_C_vec-LLE_st)
LLE_C_matrix0[tril_idx[0],tril_idx[1]]=LLE_C_vec
LLE_C_matrix_C=LLE_C_matrix0+LLE_C_matrix0.T
LLE_obj_C=torch.linalg.norm(feature_train-LLE_C_matrix_C@feature_train)**2
l1_after=torch.linalg.norm(LLE_C_matrix_C,ord=1)
tol_current=torch.norm(LLE_obj_C+l1_after-(LLE_obj+l1_before))
return Variable(LLE_C_vec.detach(), requires_grad=True),tol_current | import torch
import torch.nn as nn
from torch.autograd import Variable
def LLE_C(feature,\
b_ind,\
lalel,\
n_feature,\
LLE_C_vec,\
n_train,\
metric_M_step,\
LLE_st,\
optimizer_LLE):
tril_idx=torch.tril_indices(n_train,n_train,-1)
LLE_C_matrix0=torch.zeros(n_train,n_train)
LLE_C_matrix0[tril_idx[0],tril_idx[1]]=LLE_C_vec
LLE_C_matrix=LLE_C_matrix0+LLE_C_matrix0.T
feature_train=feature[b_ind,:]
LLE_obj=torch.linalg.norm(feature_train-LLE_C_matrix@feature_train)**2
l1_before=torch.linalg.norm(LLE_C_matrix,ord=1)
LLE_obj.backward()
optimizer_LLE.step()
LLE_C_relu=nn.ReLU()
LLE_C_vec=LLE_C_relu(LLE_C_vec-LLE_st)
LLE_C_matrix0[tril_idx[0],tril_idx[1]]=LLE_C_vec
LLE_C_matrix_C=LLE_C_matrix0+LLE_C_matrix0.T
LLE_obj_C=torch.linalg.norm(feature_train-LLE_C_matrix_C@feature_train)**2
l1_after=torch.linalg.norm(LLE_C_matrix_C,ord=1)
tol_current=torch.norm(LLE_obj_C+l1_after-(LLE_obj+l1_before))
return Variable(LLE_C_vec.detach(), requires_grad=True),tol_current | none | 1 | 2.335695 | 2 | |
scr/iou.py | DeepsMoseli/DetectronCheck | 0 | 6622269 | <gh_stars>0
import numpy as np
class intersection_over_Union:
def get_area(self,sq):
length = (sq[1]-sq[0])
width = (sq[3]-sq[2])
area = length*width
return area
def intersaction(self,sq1,sq2):
xs = []
ys = []
inter = []
if sq1[1]>=sq2[0] or sq1[0]>=sq2[1] or sq1[3]>=sq2[2] or sq1[2]>=sq2[3]:
for k in range(2):
xs.append(sq1[k])
xs.append(sq2[k])
ys.append(sq1[2+k])
ys.append(sq2[2+k])
xs = np.sort(xs)
ys = np.sort(ys)
inter.append(xs[1])
inter.append(xs[2])
inter.append(ys[1])
inter.append(ys[2])
else:
inter = [0,0,0,0]
return self.get_area(inter)
def union(self,sq1,sq2):
a1 = self.get_area(sq1)
a2 = self.get_area(sq2)
inter = self.intersaction(sq1,sq2)
union_ = a1 + a2 - inter
#print("area1: ", a1)
#print("area2: ", a2)
#print("area inter: ", inter)
return union_
def IoU(self,sq1,sq2):
return (self.intersaction(sq1,sq2)/self.union(sq1,sq2)) | import numpy as np
class intersection_over_Union:
def get_area(self,sq):
length = (sq[1]-sq[0])
width = (sq[3]-sq[2])
area = length*width
return area
def intersaction(self,sq1,sq2):
xs = []
ys = []
inter = []
if sq1[1]>=sq2[0] or sq1[0]>=sq2[1] or sq1[3]>=sq2[2] or sq1[2]>=sq2[3]:
for k in range(2):
xs.append(sq1[k])
xs.append(sq2[k])
ys.append(sq1[2+k])
ys.append(sq2[2+k])
xs = np.sort(xs)
ys = np.sort(ys)
inter.append(xs[1])
inter.append(xs[2])
inter.append(ys[1])
inter.append(ys[2])
else:
inter = [0,0,0,0]
return self.get_area(inter)
def union(self,sq1,sq2):
a1 = self.get_area(sq1)
a2 = self.get_area(sq2)
inter = self.intersaction(sq1,sq2)
union_ = a1 + a2 - inter
#print("area1: ", a1)
#print("area2: ", a2)
#print("area inter: ", inter)
return union_
def IoU(self,sq1,sq2):
return (self.intersaction(sq1,sq2)/self.union(sq1,sq2)) | en | 0.16942 | #print("area1: ", a1) #print("area2: ", a2) #print("area inter: ", inter) | 3.481265 | 3 |
colassigner/__init__.py | endremborza/colassigner | 0 | 6622270 | # flake8: noqa
from ._version import __version__
from .core import ChildColAssigner, ColAccessor, ColAssigner
from .meta_base import get_all_cols, get_att_value
from .type_hinting import Col
from .util import camel_to_snake
| # flake8: noqa
from ._version import __version__
from .core import ChildColAssigner, ColAccessor, ColAssigner
from .meta_base import get_all_cols, get_att_value
from .type_hinting import Col
from .util import camel_to_snake
| it | 0.238973 | # flake8: noqa | 1.158649 | 1 |
dazeus/__init__.py | dazeus/dazeus-python | 1 | 6622271 | from .scope import Scope
from .dazeus import DaZeus
| from .scope import Scope
from .dazeus import DaZeus
| none | 1 | 1.050658 | 1 | |
main.py | ayushbasak/AmazonPriceTracker | 0 | 6622272 | <reponame>ayushbasak/AmazonPriceTracker<gh_stars>0
import PriceTracker as pt
import time
# Insert the Amazon Link and header (User-Agent) to Track
# For more info lookup the README
urls = []
with open("data.txt","r") as f:
for line in f.readlines():
urls.append(line.rstrip("\n"))
header = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0"}
my_email = ""
my_password = ""
recievers_email = ""
for url in urls:
price = float(url.split(" ")[1])
data = {"URL":url,\
"Header":header,\
"PriceThreshold":price,\
"Email":my_email,\
"Password":<PASSWORD>,\
"Reciever":recievers_email}
tracker = pt.tracker(data)
tracker.checkPrice() | import PriceTracker as pt
import time
# Insert the Amazon Link and header (User-Agent) to Track
# For more info lookup the README
urls = []
with open("data.txt","r") as f:
for line in f.readlines():
urls.append(line.rstrip("\n"))
header = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0"}
my_email = ""
my_password = ""
recievers_email = ""
for url in urls:
price = float(url.split(" ")[1])
data = {"URL":url,\
"Header":header,\
"PriceThreshold":price,\
"Email":my_email,\
"Password":<PASSWORD>,\
"Reciever":recievers_email}
tracker = pt.tracker(data)
tracker.checkPrice() | en | 0.745635 | # Insert the Amazon Link and header (User-Agent) to Track # For more info lookup the README | 2.79637 | 3 |
gpflow/utilities/bijectors.py | akhayes/GPflow | 0 | 6622273 | <reponame>akhayes/GPflow
from typing import Optional
import tensorflow_probability as tfp
from .. import config
from .utilities import to_default_float
__all__ = ["positive", "triangular"]
def positive(lower: Optional[float] = None):
lower_value = config.default_positive_minimum()
if lower_value is None:
return tfp.bijectors.Softplus()
shift = to_default_float(lower_value)
bijectors = [tfp.bijectors.AffineScalar(shift=shift), tfp.bijectors.Softplus()]
return tfp.bijectors.Chain(bijectors)
triangular = tfp.bijectors.FillTriangular
| from typing import Optional
import tensorflow_probability as tfp
from .. import config
from .utilities import to_default_float
__all__ = ["positive", "triangular"]
def positive(lower: Optional[float] = None):
lower_value = config.default_positive_minimum()
if lower_value is None:
return tfp.bijectors.Softplus()
shift = to_default_float(lower_value)
bijectors = [tfp.bijectors.AffineScalar(shift=shift), tfp.bijectors.Softplus()]
return tfp.bijectors.Chain(bijectors)
triangular = tfp.bijectors.FillTriangular | none | 1 | 2.405277 | 2 | |
tests/orthanc/test_orthanc_instance_post.py | gacou54/pyorthanc | 12 | 6622274 | # coding: utf-8
# author: <NAME>
import unittest
import requests
from pyorthanc import Orthanc
from tests import setup_server
class TestOrthancInstancePosts(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
global orthanc_subprocess
orthanc_subprocess = setup_server.setup_orthanc_server()
@classmethod
def tearDownClass(cls) -> None:
global orthanc_subprocess
setup_server.stop_orthanc_server_and_remove_data_directory(orthanc_subprocess)
del orthanc_subprocess
def setUp(self) -> None:
self.orthanc = Orthanc(setup_server.ORTHANC_URL)
def tearDown(self) -> None:
self.orthanc = None
setup_server.clear_data()
def given_data_in_orthanc_server(self):
setup_server.setup_data()
def test_givenRawDicomData_whenPostingInstances_thenInstancesIsStored(self):
with open('./tests/data/dicom_files/RTSTRUCT.dcm', 'rb') as fh:
data = fh.read()
self.orthanc.post_instances(data)
self.assertEqual(len(self.orthanc.get_instances()), 1)
def test_givenBadDicomData_whenPostingInstances_thenInstancesIsStored(self):
with open('./tests/__init__.py', 'rb') as fh:
data = fh.read()
self.assertRaises(
requests.HTTPError,
lambda: self.orthanc.post_instances(data)
)
| # coding: utf-8
# author: <NAME>
import unittest
import requests
from pyorthanc import Orthanc
from tests import setup_server
class TestOrthancInstancePosts(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
global orthanc_subprocess
orthanc_subprocess = setup_server.setup_orthanc_server()
@classmethod
def tearDownClass(cls) -> None:
global orthanc_subprocess
setup_server.stop_orthanc_server_and_remove_data_directory(orthanc_subprocess)
del orthanc_subprocess
def setUp(self) -> None:
self.orthanc = Orthanc(setup_server.ORTHANC_URL)
def tearDown(self) -> None:
self.orthanc = None
setup_server.clear_data()
def given_data_in_orthanc_server(self):
setup_server.setup_data()
def test_givenRawDicomData_whenPostingInstances_thenInstancesIsStored(self):
with open('./tests/data/dicom_files/RTSTRUCT.dcm', 'rb') as fh:
data = fh.read()
self.orthanc.post_instances(data)
self.assertEqual(len(self.orthanc.get_instances()), 1)
def test_givenBadDicomData_whenPostingInstances_thenInstancesIsStored(self):
with open('./tests/__init__.py', 'rb') as fh:
data = fh.read()
self.assertRaises(
requests.HTTPError,
lambda: self.orthanc.post_instances(data)
)
| en | 0.824763 | # coding: utf-8 # author: <NAME> | 2.473828 | 2 |
GenerativeModels/utils/test_utils.py | ariel415el/PerceptualLossGLO-Pytorch | 0 | 6622275 | import os
import numpy as np
import torch
from tqdm import tqdm
from GenerativeModels.utils.data_utils import get_dataloader
from GenerativeModels.utils.fid_scroe.fid_score import calculate_frechet_distance
from GenerativeModels.utils.fid_scroe.inception import InceptionV3
from losses.swd.patch_swd import compute_swd
def run_FID_tests(train_dir, generator, data_embeddings, train_dataset, test_dataset, samplers, device):
"""Compute The FID score of the train, GLO, IMLE and reconstructed images distribution compared
to the test distribution"""
batch_size = 128
test_dataloader = get_dataloader(test_dataset, batch_size, device, drop_last=False)
train_dataloader = get_dataloader(train_dataset, batch_size, device, drop_last=False)
inception_model = InceptionV3([3]).to(device).eval()
data_dict = {"test": [], "train": [], "reconstructions": []}
data_dict.update({sampler.name: [] for sampler in samplers})
# Computing Inception activations
with torch.no_grad():
pbar = tqdm(enumerate(test_dataloader))
for i, (indices, images) in pbar:
# get activations for real images from test set
act = inception_model.get_activations(images, device).astype(np.float64)
data_dict['test'].append(act)
# get activations for real images from train set
images = np.stack([train_dataloader.dataset[x][1] for x in indices])
images = torch.from_numpy(images)
act = inception_model.get_activations(images, device).astype(np.float64)
data_dict['train'].append(act)
# get activations for reconstructed images
images = generator(data_embeddings[indices.long()])
act = inception_model.get_activations(images, device).astype(np.float64)
data_dict['reconstructions'].append(act)
# get activations for generated images with various samplers
for sampler in samplers:
act = inception_model.get_activations(generator(sampler.sample(batch_size)), device).astype(np.float64)
data_dict[sampler.name].append(act)
pbar.set_description(f"Computing Inception activations: {i * test_dataloader.batch_size} done")
print(f"Computing activations mean and covariances")
for k in data_dict:
activations = np.concatenate(data_dict[k], axis=0)
mu, cov = np.mean(activations, axis=0), np.cov(activations, rowvar=False)
data_dict[k] = (mu, cov)
print("Computing FID scores")
f = open(os.path.join(train_dir, "FID-scores.txt"), 'w')
test_mu, test_cov = data_dict['test']
for k, (mu, cov) in data_dict.items():
if k != 'test':
fid_score = calculate_frechet_distance(test_mu, test_cov, mu, cov)
f.write(f"{k} vs test data FID: {fid_score:.2f}\n")
f.close()
def run_swd_tests(train_dir, generator, data_embeddings, train_dataset, test_dataset, samplers, device):
n_samples = len(test_dataset)
batch_size = 128
data_dict = {"test": torch.from_numpy([test_dataset[i][1] for i in range(len(test_dataset))]),
"train": torch.from_numpy([train_dataset[i][1] for i in range(len(test_dataset))])}
with torch.no_grad():
images = []
for i in range(n_samples // batch_size):
images.append(generator(data_embeddings[i*batch_size: (i+1)*batch_size]).cpu())
leftover = n_samples % batch_size
if leftover > 0:
images.append(generator(data_embeddings[-leftover:]).cpu())
data_dict['reconstructions'] = torch.cat(images)
for sampler in samplers:
images = []
for i in range(n_samples // batch_size):
images.append(generator(sampler.sample(batch_size)).cpu())
leftover = n_samples % batch_size
if leftover > 0:
images.append(generator(sampler.sample(leftover)).cpu())
data_dict[sampler.name] = torch.cat(images)
print("Computing SWD scores")
f = open(os.path.join(train_dir, "SWD-scores.txt"), 'w')
for k, data in data_dict.items():
if k != 'test':
swd_score = compute_swd(data_dict['test'].float(), data.float(), device='cuda')
f.write(f"{k} vs test data FID: {swd_score:.2f}\n")
f.close() | import os
import numpy as np
import torch
from tqdm import tqdm
from GenerativeModels.utils.data_utils import get_dataloader
from GenerativeModels.utils.fid_scroe.fid_score import calculate_frechet_distance
from GenerativeModels.utils.fid_scroe.inception import InceptionV3
from losses.swd.patch_swd import compute_swd
def run_FID_tests(train_dir, generator, data_embeddings, train_dataset, test_dataset, samplers, device):
"""Compute The FID score of the train, GLO, IMLE and reconstructed images distribution compared
to the test distribution"""
batch_size = 128
test_dataloader = get_dataloader(test_dataset, batch_size, device, drop_last=False)
train_dataloader = get_dataloader(train_dataset, batch_size, device, drop_last=False)
inception_model = InceptionV3([3]).to(device).eval()
data_dict = {"test": [], "train": [], "reconstructions": []}
data_dict.update({sampler.name: [] for sampler in samplers})
# Computing Inception activations
with torch.no_grad():
pbar = tqdm(enumerate(test_dataloader))
for i, (indices, images) in pbar:
# get activations for real images from test set
act = inception_model.get_activations(images, device).astype(np.float64)
data_dict['test'].append(act)
# get activations for real images from train set
images = np.stack([train_dataloader.dataset[x][1] for x in indices])
images = torch.from_numpy(images)
act = inception_model.get_activations(images, device).astype(np.float64)
data_dict['train'].append(act)
# get activations for reconstructed images
images = generator(data_embeddings[indices.long()])
act = inception_model.get_activations(images, device).astype(np.float64)
data_dict['reconstructions'].append(act)
# get activations for generated images with various samplers
for sampler in samplers:
act = inception_model.get_activations(generator(sampler.sample(batch_size)), device).astype(np.float64)
data_dict[sampler.name].append(act)
pbar.set_description(f"Computing Inception activations: {i * test_dataloader.batch_size} done")
print(f"Computing activations mean and covariances")
for k in data_dict:
activations = np.concatenate(data_dict[k], axis=0)
mu, cov = np.mean(activations, axis=0), np.cov(activations, rowvar=False)
data_dict[k] = (mu, cov)
print("Computing FID scores")
f = open(os.path.join(train_dir, "FID-scores.txt"), 'w')
test_mu, test_cov = data_dict['test']
for k, (mu, cov) in data_dict.items():
if k != 'test':
fid_score = calculate_frechet_distance(test_mu, test_cov, mu, cov)
f.write(f"{k} vs test data FID: {fid_score:.2f}\n")
f.close()
def run_swd_tests(train_dir, generator, data_embeddings, train_dataset, test_dataset, samplers, device):
n_samples = len(test_dataset)
batch_size = 128
data_dict = {"test": torch.from_numpy([test_dataset[i][1] for i in range(len(test_dataset))]),
"train": torch.from_numpy([train_dataset[i][1] for i in range(len(test_dataset))])}
with torch.no_grad():
images = []
for i in range(n_samples // batch_size):
images.append(generator(data_embeddings[i*batch_size: (i+1)*batch_size]).cpu())
leftover = n_samples % batch_size
if leftover > 0:
images.append(generator(data_embeddings[-leftover:]).cpu())
data_dict['reconstructions'] = torch.cat(images)
for sampler in samplers:
images = []
for i in range(n_samples // batch_size):
images.append(generator(sampler.sample(batch_size)).cpu())
leftover = n_samples % batch_size
if leftover > 0:
images.append(generator(sampler.sample(leftover)).cpu())
data_dict[sampler.name] = torch.cat(images)
print("Computing SWD scores")
f = open(os.path.join(train_dir, "SWD-scores.txt"), 'w')
for k, data in data_dict.items():
if k != 'test':
swd_score = compute_swd(data_dict['test'].float(), data.float(), device='cuda')
f.write(f"{k} vs test data FID: {swd_score:.2f}\n")
f.close() | en | 0.82521 | Compute The FID score of the train, GLO, IMLE and reconstructed images distribution compared to the test distribution # Computing Inception activations # get activations for real images from test set # get activations for real images from train set # get activations for reconstructed images # get activations for generated images with various samplers | 2.093657 | 2 |
frappe-bench/env/lib/python2.7/site-packages/num2words/lang_PL.py | ibrahmm22/library-management | 0 | 6622276 | # -*- encoding: utf-8 -*-
# Copyright (c) 2003, <NAME>. All Rights Reserved.
# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved.
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library 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
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA
u"""
>>> from textwrap import fill
>>> ' '.join([str(i) for i in splitby3('1')])
u'1'
>>> ' '.join([str(i) for i in splitby3('1123')])
u'1 123'
>>> ' '.join([str(i) for i in splitby3('1234567890')])
u'1 234 567 890'
>>> print(' '.join([n2w(i) for i in range(10)]))
zero jeden dwa trzy cztery pięć sześć siedem osiem dziewięć
>>> print(fill(' '.join([n2w(i+10) for i in range(10)])))
dziesięć jedenaście dwanaście trzynaście czternaście piętnaście
szesnaście siedemnaście osiemnaście dziewiętnaście
>>> print(fill(' '.join([n2w(i*10) for i in range(10)])))
zero dziesięć dwadzieścia trzydzieści czterdzieści pięćdziesiąt
sześćdziesiąt siedemdziesiąt osiemdziesiąt dziewięćdzisiąt
>>> print(n2w(100))
sto
>>> print(n2w(101))
sto jeden
>>> print(n2w(110))
sto dziesięć
>>> print(n2w(115))
sto piętnaście
>>> print(n2w(123))
sto dwadzieścia trzy
>>> print(n2w(1000))
tysiąc
>>> print(n2w(1001))
tysiąc jeden
>>> print(n2w(2012))
dwa tysiące dwanaście
>>> print(n2w(12519.85))
dwanaście tysięcy pięćset dziewiętnaście przecinek osiemdziesiąt pięć
>>> print(n2w(123.50))
sto dwadzieścia trzy przecinek pięć
>>> print(fill(n2w(1234567890)))
miliard dwieście trzydzieści cztery miliony pięćset sześćdziesiąt
siedem tysięcy osiemset dziewięćdzisiąt
>>> print(fill(n2w(215461407892039002157189883901676)))
dwieście piętnaście kwintylionów czterysta sześćdziesiąt jeden
kwadryliardów czterysta siedem kwadrylionów osiemset dziewięćdzisiąt
dwa tryliardy trzydzieści dziewięć trylionów dwa biliardy sto
pięćdziesiąt siedem bilionów sto osiemdziesiąt dziewięć miliardów
osiemset osiemdziesiąt trzy miliony dziewęćset jeden tysięcy sześćset
siedemdziesiąt sześć
>>> print(fill(n2w(719094234693663034822824384220291)))
siedemset dziewiętnaście kwintylionów dziewięćdzisiąt cztery
kwadryliardy dwieście trzydzieści cztery kwadryliony sześćset
dziewięćdzisiąt trzy tryliardy sześćset sześćdziesiąt trzy tryliony
trzydzieści cztery biliardy osiemset dwadzieścia dwa biliony osiemset
dwadzieścia cztery miliardy trzysta osiemdziesiąt cztery miliony
dwieście dwadzieścia tysięcy dwieście dziewięćdzisiąt jeden
>>> print(to_currency(1.0, 'EUR'))
jeden euro, zero centów
>>> print(to_currency(1.0, 'PLN'))
jeden złoty, zero groszy
>>> print(to_currency(1234.56, 'EUR'))
tysiąc dwieście trzydzieści cztery euro, pięćdziesiąt sześć centów
>>> print(to_currency(1234.56, 'PLN'))
tysiąc dwieście trzydzieści cztery złote, pięćdziesiąt sześć groszy
>>> print(to_currency(10111, 'EUR', seperator=' i'))
sto jeden euro i jedenaście centów
>>> print(to_currency(10121, 'PLN', seperator=' i'))
sto jeden złotych i dwadzieścia jeden groszy
>>> print(to_currency(-1251985, cents = False))
minus dwanaście tysięcy pięćset dziewiętnaście euro, 85 centów
>>> print(to_currency(123.50, 'PLN', seperator=' i'))
sto dwadzieścia trzy złote i pięćdziesiąt groszy
"""
from __future__ import unicode_literals
ZERO = (u'zero',)
ONES = {
1: (u'jeden',),
2: (u'dwa',),
3: (u'trzy',),
4: (u'cztery',),
5: (u'pięć',),
6: (u'sześć',),
7: (u'siedem',),
8: (u'osiem',),
9: (u'dziewięć',),
}
TENS = {
0: (u'dziesięć',),
1: (u'jedenaście',),
2: (u'dwanaście',),
3: (u'trzynaście',),
4: (u'czternaście',),
5: (u'piętnaście',),
6: (u'szesnaście',),
7: (u'siedemnaście',),
8: (u'osiemnaście',),
9: (u'dziewiętnaście',),
}
TWENTIES = {
2: (u'dwadzieścia',),
3: (u'trzydzieści',),
4: (u'czterdzieści',),
5: (u'pięćdziesiąt',),
6: (u'sześćdziesiąt',),
7: (u'siedemdziesiąt',),
8: (u'osiemdziesiąt',),
9: (u'dziewięćdzisiąt',),
}
HUNDREDS = {
1: (u'sto',),
2: (u'dwieście',),
3: (u'trzysta',),
4: (u'czterysta',),
5: (u'pięćset',),
6: (u'sześćset',),
7: (u'siedemset',),
8: (u'osiemset',),
9: (u'dziewęćset',),
}
THOUSANDS = {
1: (u'tysiąc', u'tysiące', u'tysięcy'), # 10^3
2: (u'milion', u'miliony', u'milionów'), # 10^6
3: (u'miliard', u'miliardy', u'miliardów'), # 10^9
4: (u'bilion', u'biliony', u'bilionów'), # 10^12
5: (u'biliard', u'biliardy', u'biliardów'), # 10^15
6: (u'trylion', u'tryliony', u'trylionów'), # 10^18
7: (u'tryliard', u'tryliardy', u'tryliardów'), # 10^21
8: (u'kwadrylion', u'kwadryliony', u'kwadrylionów'), # 10^24
9: (u'kwaryliard', u'kwadryliardy', u'kwadryliardów'), #10^27
10: (u'kwintylion', u'kwintyliony', u'kwintylionów'), # 10^30
}
CURRENCIES = {
'PLN': (
(u'złoty', u'złote', u'złotych'), (u'grosz', u'grosze', u'groszy')
),
'EUR': (
(u'euro', u'euro', u'euro'), (u'cent', u'centy', u'centów')
),
}
def splitby3(n):
length = len(n)
if length > 3:
start = length % 3
if start > 0:
yield int(n[:start])
for i in range(start, length, 3):
yield int(n[i:i + 3])
else:
yield int(n)
def get_digits(n):
return [int(x) for x in reversed(list(('%03d' % n)[-3:]))]
def pluralize(n, forms):
form = 0 if n == 1 else 1 if (n % 10 > 1 and n % 10 < 5 and (n % 100 < 10 or n % 100 > 20)) else 2
return forms[form]
def int2word(n):
if n == 0:
return ZERO[0]
words = []
chunks = list(splitby3(str(n)))
i = len(chunks)
for x in chunks:
i -= 1
n1, n2, n3 = get_digits(x)
if n3 > 0:
words.append(HUNDREDS[n3][0])
if n2 > 1:
words.append(TWENTIES[n2][0])
if n2 == 1:
words.append(TENS[n1][0])
elif n1 > 0 and not (i > 0 and x == 1):
words.append(ONES[n1][0])
if i > 0:
words.append(pluralize(x, THOUSANDS[i]))
return ' '.join(words)
def n2w(n):
n = str(n).replace(',', '.')
if '.' in n:
left, right = n.split('.')
return u'%s przecinek %s' % (int2word(int(left)), int2word(int(right)))
else:
return int2word(int(n))
def to_currency(n, currency = 'EUR', cents = True, seperator = ','):
if type(n) == int:
if n < 0:
minus = True
else:
minus = False
n = abs(n)
left = n // 100
right = n % 100
else:
n = str(n).replace(',', '.')
if '.' in n:
left, right = n.split('.')
if len(right) == 1:
right = right + '0'
else:
left, right = n, 0
left, right = int(left), int(right)
minus = False
cr1, cr2 = CURRENCIES[currency]
if minus:
minus_str = "minus "
else:
minus_str = ""
if cents:
cents_str = int2word(right)
else:
cents_str = "%02d" % right
return u'%s%s %s%s %s %s' % (
minus_str,
int2word(left),
pluralize(left, cr1),
seperator,
cents_str,
pluralize(right, cr2)
)
class Num2Word_PL(object):
def to_cardinal(self, number):
return n2w(number)
def to_ordinal(self, number):
raise NotImplementedError()
if __name__ == '__main__':
import doctest
doctest.testmod()
| # -*- encoding: utf-8 -*-
# Copyright (c) 2003, <NAME>. All Rights Reserved.
# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved.
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library 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
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA
u"""
>>> from textwrap import fill
>>> ' '.join([str(i) for i in splitby3('1')])
u'1'
>>> ' '.join([str(i) for i in splitby3('1123')])
u'1 123'
>>> ' '.join([str(i) for i in splitby3('1234567890')])
u'1 234 567 890'
>>> print(' '.join([n2w(i) for i in range(10)]))
zero jeden dwa trzy cztery pięć sześć siedem osiem dziewięć
>>> print(fill(' '.join([n2w(i+10) for i in range(10)])))
dziesięć jedenaście dwanaście trzynaście czternaście piętnaście
szesnaście siedemnaście osiemnaście dziewiętnaście
>>> print(fill(' '.join([n2w(i*10) for i in range(10)])))
zero dziesięć dwadzieścia trzydzieści czterdzieści pięćdziesiąt
sześćdziesiąt siedemdziesiąt osiemdziesiąt dziewięćdzisiąt
>>> print(n2w(100))
sto
>>> print(n2w(101))
sto jeden
>>> print(n2w(110))
sto dziesięć
>>> print(n2w(115))
sto piętnaście
>>> print(n2w(123))
sto dwadzieścia trzy
>>> print(n2w(1000))
tysiąc
>>> print(n2w(1001))
tysiąc jeden
>>> print(n2w(2012))
dwa tysiące dwanaście
>>> print(n2w(12519.85))
dwanaście tysięcy pięćset dziewiętnaście przecinek osiemdziesiąt pięć
>>> print(n2w(123.50))
sto dwadzieścia trzy przecinek pięć
>>> print(fill(n2w(1234567890)))
miliard dwieście trzydzieści cztery miliony pięćset sześćdziesiąt
siedem tysięcy osiemset dziewięćdzisiąt
>>> print(fill(n2w(215461407892039002157189883901676)))
dwieście piętnaście kwintylionów czterysta sześćdziesiąt jeden
kwadryliardów czterysta siedem kwadrylionów osiemset dziewięćdzisiąt
dwa tryliardy trzydzieści dziewięć trylionów dwa biliardy sto
pięćdziesiąt siedem bilionów sto osiemdziesiąt dziewięć miliardów
osiemset osiemdziesiąt trzy miliony dziewęćset jeden tysięcy sześćset
siedemdziesiąt sześć
>>> print(fill(n2w(719094234693663034822824384220291)))
siedemset dziewiętnaście kwintylionów dziewięćdzisiąt cztery
kwadryliardy dwieście trzydzieści cztery kwadryliony sześćset
dziewięćdzisiąt trzy tryliardy sześćset sześćdziesiąt trzy tryliony
trzydzieści cztery biliardy osiemset dwadzieścia dwa biliony osiemset
dwadzieścia cztery miliardy trzysta osiemdziesiąt cztery miliony
dwieście dwadzieścia tysięcy dwieście dziewięćdzisiąt jeden
>>> print(to_currency(1.0, 'EUR'))
jeden euro, zero centów
>>> print(to_currency(1.0, 'PLN'))
jeden złoty, zero groszy
>>> print(to_currency(1234.56, 'EUR'))
tysiąc dwieście trzydzieści cztery euro, pięćdziesiąt sześć centów
>>> print(to_currency(1234.56, 'PLN'))
tysiąc dwieście trzydzieści cztery złote, pięćdziesiąt sześć groszy
>>> print(to_currency(10111, 'EUR', seperator=' i'))
sto jeden euro i jedenaście centów
>>> print(to_currency(10121, 'PLN', seperator=' i'))
sto jeden złotych i dwadzieścia jeden groszy
>>> print(to_currency(-1251985, cents = False))
minus dwanaście tysięcy pięćset dziewiętnaście euro, 85 centów
>>> print(to_currency(123.50, 'PLN', seperator=' i'))
sto dwadzieścia trzy złote i pięćdziesiąt groszy
"""
from __future__ import unicode_literals
ZERO = (u'zero',)
ONES = {
1: (u'jeden',),
2: (u'dwa',),
3: (u'trzy',),
4: (u'cztery',),
5: (u'pięć',),
6: (u'sześć',),
7: (u'siedem',),
8: (u'osiem',),
9: (u'dziewięć',),
}
TENS = {
0: (u'dziesięć',),
1: (u'jedenaście',),
2: (u'dwanaście',),
3: (u'trzynaście',),
4: (u'czternaście',),
5: (u'piętnaście',),
6: (u'szesnaście',),
7: (u'siedemnaście',),
8: (u'osiemnaście',),
9: (u'dziewiętnaście',),
}
TWENTIES = {
2: (u'dwadzieścia',),
3: (u'trzydzieści',),
4: (u'czterdzieści',),
5: (u'pięćdziesiąt',),
6: (u'sześćdziesiąt',),
7: (u'siedemdziesiąt',),
8: (u'osiemdziesiąt',),
9: (u'dziewięćdzisiąt',),
}
HUNDREDS = {
1: (u'sto',),
2: (u'dwieście',),
3: (u'trzysta',),
4: (u'czterysta',),
5: (u'pięćset',),
6: (u'sześćset',),
7: (u'siedemset',),
8: (u'osiemset',),
9: (u'dziewęćset',),
}
THOUSANDS = {
1: (u'tysiąc', u'tysiące', u'tysięcy'), # 10^3
2: (u'milion', u'miliony', u'milionów'), # 10^6
3: (u'miliard', u'miliardy', u'miliardów'), # 10^9
4: (u'bilion', u'biliony', u'bilionów'), # 10^12
5: (u'biliard', u'biliardy', u'biliardów'), # 10^15
6: (u'trylion', u'tryliony', u'trylionów'), # 10^18
7: (u'tryliard', u'tryliardy', u'tryliardów'), # 10^21
8: (u'kwadrylion', u'kwadryliony', u'kwadrylionów'), # 10^24
9: (u'kwaryliard', u'kwadryliardy', u'kwadryliardów'), #10^27
10: (u'kwintylion', u'kwintyliony', u'kwintylionów'), # 10^30
}
CURRENCIES = {
'PLN': (
(u'złoty', u'złote', u'złotych'), (u'grosz', u'grosze', u'groszy')
),
'EUR': (
(u'euro', u'euro', u'euro'), (u'cent', u'centy', u'centów')
),
}
def splitby3(n):
length = len(n)
if length > 3:
start = length % 3
if start > 0:
yield int(n[:start])
for i in range(start, length, 3):
yield int(n[i:i + 3])
else:
yield int(n)
def get_digits(n):
return [int(x) for x in reversed(list(('%03d' % n)[-3:]))]
def pluralize(n, forms):
form = 0 if n == 1 else 1 if (n % 10 > 1 and n % 10 < 5 and (n % 100 < 10 or n % 100 > 20)) else 2
return forms[form]
def int2word(n):
if n == 0:
return ZERO[0]
words = []
chunks = list(splitby3(str(n)))
i = len(chunks)
for x in chunks:
i -= 1
n1, n2, n3 = get_digits(x)
if n3 > 0:
words.append(HUNDREDS[n3][0])
if n2 > 1:
words.append(TWENTIES[n2][0])
if n2 == 1:
words.append(TENS[n1][0])
elif n1 > 0 and not (i > 0 and x == 1):
words.append(ONES[n1][0])
if i > 0:
words.append(pluralize(x, THOUSANDS[i]))
return ' '.join(words)
def n2w(n):
n = str(n).replace(',', '.')
if '.' in n:
left, right = n.split('.')
return u'%s przecinek %s' % (int2word(int(left)), int2word(int(right)))
else:
return int2word(int(n))
def to_currency(n, currency = 'EUR', cents = True, seperator = ','):
if type(n) == int:
if n < 0:
minus = True
else:
minus = False
n = abs(n)
left = n // 100
right = n % 100
else:
n = str(n).replace(',', '.')
if '.' in n:
left, right = n.split('.')
if len(right) == 1:
right = right + '0'
else:
left, right = n, 0
left, right = int(left), int(right)
minus = False
cr1, cr2 = CURRENCIES[currency]
if minus:
minus_str = "minus "
else:
minus_str = ""
if cents:
cents_str = int2word(right)
else:
cents_str = "%02d" % right
return u'%s%s %s%s %s %s' % (
minus_str,
int2word(left),
pluralize(left, cr1),
seperator,
cents_str,
pluralize(right, cr2)
)
class Num2Word_PL(object):
def to_cardinal(self, number):
return n2w(number)
def to_ordinal(self, number):
raise NotImplementedError()
if __name__ == '__main__':
import doctest
doctest.testmod()
| pl | 0.829935 | # -*- encoding: utf-8 -*- # Copyright (c) 2003, <NAME>. All Rights Reserved. # Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # This library 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 # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA >>> from textwrap import fill >>> ' '.join([str(i) for i in splitby3('1')]) u'1' >>> ' '.join([str(i) for i in splitby3('1123')]) u'1 123' >>> ' '.join([str(i) for i in splitby3('1234567890')]) u'1 234 567 890' >>> print(' '.join([n2w(i) for i in range(10)])) zero jeden dwa trzy cztery pięć sześć siedem osiem dziewięć >>> print(fill(' '.join([n2w(i+10) for i in range(10)]))) dziesięć jedenaście dwanaście trzynaście czternaście piętnaście szesnaście siedemnaście osiemnaście dziewiętnaście >>> print(fill(' '.join([n2w(i*10) for i in range(10)]))) zero dziesięć dwadzieścia trzydzieści czterdzieści pięćdziesiąt sześćdziesiąt siedemdziesiąt osiemdziesiąt dziewięćdzisiąt >>> print(n2w(100)) sto >>> print(n2w(101)) sto jeden >>> print(n2w(110)) sto dziesięć >>> print(n2w(115)) sto piętnaście >>> print(n2w(123)) sto dwadzieścia trzy >>> print(n2w(1000)) tysiąc >>> print(n2w(1001)) tysiąc jeden >>> print(n2w(2012)) dwa tysiące dwanaście >>> print(n2w(12519.85)) dwanaście tysięcy pięćset dziewiętnaście przecinek osiemdziesiąt pięć >>> print(n2w(123.50)) sto dwadzieścia trzy przecinek pięć >>> print(fill(n2w(1234567890))) miliard dwieście trzydzieści cztery miliony pięćset sześćdziesiąt siedem tysięcy osiemset dziewięćdzisiąt >>> print(fill(n2w(215461407892039002157189883901676))) dwieście piętnaście kwintylionów czterysta sześćdziesiąt jeden kwadryliardów czterysta siedem kwadrylionów osiemset dziewięćdzisiąt dwa tryliardy trzydzieści dziewięć trylionów dwa biliardy sto pięćdziesiąt siedem bilionów sto osiemdziesiąt dziewięć miliardów osiemset osiemdziesiąt trzy miliony dziewęćset jeden tysięcy sześćset siedemdziesiąt sześć >>> print(fill(n2w(719094234693663034822824384220291))) siedemset dziewiętnaście kwintylionów dziewięćdzisiąt cztery kwadryliardy dwieście trzydzieści cztery kwadryliony sześćset dziewięćdzisiąt trzy tryliardy sześćset sześćdziesiąt trzy tryliony trzydzieści cztery biliardy osiemset dwadzieścia dwa biliony osiemset dwadzieścia cztery miliardy trzysta osiemdziesiąt cztery miliony dwieście dwadzieścia tysięcy dwieście dziewięćdzisiąt jeden >>> print(to_currency(1.0, 'EUR')) jeden euro, zero centów >>> print(to_currency(1.0, 'PLN')) jeden złoty, zero groszy >>> print(to_currency(1234.56, 'EUR')) tysiąc dwieście trzydzieści cztery euro, pięćdziesiąt sześć centów >>> print(to_currency(1234.56, 'PLN')) tysiąc dwieście trzydzieści cztery złote, pięćdziesiąt sześć groszy >>> print(to_currency(10111, 'EUR', seperator=' i')) sto jeden euro i jedenaście centów >>> print(to_currency(10121, 'PLN', seperator=' i')) sto jeden złotych i dwadzieścia jeden groszy >>> print(to_currency(-1251985, cents = False)) minus dwanaście tysięcy pięćset dziewiętnaście euro, 85 centów >>> print(to_currency(123.50, 'PLN', seperator=' i')) sto dwadzieścia trzy złote i pięćdziesiąt groszy # 10^3 # 10^6 # 10^9 # 10^12 # 10^15 # 10^18 # 10^21 # 10^24 #10^27 # 10^30 | 2.803401 | 3 |
pants-completion.py | hythloday/pants | 0 | 6622277 | #!/usr/bin/env python
# goals=./pants goal goals | egrep -o -- '^ +([a-z-]+):' | egrep -o -- '[a-z-]+'
#
# for goal in $goals; do
# echo $goal
# ./pants goal $goal --help | egrep -o -- '--([a-z-]+)' > $goal.options
# done
import os
for options in [ o for o in os.listdir('.') if o.endswith('options') ]:
goal = options[:-8]
tpl = """ %s)
local opts='%s'
__comp "$opts"
;;
"""
with file(options, "rb") as f:
content = f.read().replace('\n', ' ')
print tpl % (goal, content)
# rm *.options
| #!/usr/bin/env python
# goals=./pants goal goals | egrep -o -- '^ +([a-z-]+):' | egrep -o -- '[a-z-]+'
#
# for goal in $goals; do
# echo $goal
# ./pants goal $goal --help | egrep -o -- '--([a-z-]+)' > $goal.options
# done
import os
for options in [ o for o in os.listdir('.') if o.endswith('options') ]:
goal = options[:-8]
tpl = """ %s)
local opts='%s'
__comp "$opts"
;;
"""
with file(options, "rb") as f:
content = f.read().replace('\n', ' ')
print tpl % (goal, content)
# rm *.options
| en | 0.328978 | #!/usr/bin/env python # goals=./pants goal goals | egrep -o -- '^ +([a-z-]+):' | egrep -o -- '[a-z-]+' # # for goal in $goals; do # echo $goal # ./pants goal $goal --help | egrep -o -- '--([a-z-]+)' > $goal.options # done %s) local opts='%s' __comp "$opts" ;; # rm *.options | 2.71268 | 3 |
esmvalcore/experimental/recipe.py | markelg/ESMValCore | 26 | 6622278 | """Recipe metadata."""
import logging
import os
import pprint
import shutil
from pathlib import Path
from typing import Dict, Optional
import yaml
from esmvalcore._recipe import Recipe as RecipeEngine
from esmvalcore.experimental.config import Session
from . import CFG
from ._logging import log_to_dir
from .recipe_info import RecipeInfo
from .recipe_output import RecipeOutput
logger = logging.getLogger(__file__)
class Recipe():
"""API wrapper for the esmvalcore Recipe object.
This class can be used to inspect and run the recipe.
Parameters
----------
path : pathlike
Path to the recipe.
"""
def __init__(self, path: os.PathLike):
self.path = Path(path)
if not self.path.exists():
raise FileNotFoundError(f'Cannot find recipe: `{path}`.')
self._engine: Optional[RecipeEngine] = None
self._data: Optional[Dict] = None
self.last_session: Optional[Session] = None
self.info = RecipeInfo(self.data, filename=self.path.name)
def __repr__(self) -> str:
"""Return canonical string representation."""
return f'{self.__class__.__name__}({self.name!r})'
def __str__(self) -> str:
"""Return string representation."""
return str(self.info)
def _repr_html_(self) -> str:
"""Return html representation."""
return self.render()
def render(self, template=None):
"""Render output as html.
template : :obj:`Template`
An instance of :py:class:`jinja2.Template` can be passed to
customize the output.
"""
return self.info.render(template=template)
@property
def name(self):
"""Return the name of the recipe."""
return self.info.name
@property
def data(self) -> dict:
"""Return dictionary representation of the recipe."""
if self._data is None:
self._data = yaml.safe_load(open(self.path, 'r'))
return self._data
def _load(self, session: Session) -> RecipeEngine:
"""Load the recipe.
This method loads the recipe into the internal ESMValCore Recipe
format.
Parameters
----------
session : :obj:`Session`
Defines the config parameters and location where the recipe
output will be stored. If ``None``, a new session will be
started automatically.
Returns
-------
recipe : :obj:`esmvalcore._recipe.Recipe`
Return an instance of the Recipe
"""
config_user = session.to_config_user()
logger.info(pprint.pformat(config_user))
return RecipeEngine(raw_recipe=self.data,
config_user=config_user,
recipe_file=self.path)
def run(self, task: str = None, session: Session = None):
"""Run the recipe.
This function loads the recipe into the ESMValCore recipe format
and runs it.
Parameters
----------
task : str
Specify the name of the diagnostic or preprocessor to run a
single task.
session : :obj:`Session`, optional
Defines the config parameters and location where the recipe
output will be stored. If ``None``, a new session will be
started automatically.
Returns
-------
output : dict
Returns output of the recipe as instances of :obj:`OutputItem`
grouped by diagnostic task.
"""
if session is None:
session = CFG.start_session(self.path.stem)
self.last_session = session
if task:
session['diagnostics'] = task
with log_to_dir(session.run_dir):
self._engine = self._load(session=session)
self._engine.run()
shutil.copy2(self.path, session.run_dir)
output = self.get_output()
output.write_html()
return output
def get_output(self) -> RecipeOutput:
"""Get output from recipe.
Returns
-------
output : dict
Returns output of the recipe as instances of :obj:`OutputFile`
grouped by diagnostic task.
"""
if self._engine is None:
raise AttributeError('Run the recipe first using `.run()`.')
output = self._engine.get_output()
task_output = output['task_output']
return RecipeOutput(
task_output=task_output,
session=self.last_session,
info=self.info,
)
| """Recipe metadata."""
import logging
import os
import pprint
import shutil
from pathlib import Path
from typing import Dict, Optional
import yaml
from esmvalcore._recipe import Recipe as RecipeEngine
from esmvalcore.experimental.config import Session
from . import CFG
from ._logging import log_to_dir
from .recipe_info import RecipeInfo
from .recipe_output import RecipeOutput
logger = logging.getLogger(__file__)
class Recipe():
"""API wrapper for the esmvalcore Recipe object.
This class can be used to inspect and run the recipe.
Parameters
----------
path : pathlike
Path to the recipe.
"""
def __init__(self, path: os.PathLike):
self.path = Path(path)
if not self.path.exists():
raise FileNotFoundError(f'Cannot find recipe: `{path}`.')
self._engine: Optional[RecipeEngine] = None
self._data: Optional[Dict] = None
self.last_session: Optional[Session] = None
self.info = RecipeInfo(self.data, filename=self.path.name)
def __repr__(self) -> str:
"""Return canonical string representation."""
return f'{self.__class__.__name__}({self.name!r})'
def __str__(self) -> str:
"""Return string representation."""
return str(self.info)
def _repr_html_(self) -> str:
"""Return html representation."""
return self.render()
def render(self, template=None):
"""Render output as html.
template : :obj:`Template`
An instance of :py:class:`jinja2.Template` can be passed to
customize the output.
"""
return self.info.render(template=template)
@property
def name(self):
"""Return the name of the recipe."""
return self.info.name
@property
def data(self) -> dict:
"""Return dictionary representation of the recipe."""
if self._data is None:
self._data = yaml.safe_load(open(self.path, 'r'))
return self._data
def _load(self, session: Session) -> RecipeEngine:
"""Load the recipe.
This method loads the recipe into the internal ESMValCore Recipe
format.
Parameters
----------
session : :obj:`Session`
Defines the config parameters and location where the recipe
output will be stored. If ``None``, a new session will be
started automatically.
Returns
-------
recipe : :obj:`esmvalcore._recipe.Recipe`
Return an instance of the Recipe
"""
config_user = session.to_config_user()
logger.info(pprint.pformat(config_user))
return RecipeEngine(raw_recipe=self.data,
config_user=config_user,
recipe_file=self.path)
def run(self, task: str = None, session: Session = None):
"""Run the recipe.
This function loads the recipe into the ESMValCore recipe format
and runs it.
Parameters
----------
task : str
Specify the name of the diagnostic or preprocessor to run a
single task.
session : :obj:`Session`, optional
Defines the config parameters and location where the recipe
output will be stored. If ``None``, a new session will be
started automatically.
Returns
-------
output : dict
Returns output of the recipe as instances of :obj:`OutputItem`
grouped by diagnostic task.
"""
if session is None:
session = CFG.start_session(self.path.stem)
self.last_session = session
if task:
session['diagnostics'] = task
with log_to_dir(session.run_dir):
self._engine = self._load(session=session)
self._engine.run()
shutil.copy2(self.path, session.run_dir)
output = self.get_output()
output.write_html()
return output
def get_output(self) -> RecipeOutput:
"""Get output from recipe.
Returns
-------
output : dict
Returns output of the recipe as instances of :obj:`OutputFile`
grouped by diagnostic task.
"""
if self._engine is None:
raise AttributeError('Run the recipe first using `.run()`.')
output = self._engine.get_output()
task_output = output['task_output']
return RecipeOutput(
task_output=task_output,
session=self.last_session,
info=self.info,
)
| en | 0.637812 | Recipe metadata. API wrapper for the esmvalcore Recipe object. This class can be used to inspect and run the recipe. Parameters ---------- path : pathlike Path to the recipe. Return canonical string representation. Return string representation. Return html representation. Render output as html. template : :obj:`Template` An instance of :py:class:`jinja2.Template` can be passed to customize the output. Return the name of the recipe. Return dictionary representation of the recipe. Load the recipe. This method loads the recipe into the internal ESMValCore Recipe format. Parameters ---------- session : :obj:`Session` Defines the config parameters and location where the recipe output will be stored. If ``None``, a new session will be started automatically. Returns ------- recipe : :obj:`esmvalcore._recipe.Recipe` Return an instance of the Recipe Run the recipe. This function loads the recipe into the ESMValCore recipe format and runs it. Parameters ---------- task : str Specify the name of the diagnostic or preprocessor to run a single task. session : :obj:`Session`, optional Defines the config parameters and location where the recipe output will be stored. If ``None``, a new session will be started automatically. Returns ------- output : dict Returns output of the recipe as instances of :obj:`OutputItem` grouped by diagnostic task. Get output from recipe. Returns ------- output : dict Returns output of the recipe as instances of :obj:`OutputFile` grouped by diagnostic task. | 2.222687 | 2 |
visualDet3D/utils/visualize_utils.py | saurav1869/saurav1869-mono3d_road | 0 | 6622279 | <gh_stars>0
import cv2
import numpy as np
import sys
import torch
from torch.utils.data import DataLoader
sys.path.append("../")
from visualDet3D.networks.utils import BackProjection, BBox3dProjector
from visualDet3D.data.kitti.dataset import mono_dataset
from visualDet3D.utils.utils import cfg_from_file
from visualDet3D.utils.utils import compound_annotation
backprojector = BackProjection()
projector = BBox3dProjector()
def draw_bbox2d_to_image(image, bboxes2d, color=(0, 0, 0), thickness=3):
drawed_image = image.copy()
for box2d in bboxes2d:
drawed_image = cv2.rectangle(
drawed_image, (int(box2d[0]), int(box2d[1])), (int(box2d[2]), int(box2d[3])), color, thickness)
return drawed_image
def draw_points(image, bottom_points, color=(0, 0, 255), thickness=3):
drawed_image = image.copy()
for bottom_point in bottom_points:
drawed_image = cv2.circle(
drawed_image, (int(bottom_point[0]), int(bottom_point[1])),
radius=1, color=color, thickness=thickness)
return drawed_image
def anchor_to_bbox(anchors):
"""
params:
anchors = np.ndarray(N, 4) # (x, y, w, l)
return:
bboxes = np.ndarray(N, 4) # (x1, y1, x2, y2)
"""
bboxes = np.ones(anchors.shape)
bboxes[:, 0] = anchors[:, 0] - anchors[:, 2] / 2
bboxes[:, 1] = anchors[:, 1] - anchors[:, 3] / 2
bboxes[:, 2] = anchors[:, 0] + anchors[:, 2] / 2
bboxes[:, 3] = anchors[:, 1] + anchors[:, 3] / 2
return bboxes
def get_bev_bboxes(annotations, P2):
if annotations.shape[0] == 0:
return np.ones((0, 2, 2))
if annotations.shape[1] == 11:
bbox_3d_state = annotations[:, 4:]
else:
bbox_3d_state = annotations[:, 5:]
bbox_3d_state = bbox_3d_state[torch.any(bbox_3d_state != -1, 1)]
bbox_3d_state_3d = backprojector(bbox_3d_state, P2)
abs_bbox, bbox_3d_corner_homo, thetas = projector(bbox_3d_state_3d, P2)
# mean_x = bbox_3d_state_3d[:, 0].mean()
# mean_z = bbox_3d_state_3d[:, 2].mean()
scale = 10
bbox_3d_state_3d[:, 0] = (bbox_3d_state_3d[:, 0]) * scale
bbox_3d_state_3d[:, 2] = (bbox_3d_state_3d[:, 2]) * scale
scale = 5
bbox_3d_state_3d[:, 3:] = bbox_3d_state_3d[:, 3:] * scale
points = []
for bbox_3d in bbox_3d_state_3d:
x, y, z, w, h, l, alpha = bbox_3d.numpy()
point = np.array([[x - w/2, z - l/2], [x + w/2, z + l/2]])
points.append(point)
if not points:
return np.ones((0, 2, 2))
points = np.stack(points).astype(np.int)
return points
def add_bboxes_to_image(bboxes, shape=(800, 800, 3), color=(0, 0, 0), image=None):
if type(color) == tuple:
color = [color] * len(bboxes)
for idx, points in enumerate(bboxes):
image = np.ones(shape).astype(np.uint8) * 255 if image is None else image
mean_x = np.abs(points[:, :, 0].mean()).astype(np.int)
mean_z = np.abs(points[:, :, 1].mean()).astype(np.int)
points[:, :, 0] += int(shape[0] / 2) - mean_x
points[:, :, 1] += int(shape[1] / 2) - mean_z
for bbox in points:
image = cv2.rectangle(image, bbox[0], bbox[1], color[idx], 1)
return image
def get_bev_pred_gt(pred, gt, P2, shape=(800, 800, 3), colors=[(255, 0, 0), (0, 0, 255)]):
bboxes = [get_bev_bboxes(pred, P2), get_bev_bboxes(gt, P2)]
return add_bboxes_to_image(bboxes, color=colors)
def get_bev_image(annotations, P2, shape=(800, 800, 3), color=(0, 0, 0), image=None):
image = np.ones(shape).astype(np.uint8) * 255 if image is None else image
if annotations.shape[0] == 0:
return image
if annotations.shape[1] == 11:
bbox_3d_state = annotations[:, 4:]
else:
bbox_3d_state = annotations[:, 5:]
bbox_3d_state = bbox_3d_state[torch.any(bbox_3d_state != -1, 1)]
bbox_3d_state_3d = backprojector(bbox_3d_state, P2)
abs_bbox, bbox_3d_corner_homo, thetas = projector(bbox_3d_state_3d, P2)
mean_x = bbox_3d_state_3d[:, 0].mean()
mean_z = bbox_3d_state_3d[:, 2].mean()
scale = 10
bbox_3d_state_3d[:, 0] = (bbox_3d_state_3d[:, 0] - mean_x) * scale
bbox_3d_state_3d[:, 2] = (bbox_3d_state_3d[:, 2] - mean_z) * scale
scale = 5
bbox_3d_state_3d[:, 3:] = bbox_3d_state_3d[:, 3:] * scale
points = []
for bbox_3d in bbox_3d_state_3d:
x, y, z, w, h, l, alpha = bbox_3d.numpy()
point = np.array([[x - w/2, z - l/2], [x + w/2, z + l/2]])
points.append(point)
if not points:
return image
points = np.stack(points).astype(np.int)
mean_x = np.abs(points[:, :, 0].mean()).astype(np.int)
mean_z = np.abs(points[:, :, 1].mean()).astype(np.int)
points[:, :, 0] += int(shape[0] / 2) - mean_x
points[:, :, 1] += int(shape[1] / 2) - mean_z
for bbox in points:
image = cv2.rectangle(image, bbox[0], bbox[1], color, 1)
return image
def get_corners(bbox):
# w, h, l, y, z, x, yaw = bbox
y, z, x, w, h, l, yaw = bbox
y = -y
# manually take a negative s. t. it's a right-hand
# system, with
# x facing in the front windshield of the
# car
# z facing up
# y facing to the left of
# driver
# yaw = -(yaw + np.pi / 2)
bev_corners = np.zeros((4, 2), dtype=np.float32)
# rear
# left
bev_corners[0, 0] = x - l/2 * np.cos(yaw) - w/2 * np.sin(yaw)
bev_corners[0, 1] = y - l/2 * np.sin(yaw) + w/2 * np.cos(yaw)
# rear
# right
bev_corners[1, 0] = x - l/2 * np.cos(yaw) + w/2 * np.sin(yaw)
bev_corners[1, 1] = y - l/2 * np.sin(yaw) - w/2 * np.cos(yaw)
# front
# right
bev_corners[2, 0] = x + l/2 * np.cos(yaw) + w/2 * np.sin(yaw)
bev_corners[2, 1] = y + l/2 * np.sin(yaw) - w/2 * np.cos(yaw)
# front
# left
bev_corners[3, 0] = x + l/2 * np.cos(yaw) - w/2 * np.sin(yaw)
bev_corners[3, 1] = y + l/2 * np.sin(yaw) + w/2 * np.cos(yaw)
return bev_corners
if __name__ == '__main__':
cfg = cfg_from_file("/home/shanus/workspace/3D_detection/visualDet3D/config/Road_kitti_debug.py")
dataset = mono_dataset.KittiMonoDataset(cfg)
dataloader_train = DataLoader(dataset, num_workers=cfg.data.num_workers,
batch_size=cfg.data.batch_size, collate_fn=dataset.collate_fn)
idx = 5
for index, data in enumerate(dataloader_train):
image, road_maps, calibs, labels, bbox2d, bbox_3d = data
max_length = np.max([len(label) for label in labels])
annotation = compound_annotation(labels, max_length, bbox2d, bbox_3d, cfg.obj_types)
bev_image = get_bev_image(torch.Tensor(annotation[idx]), torch.Tensor(calibs[idx]))
cv2.imwrite('bev' + str(index) + '.png', bev_image)
cv2.imwrite('image' + str(index) + '.png', image[idx].numpy().transpose(1, 2, 0))
if index > 8:
break
| import cv2
import numpy as np
import sys
import torch
from torch.utils.data import DataLoader
sys.path.append("../")
from visualDet3D.networks.utils import BackProjection, BBox3dProjector
from visualDet3D.data.kitti.dataset import mono_dataset
from visualDet3D.utils.utils import cfg_from_file
from visualDet3D.utils.utils import compound_annotation
backprojector = BackProjection()
projector = BBox3dProjector()
def draw_bbox2d_to_image(image, bboxes2d, color=(0, 0, 0), thickness=3):
drawed_image = image.copy()
for box2d in bboxes2d:
drawed_image = cv2.rectangle(
drawed_image, (int(box2d[0]), int(box2d[1])), (int(box2d[2]), int(box2d[3])), color, thickness)
return drawed_image
def draw_points(image, bottom_points, color=(0, 0, 255), thickness=3):
drawed_image = image.copy()
for bottom_point in bottom_points:
drawed_image = cv2.circle(
drawed_image, (int(bottom_point[0]), int(bottom_point[1])),
radius=1, color=color, thickness=thickness)
return drawed_image
def anchor_to_bbox(anchors):
"""
params:
anchors = np.ndarray(N, 4) # (x, y, w, l)
return:
bboxes = np.ndarray(N, 4) # (x1, y1, x2, y2)
"""
bboxes = np.ones(anchors.shape)
bboxes[:, 0] = anchors[:, 0] - anchors[:, 2] / 2
bboxes[:, 1] = anchors[:, 1] - anchors[:, 3] / 2
bboxes[:, 2] = anchors[:, 0] + anchors[:, 2] / 2
bboxes[:, 3] = anchors[:, 1] + anchors[:, 3] / 2
return bboxes
def get_bev_bboxes(annotations, P2):
if annotations.shape[0] == 0:
return np.ones((0, 2, 2))
if annotations.shape[1] == 11:
bbox_3d_state = annotations[:, 4:]
else:
bbox_3d_state = annotations[:, 5:]
bbox_3d_state = bbox_3d_state[torch.any(bbox_3d_state != -1, 1)]
bbox_3d_state_3d = backprojector(bbox_3d_state, P2)
abs_bbox, bbox_3d_corner_homo, thetas = projector(bbox_3d_state_3d, P2)
# mean_x = bbox_3d_state_3d[:, 0].mean()
# mean_z = bbox_3d_state_3d[:, 2].mean()
scale = 10
bbox_3d_state_3d[:, 0] = (bbox_3d_state_3d[:, 0]) * scale
bbox_3d_state_3d[:, 2] = (bbox_3d_state_3d[:, 2]) * scale
scale = 5
bbox_3d_state_3d[:, 3:] = bbox_3d_state_3d[:, 3:] * scale
points = []
for bbox_3d in bbox_3d_state_3d:
x, y, z, w, h, l, alpha = bbox_3d.numpy()
point = np.array([[x - w/2, z - l/2], [x + w/2, z + l/2]])
points.append(point)
if not points:
return np.ones((0, 2, 2))
points = np.stack(points).astype(np.int)
return points
def add_bboxes_to_image(bboxes, shape=(800, 800, 3), color=(0, 0, 0), image=None):
if type(color) == tuple:
color = [color] * len(bboxes)
for idx, points in enumerate(bboxes):
image = np.ones(shape).astype(np.uint8) * 255 if image is None else image
mean_x = np.abs(points[:, :, 0].mean()).astype(np.int)
mean_z = np.abs(points[:, :, 1].mean()).astype(np.int)
points[:, :, 0] += int(shape[0] / 2) - mean_x
points[:, :, 1] += int(shape[1] / 2) - mean_z
for bbox in points:
image = cv2.rectangle(image, bbox[0], bbox[1], color[idx], 1)
return image
def get_bev_pred_gt(pred, gt, P2, shape=(800, 800, 3), colors=[(255, 0, 0), (0, 0, 255)]):
bboxes = [get_bev_bboxes(pred, P2), get_bev_bboxes(gt, P2)]
return add_bboxes_to_image(bboxes, color=colors)
def get_bev_image(annotations, P2, shape=(800, 800, 3), color=(0, 0, 0), image=None):
image = np.ones(shape).astype(np.uint8) * 255 if image is None else image
if annotations.shape[0] == 0:
return image
if annotations.shape[1] == 11:
bbox_3d_state = annotations[:, 4:]
else:
bbox_3d_state = annotations[:, 5:]
bbox_3d_state = bbox_3d_state[torch.any(bbox_3d_state != -1, 1)]
bbox_3d_state_3d = backprojector(bbox_3d_state, P2)
abs_bbox, bbox_3d_corner_homo, thetas = projector(bbox_3d_state_3d, P2)
mean_x = bbox_3d_state_3d[:, 0].mean()
mean_z = bbox_3d_state_3d[:, 2].mean()
scale = 10
bbox_3d_state_3d[:, 0] = (bbox_3d_state_3d[:, 0] - mean_x) * scale
bbox_3d_state_3d[:, 2] = (bbox_3d_state_3d[:, 2] - mean_z) * scale
scale = 5
bbox_3d_state_3d[:, 3:] = bbox_3d_state_3d[:, 3:] * scale
points = []
for bbox_3d in bbox_3d_state_3d:
x, y, z, w, h, l, alpha = bbox_3d.numpy()
point = np.array([[x - w/2, z - l/2], [x + w/2, z + l/2]])
points.append(point)
if not points:
return image
points = np.stack(points).astype(np.int)
mean_x = np.abs(points[:, :, 0].mean()).astype(np.int)
mean_z = np.abs(points[:, :, 1].mean()).astype(np.int)
points[:, :, 0] += int(shape[0] / 2) - mean_x
points[:, :, 1] += int(shape[1] / 2) - mean_z
for bbox in points:
image = cv2.rectangle(image, bbox[0], bbox[1], color, 1)
return image
def get_corners(bbox):
# w, h, l, y, z, x, yaw = bbox
y, z, x, w, h, l, yaw = bbox
y = -y
# manually take a negative s. t. it's a right-hand
# system, with
# x facing in the front windshield of the
# car
# z facing up
# y facing to the left of
# driver
# yaw = -(yaw + np.pi / 2)
bev_corners = np.zeros((4, 2), dtype=np.float32)
# rear
# left
bev_corners[0, 0] = x - l/2 * np.cos(yaw) - w/2 * np.sin(yaw)
bev_corners[0, 1] = y - l/2 * np.sin(yaw) + w/2 * np.cos(yaw)
# rear
# right
bev_corners[1, 0] = x - l/2 * np.cos(yaw) + w/2 * np.sin(yaw)
bev_corners[1, 1] = y - l/2 * np.sin(yaw) - w/2 * np.cos(yaw)
# front
# right
bev_corners[2, 0] = x + l/2 * np.cos(yaw) + w/2 * np.sin(yaw)
bev_corners[2, 1] = y + l/2 * np.sin(yaw) - w/2 * np.cos(yaw)
# front
# left
bev_corners[3, 0] = x + l/2 * np.cos(yaw) - w/2 * np.sin(yaw)
bev_corners[3, 1] = y + l/2 * np.sin(yaw) + w/2 * np.cos(yaw)
return bev_corners
if __name__ == '__main__':
cfg = cfg_from_file("/home/shanus/workspace/3D_detection/visualDet3D/config/Road_kitti_debug.py")
dataset = mono_dataset.KittiMonoDataset(cfg)
dataloader_train = DataLoader(dataset, num_workers=cfg.data.num_workers,
batch_size=cfg.data.batch_size, collate_fn=dataset.collate_fn)
idx = 5
for index, data in enumerate(dataloader_train):
image, road_maps, calibs, labels, bbox2d, bbox_3d = data
max_length = np.max([len(label) for label in labels])
annotation = compound_annotation(labels, max_length, bbox2d, bbox_3d, cfg.obj_types)
bev_image = get_bev_image(torch.Tensor(annotation[idx]), torch.Tensor(calibs[idx]))
cv2.imwrite('bev' + str(index) + '.png', bev_image)
cv2.imwrite('image' + str(index) + '.png', image[idx].numpy().transpose(1, 2, 0))
if index > 8:
break | en | 0.712094 | params: anchors = np.ndarray(N, 4) # (x, y, w, l) return: bboxes = np.ndarray(N, 4) # (x1, y1, x2, y2) # mean_x = bbox_3d_state_3d[:, 0].mean() # mean_z = bbox_3d_state_3d[:, 2].mean() # w, h, l, y, z, x, yaw = bbox # manually take a negative s. t. it's a right-hand # system, with # x facing in the front windshield of the # car # z facing up # y facing to the left of # driver # yaw = -(yaw + np.pi / 2) # rear # left # rear # right # front # right # front # left | 2.282977 | 2 |
api/api.py | michaelDomingues/medinfore | 0 | 6622280 | #!/usr/bin/env python3
import fnmatch
import logging
import os
from distutils.util import strtobool
import re
from flask import Flask, jsonify, make_response, request, abort
from enigma.indexer import Indexer
logging.basicConfig(format='%(asctime)s : %(module)s: %(levelname)s : %(message)s', level=logging.DEBUG)
includes = ['*.txt']
# transform glob patterns to regular expressions
includes = r'|'.join([fnmatch.translate(x) for x in includes])
load_from_disk = True
indexer = None
app = Flask(__name__)
@app.route('/', methods=['GET'])
def home():
return jsonify({'\"message\"': 'Welcome to medinfore'})
@app.route('/search', methods=['GET'])
def search():
query = request.args.get('q')
neighborhood = request.args.get('neighbors')
synonyms = request.args.get('synonyms')
if query == "" or query is None:
abort(404)
try:
neighborhood = bool(strtobool(neighborhood))
synonyms = bool(strtobool(synonyms))
except Exception as e:
neighborhood = False
synonyms = False
logging.info('Request parameters: query=%s neighbors=%s synonyms=%s' % (query, neighborhood, synonyms))
result = indexer.search(query=query,
neighbors=neighborhood,
synonyms=synonyms)
return jsonify({"\"result\"": result})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'\"error\"': 'Not found'}), 404)
if __name__ == '__main__':
indexer = Indexer(load_from_disk)
if not load_from_disk:
for path, sub_dirs, files in os.walk("./corpus"):
files = [f for f in files if re.match(includes, f)]
for id, filename in enumerate(files):
file_path = path + '/' + filename
logging.info('Parsing file.... %s' % file_path)
indexer.index_doc(doc_path=file_path, doc_id=id)
indexer.setup_corpus_index()
app.run(debug=True)
| #!/usr/bin/env python3
import fnmatch
import logging
import os
from distutils.util import strtobool
import re
from flask import Flask, jsonify, make_response, request, abort
from enigma.indexer import Indexer
logging.basicConfig(format='%(asctime)s : %(module)s: %(levelname)s : %(message)s', level=logging.DEBUG)
includes = ['*.txt']
# transform glob patterns to regular expressions
includes = r'|'.join([fnmatch.translate(x) for x in includes])
load_from_disk = True
indexer = None
app = Flask(__name__)
@app.route('/', methods=['GET'])
def home():
return jsonify({'\"message\"': 'Welcome to medinfore'})
@app.route('/search', methods=['GET'])
def search():
query = request.args.get('q')
neighborhood = request.args.get('neighbors')
synonyms = request.args.get('synonyms')
if query == "" or query is None:
abort(404)
try:
neighborhood = bool(strtobool(neighborhood))
synonyms = bool(strtobool(synonyms))
except Exception as e:
neighborhood = False
synonyms = False
logging.info('Request parameters: query=%s neighbors=%s synonyms=%s' % (query, neighborhood, synonyms))
result = indexer.search(query=query,
neighbors=neighborhood,
synonyms=synonyms)
return jsonify({"\"result\"": result})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'\"error\"': 'Not found'}), 404)
if __name__ == '__main__':
indexer = Indexer(load_from_disk)
if not load_from_disk:
for path, sub_dirs, files in os.walk("./corpus"):
files = [f for f in files if re.match(includes, f)]
for id, filename in enumerate(files):
file_path = path + '/' + filename
logging.info('Parsing file.... %s' % file_path)
indexer.index_doc(doc_path=file_path, doc_id=id)
indexer.setup_corpus_index()
app.run(debug=True)
| en | 0.476402 | #!/usr/bin/env python3 # transform glob patterns to regular expressions | 2.152947 | 2 |
Alignment/MuonAlignment/test/MuonGeometryArrange.py | malbouis/cmssw | 0 | 6622281 | <gh_stars>0
import FWCore.ParameterSet.Config as cms
process =cms.Process("TEST")
#Ideal geometry
process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi")
process.load('Configuration.Geometry.GeometryExtended2021_cff')
process.load("Geometry.MuonNumbering.muonNumberingInitialization_cfi")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, "auto:phase1_2021_design")
import Geometry.DTGeometryBuilder.dtGeometryDB_cfi
import Geometry.CSCGeometryBuilder.cscGeometryDB_cfi
import Geometry.GEMGeometryBuilder.gemGeometryDB_cfi
process.DTGeometryIdeal = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone()
process.DTGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal'
process.DTGeometryIdeal.applyAlignment = cms.bool(False)
process.CSCGeometryIdeal = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone()
process.CSCGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal'
process.CSCGeometryIdeal.applyAlignment = cms.bool(False)
process.GEMGeometryIdeal = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone()
process.GEMGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal'
process.GEMGeometryIdeal.applyAlignment = cms.bool(False)
process.DTGeometryMuonGeometryArrange1 = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone()
process.DTGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1'
process.DTGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False)
process.CSCGeometryMuonGeometryArrange1 = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone()
process.CSCGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1'
process.CSCGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False)
process.GEMGeometryMuonGeometryArrange1 = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone()
process.GEMGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1'
process.GEMGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False)
process.DTGeometryMuonGeometryArrange2 = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone()
process.DTGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2'
process.DTGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False)
process.CSCGeometryMuonGeometryArrange2 = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone()
process.CSCGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2'
process.CSCGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False)
process.GEMGeometryMuonGeometryArrange2 = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone()
process.GEMGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2'
process.GEMGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False)
process.DTGeometryMuonGeometryArrange2a = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone()
process.DTGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a'
process.DTGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False)
process.CSCGeometryMuonGeometryArrange2a = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone()
process.CSCGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a'
process.CSCGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False)
process.GEMGeometryMuonGeometryArrange2a = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone()
process.GEMGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a'
process.GEMGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False)
process.MessageLogger = cms.Service("MessageLogger",
cerr = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
),
files = cms.untracked.PSet(
info_txt = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
)
)
)
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
# Full configuration for Muon Geometry Comparison Tool
#process.MuonGeometryCompare = cms.EDFilter("MuonGeometryArrange",
process.MuonGeometryCompare = cms.EDAnalyzer("MuonGeometryArrange",
outputFile = cms.untracked.string('output.root'),
detIdFlag = cms.untracked.bool(False),
detIdFlagFile = cms.untracked.string('blah.txt'),
weightById = cms.untracked.bool(False),
levels = cms.untracked.vstring('Det'),
weightBy = cms.untracked.string('SELF'),
weightByIdFile = cms.untracked.string('blah2.txt'),
treeName = cms.untracked.string('alignTree'),
# Root input files are not used yet.
inputROOTFile1 = cms.untracked.string('IDEAL'),
inputROOTFile2 = cms.untracked.string('idealmuon2.root'),
# Geometries are read from xml files
# inputXMLCurrent = cms.untracked.string('B.xml'),
# inputXMLCurrent = cms.untracked.string('A.xml'),
# inputXMLCurrent = cms.untracked.string('moveRing.xml'),
# inputXMLCurrent = cms.untracked.string('movedRing.xml'),
# inputXMLCurrent = cms.untracked.string('fiddleMuon.xml'),
# inputXMLCurrent = cms.untracked.string('fiddle2Muon.xml'),
inputXMLCurrent = cms.untracked.string('fiddle3Muon.xml'),
inputXMLReference = cms.untracked.string('idealMuon.xml'),
# A few defaults. You pick.
endcapNumber = cms.untracked.int32(2),
stationNumber = cms.untracked.int32(3),
ringNumber = cms.untracked.int32(2)
)
process.p = cms.Path( process.MuonGeometryCompare )
| import FWCore.ParameterSet.Config as cms
process =cms.Process("TEST")
#Ideal geometry
process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi")
process.load('Configuration.Geometry.GeometryExtended2021_cff')
process.load("Geometry.MuonNumbering.muonNumberingInitialization_cfi")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, "auto:phase1_2021_design")
import Geometry.DTGeometryBuilder.dtGeometryDB_cfi
import Geometry.CSCGeometryBuilder.cscGeometryDB_cfi
import Geometry.GEMGeometryBuilder.gemGeometryDB_cfi
process.DTGeometryIdeal = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone()
process.DTGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal'
process.DTGeometryIdeal.applyAlignment = cms.bool(False)
process.CSCGeometryIdeal = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone()
process.CSCGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal'
process.CSCGeometryIdeal.applyAlignment = cms.bool(False)
process.GEMGeometryIdeal = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone()
process.GEMGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal'
process.GEMGeometryIdeal.applyAlignment = cms.bool(False)
process.DTGeometryMuonGeometryArrange1 = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone()
process.DTGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1'
process.DTGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False)
process.CSCGeometryMuonGeometryArrange1 = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone()
process.CSCGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1'
process.CSCGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False)
process.GEMGeometryMuonGeometryArrange1 = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone()
process.GEMGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1'
process.GEMGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False)
process.DTGeometryMuonGeometryArrange2 = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone()
process.DTGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2'
process.DTGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False)
process.CSCGeometryMuonGeometryArrange2 = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone()
process.CSCGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2'
process.CSCGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False)
process.GEMGeometryMuonGeometryArrange2 = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone()
process.GEMGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2'
process.GEMGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False)
process.DTGeometryMuonGeometryArrange2a = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone()
process.DTGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a'
process.DTGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False)
process.CSCGeometryMuonGeometryArrange2a = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone()
process.CSCGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a'
process.CSCGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False)
process.GEMGeometryMuonGeometryArrange2a = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone()
process.GEMGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a'
process.GEMGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False)
process.MessageLogger = cms.Service("MessageLogger",
cerr = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
),
files = cms.untracked.PSet(
info_txt = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
)
)
)
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
# Full configuration for Muon Geometry Comparison Tool
#process.MuonGeometryCompare = cms.EDFilter("MuonGeometryArrange",
process.MuonGeometryCompare = cms.EDAnalyzer("MuonGeometryArrange",
outputFile = cms.untracked.string('output.root'),
detIdFlag = cms.untracked.bool(False),
detIdFlagFile = cms.untracked.string('blah.txt'),
weightById = cms.untracked.bool(False),
levels = cms.untracked.vstring('Det'),
weightBy = cms.untracked.string('SELF'),
weightByIdFile = cms.untracked.string('blah2.txt'),
treeName = cms.untracked.string('alignTree'),
# Root input files are not used yet.
inputROOTFile1 = cms.untracked.string('IDEAL'),
inputROOTFile2 = cms.untracked.string('idealmuon2.root'),
# Geometries are read from xml files
# inputXMLCurrent = cms.untracked.string('B.xml'),
# inputXMLCurrent = cms.untracked.string('A.xml'),
# inputXMLCurrent = cms.untracked.string('moveRing.xml'),
# inputXMLCurrent = cms.untracked.string('movedRing.xml'),
# inputXMLCurrent = cms.untracked.string('fiddleMuon.xml'),
# inputXMLCurrent = cms.untracked.string('fiddle2Muon.xml'),
inputXMLCurrent = cms.untracked.string('fiddle3Muon.xml'),
inputXMLReference = cms.untracked.string('idealMuon.xml'),
# A few defaults. You pick.
endcapNumber = cms.untracked.int32(2),
stationNumber = cms.untracked.int32(3),
ringNumber = cms.untracked.int32(2)
)
process.p = cms.Path( process.MuonGeometryCompare ) | en | 0.378811 | #Ideal geometry # Full configuration for Muon Geometry Comparison Tool #process.MuonGeometryCompare = cms.EDFilter("MuonGeometryArrange", # Root input files are not used yet. # Geometries are read from xml files # inputXMLCurrent = cms.untracked.string('B.xml'), # inputXMLCurrent = cms.untracked.string('A.xml'), # inputXMLCurrent = cms.untracked.string('moveRing.xml'), # inputXMLCurrent = cms.untracked.string('movedRing.xml'), # inputXMLCurrent = cms.untracked.string('fiddleMuon.xml'), # inputXMLCurrent = cms.untracked.string('fiddle2Muon.xml'), # A few defaults. You pick. | 1.247091 | 1 |
statzcw/zvariance.py | ZCW-Data1dot2/python-basic-stats-derek-johns | 0 | 6622282 | from statzcw import zmean, zcount
def variance(in_list):
"""
Finds variance of given list
:param in_list: list of values
:return: float rounded to 5 decimal places
"""
n = zcount.count(in_list)
mean = zmean.mean(in_list)
d = [(x - mean) ** 2 for x in in_list]
v = sum(d) / (n - 1)
return round(v, 5) | from statzcw import zmean, zcount
def variance(in_list):
"""
Finds variance of given list
:param in_list: list of values
:return: float rounded to 5 decimal places
"""
n = zcount.count(in_list)
mean = zmean.mean(in_list)
d = [(x - mean) ** 2 for x in in_list]
v = sum(d) / (n - 1)
return round(v, 5) | en | 0.400596 | Finds variance of given list :param in_list: list of values :return: float rounded to 5 decimal places | 3.45738 | 3 |
vad_service/src/VadService.py | blues-lab/passive-listening-prototype | 0 | 6622283 | import tempfile
from pathlib import Path
import grpc
from sclog import getLogger
from plp.proto import Vad_pb2
from plp.proto import Vad_pb2_grpc
from vad import file_has_speech
logger = getLogger(__name__)
CLASSIFICATION_SERVICE_PORT = 50059
def save_bytes_as_tmp_wav_file(b: bytes) -> str:
"""
Save the given bytes to a file in a new temporary directory and return that file's path
"""
fd, path = tempfile.mkstemp(suffix=".wav")
with open(fd, "wb") as f:
f.write(b)
logger.debug("saved bytes to temporary file %s", path)
return path
class VadService(Vad_pb2_grpc.VadServiceServicer):
def CheckAudioForSpeech(self, request, context):
logger.debug("received request %i", request.id)
tmp_file = Path(save_bytes_as_tmp_wav_file(request.audio))
result = file_has_speech(str(tmp_file))
tmp_file.unlink()
return Vad_pb2.VadResponse(
id=request.id,
isSpeech=result,
) | import tempfile
from pathlib import Path
import grpc
from sclog import getLogger
from plp.proto import Vad_pb2
from plp.proto import Vad_pb2_grpc
from vad import file_has_speech
logger = getLogger(__name__)
CLASSIFICATION_SERVICE_PORT = 50059
def save_bytes_as_tmp_wav_file(b: bytes) -> str:
"""
Save the given bytes to a file in a new temporary directory and return that file's path
"""
fd, path = tempfile.mkstemp(suffix=".wav")
with open(fd, "wb") as f:
f.write(b)
logger.debug("saved bytes to temporary file %s", path)
return path
class VadService(Vad_pb2_grpc.VadServiceServicer):
def CheckAudioForSpeech(self, request, context):
logger.debug("received request %i", request.id)
tmp_file = Path(save_bytes_as_tmp_wav_file(request.audio))
result = file_has_speech(str(tmp_file))
tmp_file.unlink()
return Vad_pb2.VadResponse(
id=request.id,
isSpeech=result,
) | en | 0.861384 | Save the given bytes to a file in a new temporary directory and return that file's path | 2.664756 | 3 |
models/Account.py | devArtoria/Python-BlockChain | 0 | 6622284 | from mongoengine import *
import datetime
connect('PyCoin')
class Accounts(Document):
account_id = StringField(
required=True
)
timestamp = DateTimeField(
default=datetime.datetime.now,
required=True
)
transactions = ListField(
)
amount = LongField(
default=0,
required=True
)
| from mongoengine import *
import datetime
connect('PyCoin')
class Accounts(Document):
account_id = StringField(
required=True
)
timestamp = DateTimeField(
default=datetime.datetime.now,
required=True
)
transactions = ListField(
)
amount = LongField(
default=0,
required=True
)
| none | 1 | 2.496771 | 2 | |
dator.py | bismuthfoundation/stator | 3 | 6622285 | <gh_stars>1-10
import json
from bismuthclient.rpcconnections import Connection
from diff_simple import difficulty
import psutil
class Socket:
def __init__(self):
self.connect()
def connect(self):
try:
self.connection = Connection(("127.0.0.1", 5658))
except:
raise
def get_txid(self, txid):
self.connect()
responded = False
while not responded:
try:
self.connection._send("api_gettransaction")
self.connection._send(txid)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_address(self, address):
responded = False
while not responded:
try:
self.connection._send("api_getaddressrange")
self.connection._send(address)
self.connection._send(0)
self.connection._send(100)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_status(self):
responded = False
while not responded:
try:
self.connection._send("statusjson")
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_blockfromhash(self, hash):
responded = False
while not responded:
try:
self.connection._send("api_getblockfromhash")
self.connection._send(hash)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_blockfromheight(self, height):
responded = False
while not responded:
try:
self.connection._send("api_getblockfromheight")
self.connection._send(height)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_getblockrange(self, block, limit):
responded = False
while not responded:
try:
self.connection._send("api_getblockrange")
self.connection._send(block)
self.connection._send(limit)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
class Status:
def refresh(self, socket):
self.status = socket.get_status()
# non-chartable instants
self.protocolversion = self.status['protocolversion']
self.address = self.status['address']
self.testnet = self.status['testnet']
self.timeoffset = self.status['timeoffset']
self.connections_list = self.status['connections_list']
self.uptime = self.status['uptime']
self.server_timestamp = self.status['server_timestamp']
# chartable instants
self.connections = self.status['connections']
self.threads = self.status['threads']
self.consensus = self.status['consensus']
self.consensus_percent = self.status['consensus_percent']
# non-instants
self.difficulty = self.status['difficulty']
self.blocks = self.status['blocks']
return self.status
class History:
"""saves status calls and the last block range call"""
def __init__(self):
self.blocks = []
self.stata = []
self.diffs = []
def truncate(self):
if len(self.stata) >= 50:
self.stata = self.stata[-50:]
if len(self.diffs) >= 50:
self.diffs = self.diffs[50:]
class DiffCalculator:
@staticmethod
def calculate(diff_blocks, diff_blocks_minus_1440, block: str, block_minus_1: str, block_minus_1440: str):
try:
print("Calculating difficulty")
print("diff_blocks", diff_blocks)
last_block_timestamp = diff_blocks[block]["mining_tx"]["timestamp"]
block_minus_1_timestamp = diff_blocks[block_minus_1]["mining_tx"]["timestamp"]
block_minus_1_difficulty = diff_blocks[block_minus_1]["mining_tx"]["difficulty"]
block_minus_1441_timestamp = diff_blocks_minus_1440[block_minus_1440]["mining_tx"]["difficulty"]
diff = difficulty(float(last_block_timestamp),
float(block_minus_1_timestamp),
float(block_minus_1_difficulty),
float(block_minus_1441_timestamp))
return {block: diff}
except Exception as e:
print(f"issue with {e}")
raise
class Updater:
def __init__(self):
self.status = Status()
self.history = History()
self.last_block = 0
def update(self):
try:
self.socket = Socket()
new_data = self.status.refresh(self.socket)
local_data = {}
local_data["memory"] = dict(psutil.virtual_memory()._asdict())["percent"]
local_data["cpu_usage"] = psutil.cpu_percent(3)
new_data["local_data"] = local_data
self.history.stata.append([new_data])
self.last_block = new_data["blocks"]
self.history.blocks = json.loads(self.socket.get_getblockrange(self.status.blocks - 50, 50))
print(self.history.blocks) # last block
self.history.truncate()
for number in range(-50, 0):
# difficulty
diff_blocks = json.loads(self.socket.get_getblockrange(self.status.blocks + number, 2)) # number is negative
diff_blocks_minus_1440 = json.loads(self.socket.get_getblockrange(self.status.blocks - 1440 + number, 1)) # number is negative
self.history.diffs.append(DiffCalculator.calculate(diff_blocks, diff_blocks_minus_1440,
str(self.status.blocks + number + 1),
str(self.status.blocks + number),
str(self.status.blocks - 1440 + number)))
# /difficulty
print(self.history.blocks)
print(self.history.diffs)
except Exception as e:
print(f"An error occured during update, skipping ({e})")
if __name__ == "__main__":
updater = Updater()
| import json
from bismuthclient.rpcconnections import Connection
from diff_simple import difficulty
import psutil
class Socket:
def __init__(self):
self.connect()
def connect(self):
try:
self.connection = Connection(("127.0.0.1", 5658))
except:
raise
def get_txid(self, txid):
self.connect()
responded = False
while not responded:
try:
self.connection._send("api_gettransaction")
self.connection._send(txid)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_address(self, address):
responded = False
while not responded:
try:
self.connection._send("api_getaddressrange")
self.connection._send(address)
self.connection._send(0)
self.connection._send(100)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_status(self):
responded = False
while not responded:
try:
self.connection._send("statusjson")
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_blockfromhash(self, hash):
responded = False
while not responded:
try:
self.connection._send("api_getblockfromhash")
self.connection._send(hash)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_blockfromheight(self, height):
responded = False
while not responded:
try:
self.connection._send("api_getblockfromheight")
self.connection._send(height)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
def get_getblockrange(self, block, limit):
responded = False
while not responded:
try:
self.connection._send("api_getblockrange")
self.connection._send(block)
self.connection._send(limit)
reply = self.connection._receive()
if not reply == "*":
responded = True
return reply
except Exception as e:
print(f"Error: {e}")
self.connect()
class Status:
def refresh(self, socket):
self.status = socket.get_status()
# non-chartable instants
self.protocolversion = self.status['protocolversion']
self.address = self.status['address']
self.testnet = self.status['testnet']
self.timeoffset = self.status['timeoffset']
self.connections_list = self.status['connections_list']
self.uptime = self.status['uptime']
self.server_timestamp = self.status['server_timestamp']
# chartable instants
self.connections = self.status['connections']
self.threads = self.status['threads']
self.consensus = self.status['consensus']
self.consensus_percent = self.status['consensus_percent']
# non-instants
self.difficulty = self.status['difficulty']
self.blocks = self.status['blocks']
return self.status
class History:
"""saves status calls and the last block range call"""
def __init__(self):
self.blocks = []
self.stata = []
self.diffs = []
def truncate(self):
if len(self.stata) >= 50:
self.stata = self.stata[-50:]
if len(self.diffs) >= 50:
self.diffs = self.diffs[50:]
class DiffCalculator:
@staticmethod
def calculate(diff_blocks, diff_blocks_minus_1440, block: str, block_minus_1: str, block_minus_1440: str):
try:
print("Calculating difficulty")
print("diff_blocks", diff_blocks)
last_block_timestamp = diff_blocks[block]["mining_tx"]["timestamp"]
block_minus_1_timestamp = diff_blocks[block_minus_1]["mining_tx"]["timestamp"]
block_minus_1_difficulty = diff_blocks[block_minus_1]["mining_tx"]["difficulty"]
block_minus_1441_timestamp = diff_blocks_minus_1440[block_minus_1440]["mining_tx"]["difficulty"]
diff = difficulty(float(last_block_timestamp),
float(block_minus_1_timestamp),
float(block_minus_1_difficulty),
float(block_minus_1441_timestamp))
return {block: diff}
except Exception as e:
print(f"issue with {e}")
raise
class Updater:
def __init__(self):
self.status = Status()
self.history = History()
self.last_block = 0
def update(self):
try:
self.socket = Socket()
new_data = self.status.refresh(self.socket)
local_data = {}
local_data["memory"] = dict(psutil.virtual_memory()._asdict())["percent"]
local_data["cpu_usage"] = psutil.cpu_percent(3)
new_data["local_data"] = local_data
self.history.stata.append([new_data])
self.last_block = new_data["blocks"]
self.history.blocks = json.loads(self.socket.get_getblockrange(self.status.blocks - 50, 50))
print(self.history.blocks) # last block
self.history.truncate()
for number in range(-50, 0):
# difficulty
diff_blocks = json.loads(self.socket.get_getblockrange(self.status.blocks + number, 2)) # number is negative
diff_blocks_minus_1440 = json.loads(self.socket.get_getblockrange(self.status.blocks - 1440 + number, 1)) # number is negative
self.history.diffs.append(DiffCalculator.calculate(diff_blocks, diff_blocks_minus_1440,
str(self.status.blocks + number + 1),
str(self.status.blocks + number),
str(self.status.blocks - 1440 + number)))
# /difficulty
print(self.history.blocks)
print(self.history.diffs)
except Exception as e:
print(f"An error occured during update, skipping ({e})")
if __name__ == "__main__":
updater = Updater() | en | 0.787136 | # non-chartable instants # chartable instants # non-instants saves status calls and the last block range call # last block # difficulty # number is negative # number is negative # /difficulty | 2.887814 | 3 |
tests/test_multirev_solvers.py | jorgepiloto/lamberthub | 10 | 6622286 | <filename>tests/test_multirev_solvers.py
""" A collection of tests only for multi-revolution solvers """
import numpy as np
import pytest
from numpy.testing import assert_allclose
from lamberthub import MULTI_REV_SOLVERS
TABLE_OF_TRANSFERS = {
"M1_prograde_high": [
np.array([0.50335770, 0.61869408, -1.57176904]), # [km / s]
np.array([-4.18334626, -1.13262727, 6.13307091]), # [km / s]
],
"M1_prograde_low": [
np.array([-2.45759553, 1.16945801, 0.43161258]), # [km / s]
np.array([-5.53841370, 0.01822220, 5.49641054]), # [km / s]
],
"M1_retrograde_high": [
np.array([1.33645655, -0.94654565, 0.30211211]), # [km / s]
np.array([4.93628678, 0.39863416, -5.61593092]), # [km / s]
],
"M1_retrograde_low": [
np.array([-1.38861608, -0.47836611, 2.21280154]), # [km / s]
np.array([3.92901545, 1.50871943, -6.52926969]), # [km / s]
],
}
"""
Directly taken from example 1 from The Superior Lambert Algorithm (Der
Astrodynamics), by <NAME>, see https://amostech.com/TechnicalPapers/2011/Poster/DER.pdf
"""
@pytest.mark.parametrize("solver", MULTI_REV_SOLVERS)
@pytest.mark.parametrize("case", TABLE_OF_TRANSFERS)
def test_multirev_case(solver, case):
# Initial conditions
mu_earth = 3.986004418e5 # [km ** 3 / s ** 2]
r1 = np.array([22592.145603, -1599.915239, -19783.950506]) # [km]
r2 = np.array([1922.067697, 4054.157051, -8925.727465]) # [km]
tof = 36000 # [s]
# Unpack problem conditions
M, sense, path = case.split("_")
# Convert proper type
M = int(M[-1])
sense = True if sense == "prograde" else False
path = True if path == "low" else False
# Solve the problem
v1, v2 = solver(mu_earth, r1, r2, tof, M=M, prograde=sense, low_path=path)
# Expected final results
expected_v1, expected_v2 = TABLE_OF_TRANSFERS[case]
# Assert the results
assert_allclose(v1, expected_v1, rtol=5e-6)
assert_allclose(v2, expected_v2, rtol=5e-6)
@pytest.mark.parametrize("solver", MULTI_REV_SOLVERS)
def test_exception_try_lower_M(solver):
""" Test that solver does not find any solution for particular input """
# Initial conditions
mu_earth = 3.986004418e5 # [km ** 3 / s ** 2]
r1 = np.array([22592.145603, -1599.915239, -19783.950506]) # [km]
r2 = np.array([1922.067697, 4054.157051, -8925.727465]) # [km]
tof = 5 * 3600 # [s]
with pytest.raises(ValueError) as excinfo:
solver(mu_earth, r1, r2, tof, M=1)
assert "ValueError: No feasible solution, try lower M!" in excinfo.exconly()
| <filename>tests/test_multirev_solvers.py
""" A collection of tests only for multi-revolution solvers """
import numpy as np
import pytest
from numpy.testing import assert_allclose
from lamberthub import MULTI_REV_SOLVERS
TABLE_OF_TRANSFERS = {
"M1_prograde_high": [
np.array([0.50335770, 0.61869408, -1.57176904]), # [km / s]
np.array([-4.18334626, -1.13262727, 6.13307091]), # [km / s]
],
"M1_prograde_low": [
np.array([-2.45759553, 1.16945801, 0.43161258]), # [km / s]
np.array([-5.53841370, 0.01822220, 5.49641054]), # [km / s]
],
"M1_retrograde_high": [
np.array([1.33645655, -0.94654565, 0.30211211]), # [km / s]
np.array([4.93628678, 0.39863416, -5.61593092]), # [km / s]
],
"M1_retrograde_low": [
np.array([-1.38861608, -0.47836611, 2.21280154]), # [km / s]
np.array([3.92901545, 1.50871943, -6.52926969]), # [km / s]
],
}
"""
Directly taken from example 1 from The Superior Lambert Algorithm (Der
Astrodynamics), by <NAME>, see https://amostech.com/TechnicalPapers/2011/Poster/DER.pdf
"""
@pytest.mark.parametrize("solver", MULTI_REV_SOLVERS)
@pytest.mark.parametrize("case", TABLE_OF_TRANSFERS)
def test_multirev_case(solver, case):
# Initial conditions
mu_earth = 3.986004418e5 # [km ** 3 / s ** 2]
r1 = np.array([22592.145603, -1599.915239, -19783.950506]) # [km]
r2 = np.array([1922.067697, 4054.157051, -8925.727465]) # [km]
tof = 36000 # [s]
# Unpack problem conditions
M, sense, path = case.split("_")
# Convert proper type
M = int(M[-1])
sense = True if sense == "prograde" else False
path = True if path == "low" else False
# Solve the problem
v1, v2 = solver(mu_earth, r1, r2, tof, M=M, prograde=sense, low_path=path)
# Expected final results
expected_v1, expected_v2 = TABLE_OF_TRANSFERS[case]
# Assert the results
assert_allclose(v1, expected_v1, rtol=5e-6)
assert_allclose(v2, expected_v2, rtol=5e-6)
@pytest.mark.parametrize("solver", MULTI_REV_SOLVERS)
def test_exception_try_lower_M(solver):
""" Test that solver does not find any solution for particular input """
# Initial conditions
mu_earth = 3.986004418e5 # [km ** 3 / s ** 2]
r1 = np.array([22592.145603, -1599.915239, -19783.950506]) # [km]
r2 = np.array([1922.067697, 4054.157051, -8925.727465]) # [km]
tof = 5 * 3600 # [s]
with pytest.raises(ValueError) as excinfo:
solver(mu_earth, r1, r2, tof, M=1)
assert "ValueError: No feasible solution, try lower M!" in excinfo.exconly()
| en | 0.809953 | A collection of tests only for multi-revolution solvers # [km / s] # [km / s] # [km / s] # [km / s] # [km / s] # [km / s] # [km / s] # [km / s] Directly taken from example 1 from The Superior Lambert Algorithm (Der Astrodynamics), by <NAME>, see https://amostech.com/TechnicalPapers/2011/Poster/DER.pdf # Initial conditions # [km ** 3 / s ** 2] # [km] # [km] # [s] # Unpack problem conditions # Convert proper type # Solve the problem # Expected final results # Assert the results Test that solver does not find any solution for particular input # Initial conditions # [km ** 3 / s ** 2] # [km] # [km] # [s] | 2.071424 | 2 |
venv/lib/python3.7/sre_compile.py | OseiasBeu/PyECom | 1 | 6622287 | <reponame>OseiasBeu/PyECom
/home/oseiasbeu/anaconda3/lib/python3.7/sre_compile.py | /home/oseiasbeu/anaconda3/lib/python3.7/sre_compile.py | none | 1 | 0.910978 | 1 | |
Udemy/Secao5/aula134/aula133.py | rafaelgama/Curso_Python | 1 | 6622288 | <reponame>rafaelgama/Curso_Python<gh_stars>1-10
# Web Scraping com Python.
# instalar os pacotes: pip install requests e beautifulsoup4
import requests # parar fazer as requisições
from bs4 import BeautifulSoup # Para permitir manipular o html.
url = 'https://pt.stackoverflow.com/questions/tagged/python'
# pegar a respota do request
response = requests.get(url)
#print(response.text) # mostra o html da pagina
# Analisar o HTML e disponibilizar o Objeto
html = BeautifulSoup(response.text, 'html.parser')
# select() = seletor CSS do BeautifulSoup
for pergunta in html.select('.question-summary'):
# select_one() = seletor CSS do BeautifulSoup para um só
titulo = pergunta.select_one('.question-hyperlink')
data = pergunta.select_one('.relativetime')
votos = pergunta.select_one('.vote-count-post')
# pega somente os textos da tag do CSS ex: "objeto".text
print(titulo.text, data.text, votos.text, sep='\t')
| # Web Scraping com Python.
# instalar os pacotes: pip install requests e beautifulsoup4
import requests # parar fazer as requisições
from bs4 import BeautifulSoup # Para permitir manipular o html.
url = 'https://pt.stackoverflow.com/questions/tagged/python'
# pegar a respota do request
response = requests.get(url)
#print(response.text) # mostra o html da pagina
# Analisar o HTML e disponibilizar o Objeto
html = BeautifulSoup(response.text, 'html.parser')
# select() = seletor CSS do BeautifulSoup
for pergunta in html.select('.question-summary'):
# select_one() = seletor CSS do BeautifulSoup para um só
titulo = pergunta.select_one('.question-hyperlink')
data = pergunta.select_one('.relativetime')
votos = pergunta.select_one('.vote-count-post')
# pega somente os textos da tag do CSS ex: "objeto".text
print(titulo.text, data.text, votos.text, sep='\t') | pt | 0.694303 | # Web Scraping com Python. # instalar os pacotes: pip install requests e beautifulsoup4 # parar fazer as requisições # Para permitir manipular o html. # pegar a respota do request #print(response.text) # mostra o html da pagina # Analisar o HTML e disponibilizar o Objeto # select() = seletor CSS do BeautifulSoup # select_one() = seletor CSS do BeautifulSoup para um só # pega somente os textos da tag do CSS ex: "objeto".text | 3.746795 | 4 |
Concept/Sand_Box.py | Ahmad-Fahad/Python | 0 | 6622289 |
for i in range(2,150, 4):
print("{}-{}, ". format(i, i+1), end='' )
print()
for i in range(4,150, 4):
print("{}-{}, ". format(i, i+1), end='' )
"""
lst_1 = [1,2,3]
lst_2 = [9,4,5,6]
for i in range(len(lst_2)):
if lst_2[i]>5:
lst_2[i]=0
print(lst_2)
lst_3 = [lst_1]+[lst_2]
print(list(zip(*lst_3)))
A = [1,2,3]
B = [6,5,4]
C = [7,8,9]
X = [A] + [B] + [C]
print(list(zip(*X)))
t = 2
m = []
while t<0:
t-=1
z = [float(i) for i in input().split()]
m += z
print(m)
st = {'rr',2,3,4,5}
st.add(8)
print(st)
lst = [5,5,5,5,5,5,5]
ss = set(lst)
print(ss)
n = input()
st = set(int(i) for i in input().split())
print(sum(st))
for i in range(1, int(input())+1):
print(int((10**i -1)/9)**2)
x = 1
for i in range(int(input())):
print(x**2)
x = (x*10)+1
n = int(input())
x = '1'
for i in range(n):
output = int(x)**2
print(output)
x += '1'
"""
|
for i in range(2,150, 4):
print("{}-{}, ". format(i, i+1), end='' )
print()
for i in range(4,150, 4):
print("{}-{}, ". format(i, i+1), end='' )
"""
lst_1 = [1,2,3]
lst_2 = [9,4,5,6]
for i in range(len(lst_2)):
if lst_2[i]>5:
lst_2[i]=0
print(lst_2)
lst_3 = [lst_1]+[lst_2]
print(list(zip(*lst_3)))
A = [1,2,3]
B = [6,5,4]
C = [7,8,9]
X = [A] + [B] + [C]
print(list(zip(*X)))
t = 2
m = []
while t<0:
t-=1
z = [float(i) for i in input().split()]
m += z
print(m)
st = {'rr',2,3,4,5}
st.add(8)
print(st)
lst = [5,5,5,5,5,5,5]
ss = set(lst)
print(ss)
n = input()
st = set(int(i) for i in input().split())
print(sum(st))
for i in range(1, int(input())+1):
print(int((10**i -1)/9)**2)
x = 1
for i in range(int(input())):
print(x**2)
x = (x*10)+1
n = int(input())
x = '1'
for i in range(n):
output = int(x)**2
print(output)
x += '1'
"""
| en | 0.438117 | lst_1 = [1,2,3] lst_2 = [9,4,5,6] for i in range(len(lst_2)): if lst_2[i]>5: lst_2[i]=0 print(lst_2) lst_3 = [lst_1]+[lst_2] print(list(zip(*lst_3))) A = [1,2,3] B = [6,5,4] C = [7,8,9] X = [A] + [B] + [C] print(list(zip(*X))) t = 2 m = [] while t<0: t-=1 z = [float(i) for i in input().split()] m += z print(m) st = {'rr',2,3,4,5} st.add(8) print(st) lst = [5,5,5,5,5,5,5] ss = set(lst) print(ss) n = input() st = set(int(i) for i in input().split()) print(sum(st)) for i in range(1, int(input())+1): print(int((10**i -1)/9)**2) x = 1 for i in range(int(input())): print(x**2) x = (x*10)+1 n = int(input()) x = '1' for i in range(n): output = int(x)**2 print(output) x += '1' | 3.291732 | 3 |
scripts_pipeline/feature_extraction/Hatebase.py | paulafortuna/HatEval_public | 1 | 6622290 |
from scripts_pipeline.Dataset import Dataset
from scripts_pipeline.feature_extraction.FeatureExtraction import Parameters, FeatureExtraction
from scripts_pipeline.PathsManagement import PathsManagement as Paths
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.tokenize import RegexpTokenizer
import re
class HatebaseParameters(Parameters):
"""
Parameters to be used in the Hatebase feature extraction.
"""
def __init__(self, feature_name, dataset_name, language):
Parameters.__init__(self, feature_name, dataset_name)
self.language = language
class Hatebase(FeatureExtraction):
"""
Implements methods for Hatebase feature extraction.
It is a Child Class of FeatureExtraction, and it can be instantiated because it implements
conduct_feature_extraction method.
"""
def __init__(self, parameters):
"""
Calls the parent class FeatureExtraction initiator.
:param parameters: object of the HatebaseParameters.
"""
FeatureExtraction.__init__(self, parameters)
self.hateful_words = []
self.hate_topic_words = []
def conduct_feature_extraction_train_test(self, original_dataset):
"""
Assures the feature extraction occurs in the right order of steps.
Implementation of the abstract method from the parent class.
:param original_dataset:the original data to be extracted
"""
self.hateful_words = self.read_list_hateful_words()
self.hate_topic_words = self.read_list_hate_topic_words()
features_dataset = Dataset()
features_dataset.set_ids_and_y(original_dataset)
features_dataset.x_train = self.extract_hate_words_and_topic(original_dataset.x_train)
features_dataset.x_val = self.extract_hate_words_and_topic(original_dataset.x_val)
self.save_features_to_file(features_dataset)
def conduct_feature_extraction_new_data(self, new_data, new_data_name, experiment_name):
"""
Abstract method that allows all the feature extraction procedures to be used in a list and called
with the same method.
:param new_data: the new data for being classified
"""
features_dataset = Dataset()
features_dataset.x_val = self.extract_hate_words_and_topic(new_data.x_val)
features_dataset.x_val_id = new_data.x_val_id
self.parameters.dataset_name = new_data_name
self.save_features_to_file(features_dataset)
def extract_hate_words_and_topic(self, x_data):
"""
Method that really implements the feature extraction procedure.
It counts the hatebase words in every message.
Two types of words are used: the hateful_words given by hate base. Another set of list is counted.
This is the hate_topic_words and corresponds to the words used in hatebase to describe each word without being offensive.
:param x_data: texts columns
:return: the extracted features
"""
res = pd.DataFrame({
'hateful_words': [self.count_frequencies(instance, self.hateful_words) for instance in x_data],
'hate_topic_words': [self.count_frequencies(instance, self.hate_topic_words) for instance in x_data]
})
return res
def count_frequencies(self, instance, words):
"""
Method that really implements the feature extraction procedure.
and counts a set of words in a message.
:param instance: string with the text of the message
:param words: words to chack if they are present in the instance
:return: the total of counts from words found in the instance
"""
total = 0
for word in words:
if ' ' in word and word.lower() in instance.lower():
total += 1
else:
if word.lower() in instance.lower().split():
total += 1
return total
def read_list_hateful_words(self):
"""
Method that reads from files the list of hateful words.
:return: the list of words
"""
hatebase = pd.read_csv(Paths.file_hatebase)
hatebase = hatebase.loc[hatebase['language'] == self.parameters.language]
s = hatebase['term']
p = hatebase.loc[hatebase['plural_of'].notnull()]['plural_of']
words = s.append(p)
stop_words = set(stopwords.words("english"))
filtered_words = list(filter(lambda word: word.lower() not in stop_words, words))
return list(set(filtered_words))
def read_list_hate_topic_words(self):
"""
Method that reads from files the list of hateful related words.
:return: the list of words
"""
hatebase = pd.read_csv(Paths.file_hatebase)
hatebase = hatebase.loc[hatebase['language'] == self.parameters.language]
words = hatebase['hateful_meaning']
words = ' '.join(words)
words = re.sub(r'\b\w{1,1}\b', '', words) # remove words with 1 digit
words = re.sub(r'\w*\d\w*', '', words).strip() # remove words with digits
#TODO generalize for other languages
stop_words = set(stopwords.words("english"))
words = words.lower()
tokenizer = RegexpTokenizer(r'\w+')
word_tokens = tokenizer.tokenize(words)
filtered_words = list(filter(lambda word: word not in stop_words, word_tokens))
return list(set(filtered_words))
|
from scripts_pipeline.Dataset import Dataset
from scripts_pipeline.feature_extraction.FeatureExtraction import Parameters, FeatureExtraction
from scripts_pipeline.PathsManagement import PathsManagement as Paths
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.tokenize import RegexpTokenizer
import re
class HatebaseParameters(Parameters):
"""
Parameters to be used in the Hatebase feature extraction.
"""
def __init__(self, feature_name, dataset_name, language):
Parameters.__init__(self, feature_name, dataset_name)
self.language = language
class Hatebase(FeatureExtraction):
"""
Implements methods for Hatebase feature extraction.
It is a Child Class of FeatureExtraction, and it can be instantiated because it implements
conduct_feature_extraction method.
"""
def __init__(self, parameters):
"""
Calls the parent class FeatureExtraction initiator.
:param parameters: object of the HatebaseParameters.
"""
FeatureExtraction.__init__(self, parameters)
self.hateful_words = []
self.hate_topic_words = []
def conduct_feature_extraction_train_test(self, original_dataset):
"""
Assures the feature extraction occurs in the right order of steps.
Implementation of the abstract method from the parent class.
:param original_dataset:the original data to be extracted
"""
self.hateful_words = self.read_list_hateful_words()
self.hate_topic_words = self.read_list_hate_topic_words()
features_dataset = Dataset()
features_dataset.set_ids_and_y(original_dataset)
features_dataset.x_train = self.extract_hate_words_and_topic(original_dataset.x_train)
features_dataset.x_val = self.extract_hate_words_and_topic(original_dataset.x_val)
self.save_features_to_file(features_dataset)
def conduct_feature_extraction_new_data(self, new_data, new_data_name, experiment_name):
"""
Abstract method that allows all the feature extraction procedures to be used in a list and called
with the same method.
:param new_data: the new data for being classified
"""
features_dataset = Dataset()
features_dataset.x_val = self.extract_hate_words_and_topic(new_data.x_val)
features_dataset.x_val_id = new_data.x_val_id
self.parameters.dataset_name = new_data_name
self.save_features_to_file(features_dataset)
def extract_hate_words_and_topic(self, x_data):
"""
Method that really implements the feature extraction procedure.
It counts the hatebase words in every message.
Two types of words are used: the hateful_words given by hate base. Another set of list is counted.
This is the hate_topic_words and corresponds to the words used in hatebase to describe each word without being offensive.
:param x_data: texts columns
:return: the extracted features
"""
res = pd.DataFrame({
'hateful_words': [self.count_frequencies(instance, self.hateful_words) for instance in x_data],
'hate_topic_words': [self.count_frequencies(instance, self.hate_topic_words) for instance in x_data]
})
return res
def count_frequencies(self, instance, words):
"""
Method that really implements the feature extraction procedure.
and counts a set of words in a message.
:param instance: string with the text of the message
:param words: words to chack if they are present in the instance
:return: the total of counts from words found in the instance
"""
total = 0
for word in words:
if ' ' in word and word.lower() in instance.lower():
total += 1
else:
if word.lower() in instance.lower().split():
total += 1
return total
def read_list_hateful_words(self):
"""
Method that reads from files the list of hateful words.
:return: the list of words
"""
hatebase = pd.read_csv(Paths.file_hatebase)
hatebase = hatebase.loc[hatebase['language'] == self.parameters.language]
s = hatebase['term']
p = hatebase.loc[hatebase['plural_of'].notnull()]['plural_of']
words = s.append(p)
stop_words = set(stopwords.words("english"))
filtered_words = list(filter(lambda word: word.lower() not in stop_words, words))
return list(set(filtered_words))
def read_list_hate_topic_words(self):
"""
Method that reads from files the list of hateful related words.
:return: the list of words
"""
hatebase = pd.read_csv(Paths.file_hatebase)
hatebase = hatebase.loc[hatebase['language'] == self.parameters.language]
words = hatebase['hateful_meaning']
words = ' '.join(words)
words = re.sub(r'\b\w{1,1}\b', '', words) # remove words with 1 digit
words = re.sub(r'\w*\d\w*', '', words).strip() # remove words with digits
#TODO generalize for other languages
stop_words = set(stopwords.words("english"))
words = words.lower()
tokenizer = RegexpTokenizer(r'\w+')
word_tokens = tokenizer.tokenize(words)
filtered_words = list(filter(lambda word: word not in stop_words, word_tokens))
return list(set(filtered_words))
| en | 0.862563 | Parameters to be used in the Hatebase feature extraction. Implements methods for Hatebase feature extraction. It is a Child Class of FeatureExtraction, and it can be instantiated because it implements conduct_feature_extraction method. Calls the parent class FeatureExtraction initiator. :param parameters: object of the HatebaseParameters. Assures the feature extraction occurs in the right order of steps. Implementation of the abstract method from the parent class. :param original_dataset:the original data to be extracted Abstract method that allows all the feature extraction procedures to be used in a list and called with the same method. :param new_data: the new data for being classified Method that really implements the feature extraction procedure. It counts the hatebase words in every message. Two types of words are used: the hateful_words given by hate base. Another set of list is counted. This is the hate_topic_words and corresponds to the words used in hatebase to describe each word without being offensive. :param x_data: texts columns :return: the extracted features Method that really implements the feature extraction procedure. and counts a set of words in a message. :param instance: string with the text of the message :param words: words to chack if they are present in the instance :return: the total of counts from words found in the instance Method that reads from files the list of hateful words. :return: the list of words Method that reads from files the list of hateful related words. :return: the list of words # remove words with 1 digit # remove words with digits #TODO generalize for other languages | 2.869561 | 3 |
src/tests/__init__.py | francesco-p/FACIL | 243 | 6622291 | import os
import torch
import shutil
from main_incremental import main
import datasets.dataset_config as c
def run_main(args_line, result_dir='results_test', clean_run=False):
assert "--results-path" not in args_line
print('Staring dir:', os.getcwd())
if os.getcwd().endswith('tests'):
os.chdir('..')
elif os.getcwd().endswith('IL_Survey'):
os.chdir('src')
elif os.getcwd().endswith('src'):
print('CWD is OK.')
print('Test CWD:', os.getcwd())
test_results_path = os.getcwd() + f"/../{result_dir}"
# for testing - use relative path to CWD
c.dataset_config['mnist']['path'] = '../data'
if os.path.exists(test_results_path) and clean_run:
shutil.rmtree(test_results_path)
os.makedirs(test_results_path, exist_ok=True)
args_line += " --results-path {}".format(test_results_path)
# if distributed test -- use all GPU
worker_id = int(os.environ.get("PYTEST_XDIST_WORKER", "gw-1")[2:])
if worker_id >= 0 and torch.cuda.is_available():
gpu_idx = worker_id % torch.cuda.device_count()
args_line += " --gpu {}".format(gpu_idx)
print('ARGS:', args_line)
return main(args_line.split(' '))
def run_main_and_assert(args_line,
taw_current_task_min=0.01,
tag_current_task_min=0.0,
result_dir='results_test'):
acc_taw, acc_tag, forg_taw, forg_tag, exp_dir = run_main(args_line, result_dir)
# acc matrices sanity check
assert acc_tag.shape == acc_taw.shape
assert acc_tag.shape == forg_tag.shape
assert acc_tag.shape == forg_taw.shape
# check current task performance
assert all(acc_tag.diagonal() >= tag_current_task_min)
assert all(acc_taw.diagonal() >= taw_current_task_min)
| import os
import torch
import shutil
from main_incremental import main
import datasets.dataset_config as c
def run_main(args_line, result_dir='results_test', clean_run=False):
assert "--results-path" not in args_line
print('Staring dir:', os.getcwd())
if os.getcwd().endswith('tests'):
os.chdir('..')
elif os.getcwd().endswith('IL_Survey'):
os.chdir('src')
elif os.getcwd().endswith('src'):
print('CWD is OK.')
print('Test CWD:', os.getcwd())
test_results_path = os.getcwd() + f"/../{result_dir}"
# for testing - use relative path to CWD
c.dataset_config['mnist']['path'] = '../data'
if os.path.exists(test_results_path) and clean_run:
shutil.rmtree(test_results_path)
os.makedirs(test_results_path, exist_ok=True)
args_line += " --results-path {}".format(test_results_path)
# if distributed test -- use all GPU
worker_id = int(os.environ.get("PYTEST_XDIST_WORKER", "gw-1")[2:])
if worker_id >= 0 and torch.cuda.is_available():
gpu_idx = worker_id % torch.cuda.device_count()
args_line += " --gpu {}".format(gpu_idx)
print('ARGS:', args_line)
return main(args_line.split(' '))
def run_main_and_assert(args_line,
taw_current_task_min=0.01,
tag_current_task_min=0.0,
result_dir='results_test'):
acc_taw, acc_tag, forg_taw, forg_tag, exp_dir = run_main(args_line, result_dir)
# acc matrices sanity check
assert acc_tag.shape == acc_taw.shape
assert acc_tag.shape == forg_tag.shape
assert acc_tag.shape == forg_taw.shape
# check current task performance
assert all(acc_tag.diagonal() >= tag_current_task_min)
assert all(acc_taw.diagonal() >= taw_current_task_min)
| en | 0.633062 | # for testing - use relative path to CWD # if distributed test -- use all GPU # acc matrices sanity check # check current task performance | 2.139751 | 2 |
learn/mymodel.py | starrysky9959/digital-recognition | 0 | 6622292 | """
@author starrysky
@date 2020/08/16
@details 定义网络结构, 训练模型, 导出模型参数
"""
import os
import sys
import time
import pandas as pd
import torch
import torch.nn as nn
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
# 转换成28*28的Tensor格式
# trans = transforms.Compose([
# transforms.Resize((28, 28)),
# transforms.ToTensor(),
# ])
trans = transforms.ToTensor()
def default_loader(path):
"""
定义读取图片的格式为28*28的单通道灰度图
:param path: 图片路径
:return: 图片
"""
return Image.open(path).convert('L').resize((28, 28))
class MyDataset(Dataset):
"""
制作数据集
"""
def __init__(self, csv_path, transform=None, loader=default_loader):
"""
:param csv_path: 文件路径
:param transform: 转后后的Tensor格式
:param loader: 图片加载方式
"""
super(MyDataset, self).__init__()
df = pd.read_csv(csv_path, engine="python", encoding="utf-8")
self.df = df
self.transform = transform
self.loader = loader
def __getitem__(self, index):
"""
按照索引从数据集提取对应样本的信息
Args:
index: 索引值
Returns:
特征和标签
"""
fn = self.df.iloc[index][1]
label = self.df.iloc[index][2]
img = self.loader(fn)
# 按照路径读取图片
if self.transform is not None:
# 数据标签转换为Tensor
img = self.transform(img)
return img, label
def __len__(self):
"""
样本数量
Returns:
样本数量
"""
return len(self.df)
class LeNet(nn.Module):
"""
定义模型, 这里使用LeNet
"""
def __init__(self):
super(LeNet, self).__init__()
# 卷积层
self.conv = nn.Sequential(
# 输入通道数, 输出通道数, kernel_size
nn.Conv2d(1, 6, 5),
nn.Sigmoid(),
# 最大池化
nn.MaxPool2d(2, 2),
nn.Conv2d(6, 16, 5),
nn.Sigmoid(),
nn.MaxPool2d(2, 2)
)
# 全连接层
self.fc = nn.Sequential(
nn.Linear(16 * 4 * 4, 120),
nn.Sigmoid(),
nn.Linear(120, 84),
nn.Sigmoid(),
nn.Linear(84, 7)
)
def forward(self, img):
feature = self.conv(img)
output = self.fc(feature.view(img.shape[0], -1))
return output
# %% 模型评估
def evaluate_accuracy(data_iter, net, device=None):
"""
评估模型, GPU加速运算
:param data_iter: 测试集迭代器
:param net: 待评估模型
:param device: 训练设备
:return: 正确率
"""
# 未指定训练设备的话就使用 net 的 device
if device is None and isinstance(net, nn.Module):
device = list(net.parameters())[0].device
acc_sum, n = 0.0, 0
with torch.no_grad():
for x, y in data_iter:
if isinstance(net, nn.Module):
# 评估模式, 关闭dropout(丢弃法)
net.eval()
acc_sum += (net(x.to(device)).argmax(dim=1) == y.to(device)).float().sum().cpu().item()
# 改回训练模式
net.train()
n += y.shape[0]
return acc_sum / n
def train_model(net, train_iter, test_iter, loss_func, optimizer, device, num_epochs):
"""
训练模型
:param net: 原始网络
:param train_iter: 训练集
:param test_iter: 测试集
:param loss_func: 损失函数
:param optimizer: 优化器
:param device: 训练设备
:param num_epochs: 训练周期
:return: 无
"""
net = net.to(device)
print("训练设备={0}".format(device))
for i in range(num_epochs):
# 总误差, 准确率
train_lose_sum, train_acc_sum = 0.0, 0.0
# 样本数量, 批次数量
sample_count, batch_count = 0, 0
# 训练时间
start = time.time()
for x, y in train_iter:
# x, y = j
x = x.to(device)
y = y.long().to(device)
y_output = net(x)
lose = loss_func(y_output, y)
optimizer.zero_grad()
lose.backward()
optimizer.step()
train_lose_sum += lose.cpu().item()
train_acc_sum += (y_output.argmax(dim=1) == y).sum().cpu().item()
sample_count += y.shape[0]
batch_count += 1
test_acc = evaluate_accuracy(test_iter, net)
print("第{0}个周期, lose={1:.3f}, train_acc={2:.3f}, test_acc={3:.3f}, time={4:.1f}".format(
i, train_lose_sum / batch_count, train_acc_sum / sample_count, test_acc, time.time() - start
))
if __name__ == '__main__':
# %% 设置工作路径
# print(os.getcwd())
# os.chdir(os.getcwd() + "\learn")
# 获取当前文件路径
print(os.getcwd())
# %% 超参数配置
# 数据集元数据文件的路径
metadata_path = r"./素材/num/label.csv"
# 训练设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 批次规模
batch_size = 1
# 线程数
if sys.platform == "win32":
num_workers = 0
else:
num_workers = 12
# 训练集占比
train_rate = 0.8
# 创建数据集
# src_data = MyDataset(csv_path=metadata_path, transform=trans)
src_data = MyDataset(csv_path=metadata_path, transform=trans)
print('num_of_trainData:', len(src_data))
# for i, j in train_iter:
# print(i.size(), j.size())
# break
net = LeNet()
print(net)
# 训练次数
num_epochs = 5
# 优化算法
optimizer = torch.optim.Adam(net.parameters(), lr=0.002)
# 交叉熵损失函数
loss_func = nn.CrossEntropyLoss()
for i in range(10):
# K折交叉验证
train_size = int(train_rate * len(src_data))
test_size = len(src_data) - train_size
train_set, test_set = torch.utils.data.random_split(src_data, [train_size, test_size])
train_iter = DataLoader(dataset=train_set, batch_size=batch_size, shuffle=True, num_workers=num_workers)
test_iter = DataLoader(dataset=test_set, batch_size=batch_size, shuffle=True, num_workers=num_workers)
train_model(net, train_iter, test_iter, loss_func, optimizer, device, num_epochs)
# 保存训练后的模型数据
torch.save(net.state_dict(), "./model_param/state_dict.pt")
| """
@author starrysky
@date 2020/08/16
@details 定义网络结构, 训练模型, 导出模型参数
"""
import os
import sys
import time
import pandas as pd
import torch
import torch.nn as nn
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
# 转换成28*28的Tensor格式
# trans = transforms.Compose([
# transforms.Resize((28, 28)),
# transforms.ToTensor(),
# ])
trans = transforms.ToTensor()
def default_loader(path):
"""
定义读取图片的格式为28*28的单通道灰度图
:param path: 图片路径
:return: 图片
"""
return Image.open(path).convert('L').resize((28, 28))
class MyDataset(Dataset):
"""
制作数据集
"""
def __init__(self, csv_path, transform=None, loader=default_loader):
"""
:param csv_path: 文件路径
:param transform: 转后后的Tensor格式
:param loader: 图片加载方式
"""
super(MyDataset, self).__init__()
df = pd.read_csv(csv_path, engine="python", encoding="utf-8")
self.df = df
self.transform = transform
self.loader = loader
def __getitem__(self, index):
"""
按照索引从数据集提取对应样本的信息
Args:
index: 索引值
Returns:
特征和标签
"""
fn = self.df.iloc[index][1]
label = self.df.iloc[index][2]
img = self.loader(fn)
# 按照路径读取图片
if self.transform is not None:
# 数据标签转换为Tensor
img = self.transform(img)
return img, label
def __len__(self):
"""
样本数量
Returns:
样本数量
"""
return len(self.df)
class LeNet(nn.Module):
"""
定义模型, 这里使用LeNet
"""
def __init__(self):
super(LeNet, self).__init__()
# 卷积层
self.conv = nn.Sequential(
# 输入通道数, 输出通道数, kernel_size
nn.Conv2d(1, 6, 5),
nn.Sigmoid(),
# 最大池化
nn.MaxPool2d(2, 2),
nn.Conv2d(6, 16, 5),
nn.Sigmoid(),
nn.MaxPool2d(2, 2)
)
# 全连接层
self.fc = nn.Sequential(
nn.Linear(16 * 4 * 4, 120),
nn.Sigmoid(),
nn.Linear(120, 84),
nn.Sigmoid(),
nn.Linear(84, 7)
)
def forward(self, img):
feature = self.conv(img)
output = self.fc(feature.view(img.shape[0], -1))
return output
# %% 模型评估
def evaluate_accuracy(data_iter, net, device=None):
"""
评估模型, GPU加速运算
:param data_iter: 测试集迭代器
:param net: 待评估模型
:param device: 训练设备
:return: 正确率
"""
# 未指定训练设备的话就使用 net 的 device
if device is None and isinstance(net, nn.Module):
device = list(net.parameters())[0].device
acc_sum, n = 0.0, 0
with torch.no_grad():
for x, y in data_iter:
if isinstance(net, nn.Module):
# 评估模式, 关闭dropout(丢弃法)
net.eval()
acc_sum += (net(x.to(device)).argmax(dim=1) == y.to(device)).float().sum().cpu().item()
# 改回训练模式
net.train()
n += y.shape[0]
return acc_sum / n
def train_model(net, train_iter, test_iter, loss_func, optimizer, device, num_epochs):
"""
训练模型
:param net: 原始网络
:param train_iter: 训练集
:param test_iter: 测试集
:param loss_func: 损失函数
:param optimizer: 优化器
:param device: 训练设备
:param num_epochs: 训练周期
:return: 无
"""
net = net.to(device)
print("训练设备={0}".format(device))
for i in range(num_epochs):
# 总误差, 准确率
train_lose_sum, train_acc_sum = 0.0, 0.0
# 样本数量, 批次数量
sample_count, batch_count = 0, 0
# 训练时间
start = time.time()
for x, y in train_iter:
# x, y = j
x = x.to(device)
y = y.long().to(device)
y_output = net(x)
lose = loss_func(y_output, y)
optimizer.zero_grad()
lose.backward()
optimizer.step()
train_lose_sum += lose.cpu().item()
train_acc_sum += (y_output.argmax(dim=1) == y).sum().cpu().item()
sample_count += y.shape[0]
batch_count += 1
test_acc = evaluate_accuracy(test_iter, net)
print("第{0}个周期, lose={1:.3f}, train_acc={2:.3f}, test_acc={3:.3f}, time={4:.1f}".format(
i, train_lose_sum / batch_count, train_acc_sum / sample_count, test_acc, time.time() - start
))
if __name__ == '__main__':
# %% 设置工作路径
# print(os.getcwd())
# os.chdir(os.getcwd() + "\learn")
# 获取当前文件路径
print(os.getcwd())
# %% 超参数配置
# 数据集元数据文件的路径
metadata_path = r"./素材/num/label.csv"
# 训练设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 批次规模
batch_size = 1
# 线程数
if sys.platform == "win32":
num_workers = 0
else:
num_workers = 12
# 训练集占比
train_rate = 0.8
# 创建数据集
# src_data = MyDataset(csv_path=metadata_path, transform=trans)
src_data = MyDataset(csv_path=metadata_path, transform=trans)
print('num_of_trainData:', len(src_data))
# for i, j in train_iter:
# print(i.size(), j.size())
# break
net = LeNet()
print(net)
# 训练次数
num_epochs = 5
# 优化算法
optimizer = torch.optim.Adam(net.parameters(), lr=0.002)
# 交叉熵损失函数
loss_func = nn.CrossEntropyLoss()
for i in range(10):
# K折交叉验证
train_size = int(train_rate * len(src_data))
test_size = len(src_data) - train_size
train_set, test_set = torch.utils.data.random_split(src_data, [train_size, test_size])
train_iter = DataLoader(dataset=train_set, batch_size=batch_size, shuffle=True, num_workers=num_workers)
test_iter = DataLoader(dataset=test_set, batch_size=batch_size, shuffle=True, num_workers=num_workers)
train_model(net, train_iter, test_iter, loss_func, optimizer, device, num_epochs)
# 保存训练后的模型数据
torch.save(net.state_dict(), "./model_param/state_dict.pt")
| zh | 0.771908 | @author starrysky @date 2020/08/16 @details 定义网络结构, 训练模型, 导出模型参数 # 转换成28*28的Tensor格式 # trans = transforms.Compose([ # transforms.Resize((28, 28)), # transforms.ToTensor(), # ]) 定义读取图片的格式为28*28的单通道灰度图 :param path: 图片路径 :return: 图片 制作数据集 :param csv_path: 文件路径 :param transform: 转后后的Tensor格式 :param loader: 图片加载方式 按照索引从数据集提取对应样本的信息 Args: index: 索引值 Returns: 特征和标签 # 按照路径读取图片 # 数据标签转换为Tensor 样本数量 Returns: 样本数量 定义模型, 这里使用LeNet # 卷积层 # 输入通道数, 输出通道数, kernel_size # 最大池化 # 全连接层 # %% 模型评估 评估模型, GPU加速运算 :param data_iter: 测试集迭代器 :param net: 待评估模型 :param device: 训练设备 :return: 正确率 # 未指定训练设备的话就使用 net 的 device # 评估模式, 关闭dropout(丢弃法) # 改回训练模式 训练模型 :param net: 原始网络 :param train_iter: 训练集 :param test_iter: 测试集 :param loss_func: 损失函数 :param optimizer: 优化器 :param device: 训练设备 :param num_epochs: 训练周期 :return: 无 # 总误差, 准确率 # 样本数量, 批次数量 # 训练时间 # x, y = j # %% 设置工作路径 # print(os.getcwd()) # os.chdir(os.getcwd() + "\learn") # 获取当前文件路径 # %% 超参数配置 # 数据集元数据文件的路径 # 训练设备 # 批次规模 # 线程数 # 训练集占比 # 创建数据集 # src_data = MyDataset(csv_path=metadata_path, transform=trans) # for i, j in train_iter: # print(i.size(), j.size()) # break # 训练次数 # 优化算法 # 交叉熵损失函数 # K折交叉验证 # 保存训练后的模型数据 | 2.872126 | 3 |
logger/logger_meta/base_logger.py | JiahuiLei/Pix2Surf | 26 | 6622293 | <reponame>JiahuiLei/Pix2Surf
class BaseLogger(object):
def __init__(self, tb_logger, log_path, cfg):
super().__init__()
self.cfg = cfg
self.NAME = 'base'
self.tb = tb_logger
self.log_path = log_path
# make dir
def log_phase(self):
pass
def log_batch(self, batch):
pass
| class BaseLogger(object):
def __init__(self, tb_logger, log_path, cfg):
super().__init__()
self.cfg = cfg
self.NAME = 'base'
self.tb = tb_logger
self.log_path = log_path
# make dir
def log_phase(self):
pass
def log_batch(self, batch):
pass | en | 0.587136 | # make dir | 2.271172 | 2 |
mycarehub/common/migrations/0014_facility_phone.py | savannahghi/mycarehub-backend | 1 | 6622294 | <gh_stars>1-10
# Generated by Django 3.2.9 on 2021-11-29 08:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0013_alter_facilityattachment_content_type'),
]
operations = [
migrations.AddField(
model_name='facility',
name='phone',
field=models.CharField(blank=True, max_length=15, null=True),
),
]
| # Generated by Django 3.2.9 on 2021-11-29 08:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0013_alter_facilityattachment_content_type'),
]
operations = [
migrations.AddField(
model_name='facility',
name='phone',
field=models.CharField(blank=True, max_length=15, null=True),
),
] | en | 0.831161 | # Generated by Django 3.2.9 on 2021-11-29 08:46 | 1.41833 | 1 |
app/language_features/alt_input.py | andykmiles/code-boutique | 0 | 6622295 | <filename>app/language_features/alt_input.py
import sys
print("does it")
the_input = sys.stdin.readline()
| <filename>app/language_features/alt_input.py
import sys
print("does it")
the_input = sys.stdin.readline()
| none | 1 | 1.853448 | 2 | |
src/app/image_viewer/vertex.py | northfieldzz/vision_tester | 0 | 6622296 | <gh_stars>0
class Vertex:
def __init__(self, x, y):
self.x = x
self.y = y
@property
def tuple(self):
return self.x, self.y
| class Vertex:
def __init__(self, x, y):
self.x = x
self.y = y
@property
def tuple(self):
return self.x, self.y | none | 1 | 2.997449 | 3 | |
Excel2MySQL/dumps.py | sw5cc/Excel2MySQL | 0 | 6622297 | <reponame>sw5cc/Excel2MySQL
# -*- utf-8 -*-
import mysql.connector
from openpyxl import load_workbook
from settings import *
def insert_record(isbn, name, price):
server = mysql.connector.connect(user=MYSQL_USER,
password=<PASSWORD>,
database=MYSQL_DATABASE,
use_unicode=True)
cursor = server.cursor()
cursor.execute('insert into book (isbn, name, price) values (%s, %s, %s)', [isbn, name, price])
server.commit()
cursor.close()
def xls2db(path):
wb = load_workbook(filename=path, read_only=True)
# :type: list of :class:`openpyxl.worksheet.worksheet.Worksheet`
wss = wb.worksheets
for ws in wss:
for row in ws.rows:
book = []
for cell in row:
book.append(cell.value)
if book is not None:
insert_record(book[0], book[1], book[2]) | # -*- utf-8 -*-
import mysql.connector
from openpyxl import load_workbook
from settings import *
def insert_record(isbn, name, price):
server = mysql.connector.connect(user=MYSQL_USER,
password=<PASSWORD>,
database=MYSQL_DATABASE,
use_unicode=True)
cursor = server.cursor()
cursor.execute('insert into book (isbn, name, price) values (%s, %s, %s)', [isbn, name, price])
server.commit()
cursor.close()
def xls2db(path):
wb = load_workbook(filename=path, read_only=True)
# :type: list of :class:`openpyxl.worksheet.worksheet.Worksheet`
wss = wb.worksheets
for ws in wss:
for row in ws.rows:
book = []
for cell in row:
book.append(cell.value)
if book is not None:
insert_record(book[0], book[1], book[2]) | en | 0.50109 | # -*- utf-8 -*- # :type: list of :class:`openpyxl.worksheet.worksheet.Worksheet` | 2.830943 | 3 |
rlkit/envs/half_cheetah_non_stationary_rand_params.py | BZSROCKETS/cemrl | 0 | 6622298 | <filename>rlkit/envs/half_cheetah_non_stationary_rand_params.py
from meta_rand_envs.half_cheetah_non_stationary_rand_mass_params import HalfCheetahNonStationaryRandMassParamEnv
from . import register_env
@register_env('cheetah-non-stationary-rand-mass-params')
class HalfCheetahNonStationaryRandMassParamWrappedEnv(HalfCheetahNonStationaryRandMassParamEnv):
def __init__(self, *args, **kwargs):
HalfCheetahNonStationaryRandMassParamEnv.__init__(self, *args, **kwargs)
| <filename>rlkit/envs/half_cheetah_non_stationary_rand_params.py
from meta_rand_envs.half_cheetah_non_stationary_rand_mass_params import HalfCheetahNonStationaryRandMassParamEnv
from . import register_env
@register_env('cheetah-non-stationary-rand-mass-params')
class HalfCheetahNonStationaryRandMassParamWrappedEnv(HalfCheetahNonStationaryRandMassParamEnv):
def __init__(self, *args, **kwargs):
HalfCheetahNonStationaryRandMassParamEnv.__init__(self, *args, **kwargs)
| none | 1 | 1.73417 | 2 | |
WrapperMap__work_with_dict_through_atts.py | gil9red/SimplePyScripts | 117 | 6622299 | <gh_stars>100-1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
class WrapperMap:
def __init__(self, d: dict):
self.d = d
def get_value(self):
return self.d
def __getattr__(self, item: str):
value = self.d.get(item)
if isinstance(value, dict):
return self.__class__(value)
return value
def __repr__(self):
return repr(self.d)
genMessage = {
'from_user': {
'id': 123,
'username': "username",
'full_name': "fullName"
}
}
x = WrapperMap(genMessage)
print(x.from_user, type(x.from_user))
# {'id': 123, 'username': 'username', 'full_name': 'fullName'} <class '__main__.WrapperMap'>
print(x.from_user.id, type(x.from_user.id))
# 123 <class 'int'>
print(x.from_user.username, type(x.from_user.username))
# username <class 'str'>
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
class WrapperMap:
def __init__(self, d: dict):
self.d = d
def get_value(self):
return self.d
def __getattr__(self, item: str):
value = self.d.get(item)
if isinstance(value, dict):
return self.__class__(value)
return value
def __repr__(self):
return repr(self.d)
genMessage = {
'from_user': {
'id': 123,
'username': "username",
'full_name': "fullName"
}
}
x = WrapperMap(genMessage)
print(x.from_user, type(x.from_user))
# {'id': 123, 'username': 'username', 'full_name': 'fullName'} <class '__main__.WrapperMap'>
print(x.from_user.id, type(x.from_user.id))
# 123 <class 'int'>
print(x.from_user.username, type(x.from_user.username))
# username <class 'str'> | en | 0.157351 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # {'id': 123, 'username': 'username', 'full_name': 'fullName'} <class '__main__.WrapperMap'> # 123 <class 'int'> # username <class 'str'> | 2.937154 | 3 |
common.py | zhaoyueyi/TaichiRenderer | 0 | 6622300 | # @Time : 2021/4/30 23:02
# @Author : 赵曰艺
# @File : common.py
# @Software: PyCharm
# coding:utf-8
import taichi as ti
import taichi_glsl as ts
import numpy as np
from tr_utils import texture_as_field
MAX = 2**20
def V(*xs):
return ti.Vector(xs)
@ti.pyfunc
def ifloor(x):
return int(ti.floor(x))
@ti.pyfunc
def iceil(x):
return int(ti.ceil(x))
@ti.func
def mapply(mat, pos, wei):
res = ti.Vector([mat[i, 3] for i in range(3)]) * wei
for i, j in ti.static(ti.ndrange(3, 3)):
res[i] += mat[i, j] * pos[j]
rew = mat[3, 3] * wei
for i in ti.static(range(3)):
rew += mat[3, i] * pos[i]
return res, rew
@ti.func
def mapply_pos(mat, pos):
res, rew = mapply(mat, pos, 1)
return res / rew
def totuple(x):
if x is None:
x = []
if isinstance(x, ti.Matrix):
x = x.entries
if isinstance(x, list):
x = tuple(x)
if not isinstance(x, tuple):
x = [x]
if isinstance(x, tuple) and len(x) and x[0] is None:
x = []
return tuple(x)
def tovector(x):
return ti.Vector(totuple(x))
@ti.pyfunc
def Vprod(w):
v = tovector(w)
if ti.static(not v.entries):
return 1
x = v.entries[0]
if ti.static(len(v.entries) > 1):
for y in ti.static(v.entries[1:]):
x *= y
return x
@ti.data_oriented
class Node:
arguments = []
defaults = []
def __init__(self, **kwargs):
self.params = {}
for dfl, key in zip(self.defaults, self.arguments):
if key not in kwargs:
if dfl is None:
raise ValueError(f'`{key}` must specified for `{type(self)}`')
value = dfl
else:
value = kwargs[key]
del kwargs[key]
if isinstance(value, str):
if any(value.endswith(x) for x in ['.tga', '.png', '.jpg', '.bmp']):
value = Texture(value)
self.params[key] = value
for key in kwargs.keys():
raise TypeError(
f"{type(self).__name__}() got an unexpected keyword argument '{key}', supported keywords are: {self.arguments}")
def __call__(self, *args, **kwargs):
raise NotImplementedError(type(self))
def param(self, key, *args, **kwargs):
return self.params[key](*args, **kwargs)
class NoTexture:
def __init__(self, name):
pass
@ti.func
def get_color(self, texcoord):
return (1, 1, 1)
@ti.data_oriented
class Texture:
def __init__(self, name):
self.texture = texture_as_field(name+'_diffuse.tga')
self.normal = texture_as_field(name+'_nm.tga')
self.spec = texture_as_field(name+'_spec.tga')
@ti.func
def get_color(self, texcoord):
maxcoor = V(*self.texture.shape) - 1
coor = texcoord * maxcoor
return bilerp(self.texture, coor)
@ti.func
def bilerp(f: ti.template(), pos):
p = float(pos)
I = ifloor(p)
x = p - I
y = 1 - x
return (f[I + V(1, 1)] * x[0] * x[1] +
f[I + V(1, 0)] * x[0] * y[1] +
f[I + V(0, 0)] * y[0] * y[1] +
f[I + V(0, 1)] * y[0] * x[1])
| # @Time : 2021/4/30 23:02
# @Author : 赵曰艺
# @File : common.py
# @Software: PyCharm
# coding:utf-8
import taichi as ti
import taichi_glsl as ts
import numpy as np
from tr_utils import texture_as_field
MAX = 2**20
def V(*xs):
return ti.Vector(xs)
@ti.pyfunc
def ifloor(x):
return int(ti.floor(x))
@ti.pyfunc
def iceil(x):
return int(ti.ceil(x))
@ti.func
def mapply(mat, pos, wei):
res = ti.Vector([mat[i, 3] for i in range(3)]) * wei
for i, j in ti.static(ti.ndrange(3, 3)):
res[i] += mat[i, j] * pos[j]
rew = mat[3, 3] * wei
for i in ti.static(range(3)):
rew += mat[3, i] * pos[i]
return res, rew
@ti.func
def mapply_pos(mat, pos):
res, rew = mapply(mat, pos, 1)
return res / rew
def totuple(x):
if x is None:
x = []
if isinstance(x, ti.Matrix):
x = x.entries
if isinstance(x, list):
x = tuple(x)
if not isinstance(x, tuple):
x = [x]
if isinstance(x, tuple) and len(x) and x[0] is None:
x = []
return tuple(x)
def tovector(x):
return ti.Vector(totuple(x))
@ti.pyfunc
def Vprod(w):
v = tovector(w)
if ti.static(not v.entries):
return 1
x = v.entries[0]
if ti.static(len(v.entries) > 1):
for y in ti.static(v.entries[1:]):
x *= y
return x
@ti.data_oriented
class Node:
arguments = []
defaults = []
def __init__(self, **kwargs):
self.params = {}
for dfl, key in zip(self.defaults, self.arguments):
if key not in kwargs:
if dfl is None:
raise ValueError(f'`{key}` must specified for `{type(self)}`')
value = dfl
else:
value = kwargs[key]
del kwargs[key]
if isinstance(value, str):
if any(value.endswith(x) for x in ['.tga', '.png', '.jpg', '.bmp']):
value = Texture(value)
self.params[key] = value
for key in kwargs.keys():
raise TypeError(
f"{type(self).__name__}() got an unexpected keyword argument '{key}', supported keywords are: {self.arguments}")
def __call__(self, *args, **kwargs):
raise NotImplementedError(type(self))
def param(self, key, *args, **kwargs):
return self.params[key](*args, **kwargs)
class NoTexture:
def __init__(self, name):
pass
@ti.func
def get_color(self, texcoord):
return (1, 1, 1)
@ti.data_oriented
class Texture:
def __init__(self, name):
self.texture = texture_as_field(name+'_diffuse.tga')
self.normal = texture_as_field(name+'_nm.tga')
self.spec = texture_as_field(name+'_spec.tga')
@ti.func
def get_color(self, texcoord):
maxcoor = V(*self.texture.shape) - 1
coor = texcoord * maxcoor
return bilerp(self.texture, coor)
@ti.func
def bilerp(f: ti.template(), pos):
p = float(pos)
I = ifloor(p)
x = p - I
y = 1 - x
return (f[I + V(1, 1)] * x[0] * x[1] +
f[I + V(1, 0)] * x[0] * y[1] +
f[I + V(0, 0)] * y[0] * y[1] +
f[I + V(0, 1)] * y[0] * x[1])
| fr | 0.164307 | # @Time : 2021/4/30 23:02 # @Author : 赵曰艺 # @File : common.py # @Software: PyCharm # coding:utf-8 | 2.173332 | 2 |
reference_code/alex_slalom.py | apanas9246/GRANDPRIX | 0 | 6622301 | <filename>reference_code/alex_slalom.py
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Phase 1 Challenge - Cone Slaloming
"""
########################################################################################
# Imports
########################################################################################
import sys
import cv2 as cv
import numpy as np
import time
from enum import IntEnum, Enum
sys.path.insert(0, "../../library")
import racecar_core
import racecar_utils as rc_utils
########################################################################################
# Global variables
########################################################################################
rc = racecar_core.create_racecar()
KERNEL_SIZE = 5
MIN_CONTOUR_AREA = 70
MAX_CONTOUR_DIST = 300
MAX_SPEED = 0.25
# Add any global variables here
########################################################################################
# Functions
########################################################################################
class Slalom:
class State(IntEnum):
# Align with cone and move towards it while it is visible
APPROACH = 0
# Once cone is no longer visible (i.e no visible contours or next contour visible is not same color)
# Car uses previous estimates of speed to pass the cone
PASS = 1
# Depending on color, turn car until contour is found. If found, go to state 0
TURN = 2
class Color(IntEnum):
# Pass on the left
BLUE = 0
# Pass on the right
RED = 1
class Const(Enum):
# Maximum distance change between frames to count as valid
MAX_DIST_DIFF = 30
# When passing visible cone, used as lower and higher boundaries for a proportion used to determine
# how far off-center of the screen to set the setpoint to not crash into the cone as the car gets close
LOW_SET_PROPORTION = (90 / 320)
HIGH_SET_PROPORTION = (320 / 320)
# The distance boundaries used for the above proportion
APPROACH_DIST_UPPER = 200
APPROACH_DIST_LOWER = 27
# How many cm to drive to pass a cone that went out of view
PASS_DIST = 15
PASS_TIME = 0.25
# Consecutive no contours to start turn
MAX_CONSEC_CONTOURS = 1
def __init__(self, manual_mode=False):
self.__is_manual = manual_mode
print("$: Initiated Cone Slalom in", "Manual" if self.__is_manual else "Auto", "Mode")
self.COLORS = {"BLUE": ((90, 120, 120), (120, 255, 255)),
"RED": ((130, 50, 50), (179, 255, 255))}
self.__cur_col = self.Color.RED
self.__cur_state = self.State.APPROACH
self.__depth_image = None
self.__color_image = None
self.__closest_lidar_sample = None
self.update_images()
# Variables for contour tracking
self.__contour_distance = None
self.__contour_center = None
self.__contour = None
self.update_contours()
# Estimated Speed of car. Only calculated in approach state
self.__speed = None
# Previous distance to cone
self.__prev_distance = None
# Used to calculate speed
self.__prev_time = None
# Consecutive frames where no contour was seen
self.__consec_no_cont = 0
self.__approach_angle = 0
self.__approach_speed = 0
self.__approach_setpoint = 0
def update_contours(self):
contours = rc_utils.find_contours(self.__color_image, self.COLORS[self.__cur_col.name][0], self.COLORS[self.__cur_col.name][1])
out = Slalom.get_closest_contour(contours, self.__depth_image)
if out is not None:
# Saves previous measured distance
if self.__contour_distance is not None:
self.__prev_distance = self.__contour_distance
self.__contour_distance, self.__contour, self.__contour_center = out
# Draws closest contour
rc_utils.draw_contour(self.__color_image, self.__contour)
rc_utils.draw_circle(self.__color_image, self.__contour_center)
else:
self.__contour_distance = None
self.__contour_center = None
self.__contour = None
# Displays image
rc.display.show_color_image(self.__color_image)
def update_images(self):
self.__color_image = rc.camera.get_color_image()
self.__depth_image = cv.GaussianBlur((rc.camera.get_depth_image() - 0.01) % 10000, (KERNEL_SIZE, KERNEL_SIZE), 0)
self.__closest_lidar_sample = rc_utils.get_lidar_closest_point((rc.lidar.get_samples() - 0.1) * 1000, (0, 360))
# Gets speed based on the cone being approached
def update_speed(self):
if self.__contour_distance is not None and self.__prev_distance is not None and self.__prev_time is not None:
# Calculates Speed
self.__speed = round(-(self.__contour_distance - self.__prev_distance) / (time.time() - self.__prev_time), 2)
else:
self.__speed = None
# Updates previous time
self.__prev_time = time.time()
def get_closest_opposite_contour(self):
# Finds closest contour of opposite color
opp_col = self.Color.RED if self.__cur_col == self.Color.BLUE else self.Color.BLUE
opp_conts = rc_utils.find_contours(self.__color_image, self.COLORS[opp_col.name][0], self.COLORS[opp_col.name][1])
out = Slalom.get_closest_contour(opp_conts, self.__depth_image)
# Gets the distance to the closest opposite color cone
if out is not None:
dist_opp = out[0]
else:
# A really high number that will always be greater than the closest desired cone
dist_opp = 99999
return dist_opp
def run_pass_state(self):
if 60 < self.__closest_lidar_sample[0] < 300:
self.__is_stamped = False
self.__cur_state = self.State.TURN
def run_turn_state(self):
# >>> State Switch Detection
# --------------------
dist_opp = self.get_closest_opposite_contour()
# Must have a cone of the needed color visible
# and checks if the needed cone is closer than the closest opposite color cone
if self.__contour_distance is not None and self.__contour_distance < dist_opp:
self.__cur_state = self.State.APPROACH
# >>> Turn to find cone
# ---------------------
else:
speed = 1
# If blue cone needs to be found next, turn left. Otherwise right
angle = -1 if self.__cur_col == self.Color.BLUE else 1
# Turns until cone is found
rc.drive.set_speed_angle(speed, angle)
def run_approach_state(self):
# Calculates distance change to see if cone was passed
if self.__contour_distance is not None:
distance_change = self.__contour_distance - self.__prev_distance
self.__consec_no_cont = 0
else:
distance_change = None
self.__consec_no_cont += 1
dist_opp = self.get_closest_opposite_contour()
# If distance makes a huge jump, assume that it is now following a different cone so switch states
if self.__consec_no_cont >= self.Const.MAX_CONSEC_CONTOURS.value or (distance_change > self.Const.MAX_DIST_DIFF.value and dist_opp < self.__contour_distance):
self.__cur_col = self.Color.BLUE if self.__cur_col == self.Color.RED else self.Color.RED
self.__cur_state = self.State.PASS
else:
# >>>> Proportional control
# -------------------------
# Updates speed variable
self.update_speed()
# Scales the center offset boundaries based on screen width
w = rc.camera.get_width()
low_set = self.Const.LOW_SET_PROPORTION.value * (w / 2)
high_set = self.Const.HIGH_SET_PROPORTION.value * (w / 2)
# Calculates new setpoint based on how close the car is to the cone.
if self.__contour_distance is not None:
self.__approach_setpoint = rc_utils.remap_range(self.__contour_distance, self.Const.APPROACH_DIST_UPPER.value,
self.Const.APPROACH_DIST_LOWER.value, low_set, high_set)
# negates setpoint if color is red. This ensures that the car passes cone on correct side
self.__approach_setpoint *= (-1 if self.__cur_col == self.Color.RED else 1)
"""DEBUG: Draw Setpoint"""
#rc_utils.draw_circle(self.__color_image, (rc.camera.get_height() // 2, int((w / 2) + setpoint)))
# Gets angle from setpoint using proportional control
kP = 4
if self.__contour_distance is not None:
self.__approach_angle = rc_utils.clamp(rc_utils.remap_range(self.__contour_center[1], self.__approach_setpoint,
rc.camera.get_width() + self.__approach_setpoint, -1, 1) * kP, -1, 1)
self.__approach_speed = rc_utils.remap_range(abs(self.__approach_angle), 1, 0, 0.1, 1)
#self.__approach_speed = 1
# Sets speed angle
rc.drive.set_speed_angle(self.__approach_speed, self.__approach_angle)
"""DEBUG: Show image"""
#rc.display.show_color_image(self.__color_image)
# Call this to run automatic slaloms
def auto_control(self):
if self.__cur_state == self.State.APPROACH:
self.run_approach_state()
elif self.__cur_state == self.State.PASS:
self.run_pass_state()
elif self.__cur_state == self.State.TURN:
self.run_turn_state()
else:
rc.drive.set_speed_angle(0, 0)
# Call this to debug. Allows full user car control
def user_control(self):
# Gets speed using triggers
rt = rc.controller.get_trigger(rc.controller.Trigger.RIGHT)
lt = rc.controller.get_trigger(rc.controller.Trigger.LEFT)
speed = rt - lt
# Gets angle from x axis of left joystick
angle = rc.controller.get_joystick(rc.controller.Joystick.LEFT)[0]
# Sets speed and angle
rc.drive.set_speed_angle(rc_utils.clamp(speed, -1, 1), rc_utils.clamp(angle, -1, 1))
# Main overhead function. Runs state machine
def run_slalom(self):
self.update_images()
self.update_contours()
# Calls respective functions depending on if manual control was enabled
if self.__is_manual:
self.user_control()
else:
self.auto_control()
# DEBUGGING
#self.update_speed()
print("Distance", self.__contour_distance, "Speed", self.__speed, "State", self.__cur_state.name, "Angle", self.__closest_lidar_sample[0])
@staticmethod
def get_closest_contour(contours, depth_img):
# Gets centers of each contour and extracts countours based on conditions
centers = []
for idx, contour in enumerate(contours):
cent = rc_utils.get_contour_center(contour)
if cent is not None:
dist = rc_utils.get_pixel_average_distance(depth_img, cent)
area = rc_utils.get_contour_area(contour)
if area > MIN_CONTOUR_AREA and dist < MAX_CONTOUR_DIST:
centers.append((idx, rc_utils.get_contour_center(contour)))
indexes = [center[0] for center in centers]
centers = [center[1] for center in centers]
# Calculates the distance to each center
distances = [rc_utils.get_pixel_average_distance(depth_img, (center[0], center[1])) for center in centers]
conts = [contours[index] for index in indexes]
# Finds smallest distance and index of that distance
if len(conts):
minimum = min(enumerate(distances), key=lambda x: x[1])
# (index, min dist)
# Returns distance to closest contour center, the contour itself, and the center position
return (minimum[1], conts[minimum[0]], centers[minimum[0]])
else:
# If there is no contour, my love for humanities is returned
return None
SLALOM = None
def start():
global SLALOM
"""
This function is run once every time the start button is pressed
"""
# Have the car begin at a stop
rc.drive.stop()
# Sets maximum speed
rc.drive.set_max_speed(MAX_SPEED)
# Print start message
print(">> Phase 1 Challenge: Cone Slaloming")
SLALOM = Slalom(manual_mode=False)
def update():
"""
After start() is run, this function is run every frame until the back button
is pressed
"""
# TODO: Slalom between red and blue cones. The car should pass to the right of
# each red cone and the left of each blue cone.
SLALOM.run_slalom()
########################################################################################
# DO NOT MODIFY: Register start and update and begin execution
########################################################################################
if __name__ == "__main__":
rc.set_start_update(start, update, None)
rc.go()
| <filename>reference_code/alex_slalom.py
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Phase 1 Challenge - Cone Slaloming
"""
########################################################################################
# Imports
########################################################################################
import sys
import cv2 as cv
import numpy as np
import time
from enum import IntEnum, Enum
sys.path.insert(0, "../../library")
import racecar_core
import racecar_utils as rc_utils
########################################################################################
# Global variables
########################################################################################
rc = racecar_core.create_racecar()
KERNEL_SIZE = 5
MIN_CONTOUR_AREA = 70
MAX_CONTOUR_DIST = 300
MAX_SPEED = 0.25
# Add any global variables here
########################################################################################
# Functions
########################################################################################
class Slalom:
class State(IntEnum):
# Align with cone and move towards it while it is visible
APPROACH = 0
# Once cone is no longer visible (i.e no visible contours or next contour visible is not same color)
# Car uses previous estimates of speed to pass the cone
PASS = 1
# Depending on color, turn car until contour is found. If found, go to state 0
TURN = 2
class Color(IntEnum):
# Pass on the left
BLUE = 0
# Pass on the right
RED = 1
class Const(Enum):
# Maximum distance change between frames to count as valid
MAX_DIST_DIFF = 30
# When passing visible cone, used as lower and higher boundaries for a proportion used to determine
# how far off-center of the screen to set the setpoint to not crash into the cone as the car gets close
LOW_SET_PROPORTION = (90 / 320)
HIGH_SET_PROPORTION = (320 / 320)
# The distance boundaries used for the above proportion
APPROACH_DIST_UPPER = 200
APPROACH_DIST_LOWER = 27
# How many cm to drive to pass a cone that went out of view
PASS_DIST = 15
PASS_TIME = 0.25
# Consecutive no contours to start turn
MAX_CONSEC_CONTOURS = 1
def __init__(self, manual_mode=False):
self.__is_manual = manual_mode
print("$: Initiated Cone Slalom in", "Manual" if self.__is_manual else "Auto", "Mode")
self.COLORS = {"BLUE": ((90, 120, 120), (120, 255, 255)),
"RED": ((130, 50, 50), (179, 255, 255))}
self.__cur_col = self.Color.RED
self.__cur_state = self.State.APPROACH
self.__depth_image = None
self.__color_image = None
self.__closest_lidar_sample = None
self.update_images()
# Variables for contour tracking
self.__contour_distance = None
self.__contour_center = None
self.__contour = None
self.update_contours()
# Estimated Speed of car. Only calculated in approach state
self.__speed = None
# Previous distance to cone
self.__prev_distance = None
# Used to calculate speed
self.__prev_time = None
# Consecutive frames where no contour was seen
self.__consec_no_cont = 0
self.__approach_angle = 0
self.__approach_speed = 0
self.__approach_setpoint = 0
def update_contours(self):
contours = rc_utils.find_contours(self.__color_image, self.COLORS[self.__cur_col.name][0], self.COLORS[self.__cur_col.name][1])
out = Slalom.get_closest_contour(contours, self.__depth_image)
if out is not None:
# Saves previous measured distance
if self.__contour_distance is not None:
self.__prev_distance = self.__contour_distance
self.__contour_distance, self.__contour, self.__contour_center = out
# Draws closest contour
rc_utils.draw_contour(self.__color_image, self.__contour)
rc_utils.draw_circle(self.__color_image, self.__contour_center)
else:
self.__contour_distance = None
self.__contour_center = None
self.__contour = None
# Displays image
rc.display.show_color_image(self.__color_image)
def update_images(self):
self.__color_image = rc.camera.get_color_image()
self.__depth_image = cv.GaussianBlur((rc.camera.get_depth_image() - 0.01) % 10000, (KERNEL_SIZE, KERNEL_SIZE), 0)
self.__closest_lidar_sample = rc_utils.get_lidar_closest_point((rc.lidar.get_samples() - 0.1) * 1000, (0, 360))
# Gets speed based on the cone being approached
def update_speed(self):
if self.__contour_distance is not None and self.__prev_distance is not None and self.__prev_time is not None:
# Calculates Speed
self.__speed = round(-(self.__contour_distance - self.__prev_distance) / (time.time() - self.__prev_time), 2)
else:
self.__speed = None
# Updates previous time
self.__prev_time = time.time()
def get_closest_opposite_contour(self):
# Finds closest contour of opposite color
opp_col = self.Color.RED if self.__cur_col == self.Color.BLUE else self.Color.BLUE
opp_conts = rc_utils.find_contours(self.__color_image, self.COLORS[opp_col.name][0], self.COLORS[opp_col.name][1])
out = Slalom.get_closest_contour(opp_conts, self.__depth_image)
# Gets the distance to the closest opposite color cone
if out is not None:
dist_opp = out[0]
else:
# A really high number that will always be greater than the closest desired cone
dist_opp = 99999
return dist_opp
def run_pass_state(self):
if 60 < self.__closest_lidar_sample[0] < 300:
self.__is_stamped = False
self.__cur_state = self.State.TURN
def run_turn_state(self):
# >>> State Switch Detection
# --------------------
dist_opp = self.get_closest_opposite_contour()
# Must have a cone of the needed color visible
# and checks if the needed cone is closer than the closest opposite color cone
if self.__contour_distance is not None and self.__contour_distance < dist_opp:
self.__cur_state = self.State.APPROACH
# >>> Turn to find cone
# ---------------------
else:
speed = 1
# If blue cone needs to be found next, turn left. Otherwise right
angle = -1 if self.__cur_col == self.Color.BLUE else 1
# Turns until cone is found
rc.drive.set_speed_angle(speed, angle)
def run_approach_state(self):
# Calculates distance change to see if cone was passed
if self.__contour_distance is not None:
distance_change = self.__contour_distance - self.__prev_distance
self.__consec_no_cont = 0
else:
distance_change = None
self.__consec_no_cont += 1
dist_opp = self.get_closest_opposite_contour()
# If distance makes a huge jump, assume that it is now following a different cone so switch states
if self.__consec_no_cont >= self.Const.MAX_CONSEC_CONTOURS.value or (distance_change > self.Const.MAX_DIST_DIFF.value and dist_opp < self.__contour_distance):
self.__cur_col = self.Color.BLUE if self.__cur_col == self.Color.RED else self.Color.RED
self.__cur_state = self.State.PASS
else:
# >>>> Proportional control
# -------------------------
# Updates speed variable
self.update_speed()
# Scales the center offset boundaries based on screen width
w = rc.camera.get_width()
low_set = self.Const.LOW_SET_PROPORTION.value * (w / 2)
high_set = self.Const.HIGH_SET_PROPORTION.value * (w / 2)
# Calculates new setpoint based on how close the car is to the cone.
if self.__contour_distance is not None:
self.__approach_setpoint = rc_utils.remap_range(self.__contour_distance, self.Const.APPROACH_DIST_UPPER.value,
self.Const.APPROACH_DIST_LOWER.value, low_set, high_set)
# negates setpoint if color is red. This ensures that the car passes cone on correct side
self.__approach_setpoint *= (-1 if self.__cur_col == self.Color.RED else 1)
"""DEBUG: Draw Setpoint"""
#rc_utils.draw_circle(self.__color_image, (rc.camera.get_height() // 2, int((w / 2) + setpoint)))
# Gets angle from setpoint using proportional control
kP = 4
if self.__contour_distance is not None:
self.__approach_angle = rc_utils.clamp(rc_utils.remap_range(self.__contour_center[1], self.__approach_setpoint,
rc.camera.get_width() + self.__approach_setpoint, -1, 1) * kP, -1, 1)
self.__approach_speed = rc_utils.remap_range(abs(self.__approach_angle), 1, 0, 0.1, 1)
#self.__approach_speed = 1
# Sets speed angle
rc.drive.set_speed_angle(self.__approach_speed, self.__approach_angle)
"""DEBUG: Show image"""
#rc.display.show_color_image(self.__color_image)
# Call this to run automatic slaloms
def auto_control(self):
if self.__cur_state == self.State.APPROACH:
self.run_approach_state()
elif self.__cur_state == self.State.PASS:
self.run_pass_state()
elif self.__cur_state == self.State.TURN:
self.run_turn_state()
else:
rc.drive.set_speed_angle(0, 0)
# Call this to debug. Allows full user car control
def user_control(self):
# Gets speed using triggers
rt = rc.controller.get_trigger(rc.controller.Trigger.RIGHT)
lt = rc.controller.get_trigger(rc.controller.Trigger.LEFT)
speed = rt - lt
# Gets angle from x axis of left joystick
angle = rc.controller.get_joystick(rc.controller.Joystick.LEFT)[0]
# Sets speed and angle
rc.drive.set_speed_angle(rc_utils.clamp(speed, -1, 1), rc_utils.clamp(angle, -1, 1))
# Main overhead function. Runs state machine
def run_slalom(self):
self.update_images()
self.update_contours()
# Calls respective functions depending on if manual control was enabled
if self.__is_manual:
self.user_control()
else:
self.auto_control()
# DEBUGGING
#self.update_speed()
print("Distance", self.__contour_distance, "Speed", self.__speed, "State", self.__cur_state.name, "Angle", self.__closest_lidar_sample[0])
@staticmethod
def get_closest_contour(contours, depth_img):
# Gets centers of each contour and extracts countours based on conditions
centers = []
for idx, contour in enumerate(contours):
cent = rc_utils.get_contour_center(contour)
if cent is not None:
dist = rc_utils.get_pixel_average_distance(depth_img, cent)
area = rc_utils.get_contour_area(contour)
if area > MIN_CONTOUR_AREA and dist < MAX_CONTOUR_DIST:
centers.append((idx, rc_utils.get_contour_center(contour)))
indexes = [center[0] for center in centers]
centers = [center[1] for center in centers]
# Calculates the distance to each center
distances = [rc_utils.get_pixel_average_distance(depth_img, (center[0], center[1])) for center in centers]
conts = [contours[index] for index in indexes]
# Finds smallest distance and index of that distance
if len(conts):
minimum = min(enumerate(distances), key=lambda x: x[1])
# (index, min dist)
# Returns distance to closest contour center, the contour itself, and the center position
return (minimum[1], conts[minimum[0]], centers[minimum[0]])
else:
# If there is no contour, my love for humanities is returned
return None
SLALOM = None
def start():
global SLALOM
"""
This function is run once every time the start button is pressed
"""
# Have the car begin at a stop
rc.drive.stop()
# Sets maximum speed
rc.drive.set_max_speed(MAX_SPEED)
# Print start message
print(">> Phase 1 Challenge: Cone Slaloming")
SLALOM = Slalom(manual_mode=False)
def update():
"""
After start() is run, this function is run every frame until the back button
is pressed
"""
# TODO: Slalom between red and blue cones. The car should pass to the right of
# each red cone and the left of each blue cone.
SLALOM.run_slalom()
########################################################################################
# DO NOT MODIFY: Register start and update and begin execution
########################################################################################
if __name__ == "__main__":
rc.set_start_update(start, update, None)
rc.go()
| en | 0.668284 | Copyright MIT and Harvey Mudd College MIT License Summer 2020 Phase 1 Challenge - Cone Slaloming ######################################################################################## # Imports ######################################################################################## ######################################################################################## # Global variables ######################################################################################## # Add any global variables here ######################################################################################## # Functions ######################################################################################## # Align with cone and move towards it while it is visible # Once cone is no longer visible (i.e no visible contours or next contour visible is not same color) # Car uses previous estimates of speed to pass the cone # Depending on color, turn car until contour is found. If found, go to state 0 # Pass on the left # Pass on the right # Maximum distance change between frames to count as valid # When passing visible cone, used as lower and higher boundaries for a proportion used to determine # how far off-center of the screen to set the setpoint to not crash into the cone as the car gets close # The distance boundaries used for the above proportion # How many cm to drive to pass a cone that went out of view # Consecutive no contours to start turn # Variables for contour tracking # Estimated Speed of car. Only calculated in approach state # Previous distance to cone # Used to calculate speed # Consecutive frames where no contour was seen # Saves previous measured distance # Draws closest contour # Displays image # Gets speed based on the cone being approached # Calculates Speed # Updates previous time # Finds closest contour of opposite color # Gets the distance to the closest opposite color cone # A really high number that will always be greater than the closest desired cone # >>> State Switch Detection # -------------------- # Must have a cone of the needed color visible # and checks if the needed cone is closer than the closest opposite color cone # >>> Turn to find cone # --------------------- # If blue cone needs to be found next, turn left. Otherwise right # Turns until cone is found # Calculates distance change to see if cone was passed # If distance makes a huge jump, assume that it is now following a different cone so switch states # >>>> Proportional control # ------------------------- # Updates speed variable # Scales the center offset boundaries based on screen width # Calculates new setpoint based on how close the car is to the cone. # negates setpoint if color is red. This ensures that the car passes cone on correct side DEBUG: Draw Setpoint #rc_utils.draw_circle(self.__color_image, (rc.camera.get_height() // 2, int((w / 2) + setpoint))) # Gets angle from setpoint using proportional control #self.__approach_speed = 1 # Sets speed angle DEBUG: Show image #rc.display.show_color_image(self.__color_image) # Call this to run automatic slaloms # Call this to debug. Allows full user car control # Gets speed using triggers # Gets angle from x axis of left joystick # Sets speed and angle # Main overhead function. Runs state machine # Calls respective functions depending on if manual control was enabled # DEBUGGING #self.update_speed() # Gets centers of each contour and extracts countours based on conditions # Calculates the distance to each center # Finds smallest distance and index of that distance # (index, min dist) # Returns distance to closest contour center, the contour itself, and the center position # If there is no contour, my love for humanities is returned This function is run once every time the start button is pressed # Have the car begin at a stop # Sets maximum speed # Print start message After start() is run, this function is run every frame until the back button is pressed # TODO: Slalom between red and blue cones. The car should pass to the right of # each red cone and the left of each blue cone. ######################################################################################## # DO NOT MODIFY: Register start and update and begin execution ######################################################################################## | 2.157152 | 2 |
TwitterAPI_exploring/twitterSearch.py | LuisFeliciano/BokChoy | 1 | 6622302 | import constants
import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
def main():
authentication = tweepy.OAuthHandler(constants.API_KEY, constants.API_SECRET_KEY)
authentication.set_access_token(constants.ACCESS_TOKEN, constants.ACCESS_SECRET_TOKEN)
api = tweepy.API(authentication)
tweets = api.search('weather', 'ohio', 50)
for tweet in tweets:
print("Tweet from " + tweet.user + " Tweet Message: " + tweet.text)
tweets = api.search('39.758949,-84.191605,25mi', 50)
for tweet in tweets:
print("Tweet from " + tweet.user + " Tweet Message: " + tweet.text)
if __name__ == "__main__":
main()
| import constants
import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
def main():
authentication = tweepy.OAuthHandler(constants.API_KEY, constants.API_SECRET_KEY)
authentication.set_access_token(constants.ACCESS_TOKEN, constants.ACCESS_SECRET_TOKEN)
api = tweepy.API(authentication)
tweets = api.search('weather', 'ohio', 50)
for tweet in tweets:
print("Tweet from " + tweet.user + " Tweet Message: " + tweet.text)
tweets = api.search('39.758949,-84.191605,25mi', 50)
for tweet in tweets:
print("Tweet from " + tweet.user + " Tweet Message: " + tweet.text)
if __name__ == "__main__":
main()
| none | 1 | 3.151666 | 3 | |
app/main.py | sarahalamdari/DIRECT_capstone | 1 | 6622303 | <filename>app/main.py
import base64
import json
import os
import pickle
import copy
import datetime as dt
import pandas as pd
import numpy as np
from flask import Flask
#from flask_cors import CORS
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
server = Flask(__name__)
app = dash.Dash(__name__, server=server)
#app.scripts.config.serve_locally = True
app.css.append_css({'external_url': 'https://cdn.rawgit.com/plotly/dash-app-stylesheets/2d266c578d2a6e8850ebce48fdb52759b2aef506/stylesheet-oil-and-gas.css'}) # noqa: E501
#server = app.server
#CORS(server)
#if 'DYNO' in os.environ:
# app.scripts.append_script({
# 'external_url': 'https://cdn.rawgit.com/chriddyp/ca0d8f02a1659981a0ea7f013a378bbd/raw/e79f3f789517deec58f41251f7dbb6bee72c44ab/plotly_ga.js' # noqa: E501
# })
# Create global chart template
mapbox_access_token = '<KEY>' # noqa: E501
#data = pd.read_csv("https://www.dropbox.com/s/3x1b7glfpuwn794/tweet_global_warming.csv?dl=1", encoding="latin")
data = pd.read_csv("https://www.dropbox.com/s/3a31qflbppy3ob8/sample_prediction.csv?dl=1", encoding="latin")
#data = pd.read_csv("sample_prediction.csv", encoding="latin")
#print (data['clean_text'])
#Change size of points
data['score'] = data['positive']-data['negative']
data['var_mean'] = np.sqrt(data['retweets']/data['retweets'].max())*20
sizes = data['var_mean']+4 # 4 is the smallest size a point can be
num_bin = 50
bin_width = 2/num_bin
#twit image
img = base64.b64encode(open('twit.png', 'rb').read())
layout = dict(
autosize=True,
height=800,
font=dict(color='#CCCCCC'),
titlefont=dict(color='#CCCCCC', size='14'),
margin=dict(
l=35,
r=35,
b=35,
t=45
),
hovermode="closest",
plot_bgcolor="#191A1A",
paper_bgcolor="#020202",
legend=dict(font=dict(size=10), orientation='h'),
title='Satellite Overview',
mapbox=dict(
accesstoken=mapbox_access_token,
style="dark",
center=dict(
lon=-98.4842,
lat=39.0119
),
zoom=3,
),
updatemenus= [
dict(
buttons=([
dict(
args=[{
'mapbox.zoom': 3,
'mapbox.center.lon': '-98.4842',
'mapbox.center.lat': '39.0119',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Reset Zoom',
method='relayout'
)
]),
direction='left',
pad={'r': 0, 't': 0, 'b': 0, 'l': 0},
showactive=False,
type='buttons',
x=0.45,
xanchor='left',
yanchor='bottom',
bgcolor='#323130',
borderwidth=1,
bordercolor="#6d6d6d",
font=dict(
color="#FFFFFF"
),
y=0.02
),
dict(
buttons=([
dict(
args=[{
'mapbox.zoom': 8,
'mapbox.center.lon': '-95.3698',
'mapbox.center.lat': '29.7604',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Houston',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 8,
'mapbox.center.lon': '-87.6298',
'mapbox.center.lat': '41.8781',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Chicago',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 5,
'mapbox.center.lon': '-86.9023',
'mapbox.center.lat': '32.3182',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Alabama',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 8,
'mapbox.center.lon': '-74.0113',
'mapbox.center.lat': '40.7069',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='New York City',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 8,
'mapbox.center.lon': '-122.3321',
'mapbox.center.lat': '47.6062',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Seattle',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 7,
'mapbox.center.lon': '-118.2437',
'mapbox.center.lat': '34.0522',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Los Angeles',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 5,
'mapbox.center.lon': '-86.5804',
'mapbox.center.lat': '35.5175',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Tennessee',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 5,
'mapbox.center.lon': '-3.4360',
'mapbox.center.lat': '55.3781',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='UK',
method='relayout'
)
]),
direction="down",
pad={'r': 0, 't': 0, 'b': 0, 'l': 0},
showactive=False,
bgcolor="rgb(50, 49, 48, 0)",
type='buttons',
yanchor='bottom',
xanchor='left',
font=dict(
color="#FFFFFF"
),
x=0,
y=0.05
)
]
)
# Create app layout
app.layout = html.Div([
html.Div([
html.H1(
'WYNS',
#className='eight columns',
),
html.H4(
'Use our tools to explore tweets on climate change from around the world!'),
html.Br(),
],
className='row'
),
html.Div([
html.Img(src='data:image/png;base64,{}'.format(img.decode())),
],
style={
'minHeight':'100px'},
className='one columns'
),
html.Div([
html.Div(id='tweet-text')
],
style={
#'color':'blue',
'fontSize':18,
#'columnCount':2,
'minHeight':'100px'},
className='eight columns'
),
html.Div([
html.P(
id='year_text',
style={'text-align': 'right'}
),
],
className='two columns'
),
html.Div([
html.Br(),
html.P('Filter by Date:'),
dcc.RangeSlider(
id='year_slider',
min=0,
max=len(data),
value=[len(data)//10,len(data)*2//10],
marks={
0: data['time'].min(),
len(data): data['time'].max()
}
),
html.Br(),
],
className='twelve columns',
id='slider_holder'
),
html.Div([
dcc.Checklist(
id='lock_selector',
options=[
{'label': 'Lock camera', 'value': 'locked'}
],
values=[],
),
# html.Button('Reload Data', id='button'),
# html.Div(id='hidden_div')
],
style={'margin-top': '20'},
className='eight columns'
),
html.Div(
[
html.Div(
[
dcc.Graph(id='main_graph')
],
className='eight columns',
style={'margin-top': '20'}
),
html.Div(
[
dcc.Graph(id='individual_graph')
],
className='four columns',
style={'margin-top': '20'}
),
],
className='row'
),
],
className='ten columns offset-by-one'
)
# functions that help with cleaning / filtering data
TWIT_TYPES = dict(
Yes = '#76acf2',
Y = '#76acf2',
No = '#e85353',
N = '#e85353',
unrelated = '#efe98d'
)
def filter_data(df, slider):
return
# function that reloads the data
#@app.callback(Output('slider_holder','children'),[Input('button','n_clicks')])
#def fetch_data(n_clicks):
# print(n_clicks)
# if n_clicks is not None:
# data = pd.read_csv("https://www.dropbox.com/s/3a31qflbppy3ob8/sample_prediction.csv?dl=1", encoding="latin")
# #data = pd.read_csv("sample_prediction.csv", encoding="latin")
# #print (data['clean_text'])
#
# #Change size of points
# data['score'] = data['positive']-data['negative']
# data['var_mean'] = np.sqrt(data['retweets']/data['retweets'].max())*20
# sizes = data['var_mean']+4
# print(len(data))
## return html.Div([])
# return html.Div([
# html.Br(),
# html.P('Filter by Date:'),
# dcc.RangeSlider(
# id='year_slider',
# min=0,
# max=len(data),
# value=[len(data)//10,len(data)*2//10],
# marks={
# 0: data['time'].min(),
# len(data): data['time'].max()
# }
# ),
# html.Br(),
# ],
# className='twelve columns',
# id='slider_holder'
# )
# else:
# return html.Div([
# html.Br(),
# html.P('Filter by Date:'),
# dcc.RangeSlider(
# id='year_slider',
# min=0,
# max=len(data),
# value=[len(data)//10,len(data)*2//10],
# marks={
# 0: data['time'].min(),
# len(data): data['time'].max()
# }
# ),
# html.Br(),
# ],
# className='twelve columns',
# id='slider_holder'
# )
# start the callbacks
# Main Graph -> update
# the below code uses a heatmap to render the data points
@app.callback(Output('main_graph', 'figure'),
[Input('year_slider', 'value'),
Input('individual_graph', 'selectedData')],
[State('lock_selector', 'values'),
State('main_graph', 'relayoutData')])
def make_main_figure(year_slider, hist_select, selector, main_graph_layout):
###slect first thingy in json and grab x as min
###slelect last thingy in json and grab x as max
####return that cheese to the filter function as [min, max]
###we'll call that funciton in the main graph callback
####and then business as usuall.....
df = data.iloc[year_slider[0]:year_slider[1]]
if hist_select:
min_heat = hist_select['points'][0]['x']
max_heat = hist_select['points'][-1]['x'] + bin_width
# change this if you change bin size doood
dff = df[df['score'] > min_heat]
df = dff[dff['score'] < max_heat]
traces = [dict(
type='scattermapbox',
lon = df['long'],
lat = df['lat'],
#text='can customize text',
customdata = df['clean_text'],
name = df['score'],
marker=dict(
size=sizes,
opacity=0.8,
color = df['score'],
cmin=-1,
cmax=1,
colorbar = dict(
title='Belief'
),
colorscale = [[0.0, 'rgb(165,0,38)'],
[0.1111111111111111, 'rgb(215,48,39)'],
[0.2222222222222222, 'rgb(244,109,67)'],
[0.3333333333333333, 'rgb(253,174,97)'],
[0.4444444444444444, 'rgb(254,224,144)'],
[0.5555555555555556, 'rgb(224,243,248)'],
[0.6666666666666666, 'rgb(171,217,233)'],
[0.7777777777777778, 'rgb(116,173,209)'],
[0.8888888888888888, 'rgb(69,117,180)'],
[1.0, 'rgb(49,54,149)']]
),
)]
if (main_graph_layout is not None and 'locked' in selector):
# print(main_graph_layout)
try:
lon = float(main_graph_layout['mapbox']['center']['lon'])
lat = float(main_graph_layout['mapbox']['center']['lat'])
zoom = float(main_graph_layout['mapbox']['zoom'])
layout['mapbox']['center']['lon'] = lon
layout['mapbox']['center']['lat'] = lat
layout['mapbox']['zoom'] = zoom
except:
print(main_graph_layout)
lon = float(main_graph_layout['mapbox.center.lon'])
lat = float(main_graph_layout['mapbox.center.lat'])
zoom = float(main_graph_layout['mapbox.zoom'])
layout['mapbox']['center']['lon'] = lon
layout['mapbox']['center']['lat'] = lat
layout['mapbox']['zoom'] = zoom
else:
lon=-98.4842,
lat=39.0119
zoom = 3
figure = dict(data=traces, layout=layout)
return figure
#Update Text on Screen
@app.callback(Output('tweet-text', 'children'),
[Input('year_slider', 'value'),
Input('individual_graph', 'selectedData'),
Input('main_graph','hoverData')])
def update_text(year_slider, hist_select, hoverData):
if hoverData is not None:
df = data.iloc[year_slider[0]:year_slider[1]]
s = df[df['clean_text'] == hoverData['points'][0]['customdata']]
return html.P(s['raw_tweet'].iloc[0])
# Slider -> year text
@app.callback(Output('year_text', 'children'),
[Input('year_slider', 'value')])
def update_year_text(year_slider):
return "Showing Tweets from {} to {}".format(''.join(data['time'].iloc[year_slider[0]].split('+0000')),
''.join(data['time'].iloc[year_slider[1]].split('+0000')))
# Slider / Selection -> individual graph
@app.callback(Output('individual_graph', 'figure'),
[Input('main_graph', 'selectedData'),
Input('year_slider', 'value')])
def make_individual_figure(main_graph_data, year_slider):
df = data.iloc[year_slider[0]:year_slider[1]]
# df2 = df1[year_slider[0]:year_slider[1],:]
layout_individual = copy.deepcopy(layout)
layout_individual['title'] = 'Histogram from index %i to %i' % (year_slider[0], year_slider[1])
layout_individual['updatemenus'] = []
# custom histogram code:
hist = np.histogram(df['score'], bins=num_bin)
traces = [dict(
hoverinfo='none',
type='bar',
x = hist[1][:-1],
y = hist[0],
marker = dict(
color = hist[1][:-1],
colorscale = [[0.0, 'rgb(165,0,38)'], [0.1111111111111111, 'rgb(215,48,39)'], [0.2222222222222222, 'rgb(244,109,67)'], [0.3333333333333333, 'rgb(253,174,97)'], [0.4444444444444444, 'rgb(254,224,144)'], [0.5555555555555556, 'rgb(224,243,248)'], [0.6666666666666666, 'rgb(171,217,233)'], [0.7777777777777778, 'rgb(116,173,209)'], [0.8888888888888888, 'rgb(69,117,180)'], [1.0, 'rgb(49,54,149)']]
),
)]
figure = dict(data=traces, layout=layout_individual)
return figure
# Main
if __name__ == '__main__':
app.run_server(debug=True)
# app.server.run( threaded=True)
| <filename>app/main.py
import base64
import json
import os
import pickle
import copy
import datetime as dt
import pandas as pd
import numpy as np
from flask import Flask
#from flask_cors import CORS
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
server = Flask(__name__)
app = dash.Dash(__name__, server=server)
#app.scripts.config.serve_locally = True
app.css.append_css({'external_url': 'https://cdn.rawgit.com/plotly/dash-app-stylesheets/2d266c578d2a6e8850ebce48fdb52759b2aef506/stylesheet-oil-and-gas.css'}) # noqa: E501
#server = app.server
#CORS(server)
#if 'DYNO' in os.environ:
# app.scripts.append_script({
# 'external_url': 'https://cdn.rawgit.com/chriddyp/ca0d8f02a1659981a0ea7f013a378bbd/raw/e79f3f789517deec58f41251f7dbb6bee72c44ab/plotly_ga.js' # noqa: E501
# })
# Create global chart template
mapbox_access_token = '<KEY>' # noqa: E501
#data = pd.read_csv("https://www.dropbox.com/s/3x1b7glfpuwn794/tweet_global_warming.csv?dl=1", encoding="latin")
data = pd.read_csv("https://www.dropbox.com/s/3a31qflbppy3ob8/sample_prediction.csv?dl=1", encoding="latin")
#data = pd.read_csv("sample_prediction.csv", encoding="latin")
#print (data['clean_text'])
#Change size of points
data['score'] = data['positive']-data['negative']
data['var_mean'] = np.sqrt(data['retweets']/data['retweets'].max())*20
sizes = data['var_mean']+4 # 4 is the smallest size a point can be
num_bin = 50
bin_width = 2/num_bin
#twit image
img = base64.b64encode(open('twit.png', 'rb').read())
layout = dict(
autosize=True,
height=800,
font=dict(color='#CCCCCC'),
titlefont=dict(color='#CCCCCC', size='14'),
margin=dict(
l=35,
r=35,
b=35,
t=45
),
hovermode="closest",
plot_bgcolor="#191A1A",
paper_bgcolor="#020202",
legend=dict(font=dict(size=10), orientation='h'),
title='Satellite Overview',
mapbox=dict(
accesstoken=mapbox_access_token,
style="dark",
center=dict(
lon=-98.4842,
lat=39.0119
),
zoom=3,
),
updatemenus= [
dict(
buttons=([
dict(
args=[{
'mapbox.zoom': 3,
'mapbox.center.lon': '-98.4842',
'mapbox.center.lat': '39.0119',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Reset Zoom',
method='relayout'
)
]),
direction='left',
pad={'r': 0, 't': 0, 'b': 0, 'l': 0},
showactive=False,
type='buttons',
x=0.45,
xanchor='left',
yanchor='bottom',
bgcolor='#323130',
borderwidth=1,
bordercolor="#6d6d6d",
font=dict(
color="#FFFFFF"
),
y=0.02
),
dict(
buttons=([
dict(
args=[{
'mapbox.zoom': 8,
'mapbox.center.lon': '-95.3698',
'mapbox.center.lat': '29.7604',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Houston',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 8,
'mapbox.center.lon': '-87.6298',
'mapbox.center.lat': '41.8781',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Chicago',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 5,
'mapbox.center.lon': '-86.9023',
'mapbox.center.lat': '32.3182',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Alabama',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 8,
'mapbox.center.lon': '-74.0113',
'mapbox.center.lat': '40.7069',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='New York City',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 8,
'mapbox.center.lon': '-122.3321',
'mapbox.center.lat': '47.6062',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Seattle',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 7,
'mapbox.center.lon': '-118.2437',
'mapbox.center.lat': '34.0522',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Los Angeles',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 5,
'mapbox.center.lon': '-86.5804',
'mapbox.center.lat': '35.5175',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='Tennessee',
method='relayout'
),
dict(
args=[{
'mapbox.zoom': 5,
'mapbox.center.lon': '-3.4360',
'mapbox.center.lat': '55.3781',
'mapbox.bearing': 0,
'mapbox.style': 'dark'
}],
label='UK',
method='relayout'
)
]),
direction="down",
pad={'r': 0, 't': 0, 'b': 0, 'l': 0},
showactive=False,
bgcolor="rgb(50, 49, 48, 0)",
type='buttons',
yanchor='bottom',
xanchor='left',
font=dict(
color="#FFFFFF"
),
x=0,
y=0.05
)
]
)
# Create app layout
app.layout = html.Div([
html.Div([
html.H1(
'WYNS',
#className='eight columns',
),
html.H4(
'Use our tools to explore tweets on climate change from around the world!'),
html.Br(),
],
className='row'
),
html.Div([
html.Img(src='data:image/png;base64,{}'.format(img.decode())),
],
style={
'minHeight':'100px'},
className='one columns'
),
html.Div([
html.Div(id='tweet-text')
],
style={
#'color':'blue',
'fontSize':18,
#'columnCount':2,
'minHeight':'100px'},
className='eight columns'
),
html.Div([
html.P(
id='year_text',
style={'text-align': 'right'}
),
],
className='two columns'
),
html.Div([
html.Br(),
html.P('Filter by Date:'),
dcc.RangeSlider(
id='year_slider',
min=0,
max=len(data),
value=[len(data)//10,len(data)*2//10],
marks={
0: data['time'].min(),
len(data): data['time'].max()
}
),
html.Br(),
],
className='twelve columns',
id='slider_holder'
),
html.Div([
dcc.Checklist(
id='lock_selector',
options=[
{'label': 'Lock camera', 'value': 'locked'}
],
values=[],
),
# html.Button('Reload Data', id='button'),
# html.Div(id='hidden_div')
],
style={'margin-top': '20'},
className='eight columns'
),
html.Div(
[
html.Div(
[
dcc.Graph(id='main_graph')
],
className='eight columns',
style={'margin-top': '20'}
),
html.Div(
[
dcc.Graph(id='individual_graph')
],
className='four columns',
style={'margin-top': '20'}
),
],
className='row'
),
],
className='ten columns offset-by-one'
)
# functions that help with cleaning / filtering data
TWIT_TYPES = dict(
Yes = '#76acf2',
Y = '#76acf2',
No = '#e85353',
N = '#e85353',
unrelated = '#efe98d'
)
def filter_data(df, slider):
return
# function that reloads the data
#@app.callback(Output('slider_holder','children'),[Input('button','n_clicks')])
#def fetch_data(n_clicks):
# print(n_clicks)
# if n_clicks is not None:
# data = pd.read_csv("https://www.dropbox.com/s/3a31qflbppy3ob8/sample_prediction.csv?dl=1", encoding="latin")
# #data = pd.read_csv("sample_prediction.csv", encoding="latin")
# #print (data['clean_text'])
#
# #Change size of points
# data['score'] = data['positive']-data['negative']
# data['var_mean'] = np.sqrt(data['retweets']/data['retweets'].max())*20
# sizes = data['var_mean']+4
# print(len(data))
## return html.Div([])
# return html.Div([
# html.Br(),
# html.P('Filter by Date:'),
# dcc.RangeSlider(
# id='year_slider',
# min=0,
# max=len(data),
# value=[len(data)//10,len(data)*2//10],
# marks={
# 0: data['time'].min(),
# len(data): data['time'].max()
# }
# ),
# html.Br(),
# ],
# className='twelve columns',
# id='slider_holder'
# )
# else:
# return html.Div([
# html.Br(),
# html.P('Filter by Date:'),
# dcc.RangeSlider(
# id='year_slider',
# min=0,
# max=len(data),
# value=[len(data)//10,len(data)*2//10],
# marks={
# 0: data['time'].min(),
# len(data): data['time'].max()
# }
# ),
# html.Br(),
# ],
# className='twelve columns',
# id='slider_holder'
# )
# start the callbacks
# Main Graph -> update
# the below code uses a heatmap to render the data points
@app.callback(Output('main_graph', 'figure'),
[Input('year_slider', 'value'),
Input('individual_graph', 'selectedData')],
[State('lock_selector', 'values'),
State('main_graph', 'relayoutData')])
def make_main_figure(year_slider, hist_select, selector, main_graph_layout):
###slect first thingy in json and grab x as min
###slelect last thingy in json and grab x as max
####return that cheese to the filter function as [min, max]
###we'll call that funciton in the main graph callback
####and then business as usuall.....
df = data.iloc[year_slider[0]:year_slider[1]]
if hist_select:
min_heat = hist_select['points'][0]['x']
max_heat = hist_select['points'][-1]['x'] + bin_width
# change this if you change bin size doood
dff = df[df['score'] > min_heat]
df = dff[dff['score'] < max_heat]
traces = [dict(
type='scattermapbox',
lon = df['long'],
lat = df['lat'],
#text='can customize text',
customdata = df['clean_text'],
name = df['score'],
marker=dict(
size=sizes,
opacity=0.8,
color = df['score'],
cmin=-1,
cmax=1,
colorbar = dict(
title='Belief'
),
colorscale = [[0.0, 'rgb(165,0,38)'],
[0.1111111111111111, 'rgb(215,48,39)'],
[0.2222222222222222, 'rgb(244,109,67)'],
[0.3333333333333333, 'rgb(253,174,97)'],
[0.4444444444444444, 'rgb(254,224,144)'],
[0.5555555555555556, 'rgb(224,243,248)'],
[0.6666666666666666, 'rgb(171,217,233)'],
[0.7777777777777778, 'rgb(116,173,209)'],
[0.8888888888888888, 'rgb(69,117,180)'],
[1.0, 'rgb(49,54,149)']]
),
)]
if (main_graph_layout is not None and 'locked' in selector):
# print(main_graph_layout)
try:
lon = float(main_graph_layout['mapbox']['center']['lon'])
lat = float(main_graph_layout['mapbox']['center']['lat'])
zoom = float(main_graph_layout['mapbox']['zoom'])
layout['mapbox']['center']['lon'] = lon
layout['mapbox']['center']['lat'] = lat
layout['mapbox']['zoom'] = zoom
except:
print(main_graph_layout)
lon = float(main_graph_layout['mapbox.center.lon'])
lat = float(main_graph_layout['mapbox.center.lat'])
zoom = float(main_graph_layout['mapbox.zoom'])
layout['mapbox']['center']['lon'] = lon
layout['mapbox']['center']['lat'] = lat
layout['mapbox']['zoom'] = zoom
else:
lon=-98.4842,
lat=39.0119
zoom = 3
figure = dict(data=traces, layout=layout)
return figure
#Update Text on Screen
@app.callback(Output('tweet-text', 'children'),
[Input('year_slider', 'value'),
Input('individual_graph', 'selectedData'),
Input('main_graph','hoverData')])
def update_text(year_slider, hist_select, hoverData):
if hoverData is not None:
df = data.iloc[year_slider[0]:year_slider[1]]
s = df[df['clean_text'] == hoverData['points'][0]['customdata']]
return html.P(s['raw_tweet'].iloc[0])
# Slider -> year text
@app.callback(Output('year_text', 'children'),
[Input('year_slider', 'value')])
def update_year_text(year_slider):
return "Showing Tweets from {} to {}".format(''.join(data['time'].iloc[year_slider[0]].split('+0000')),
''.join(data['time'].iloc[year_slider[1]].split('+0000')))
# Slider / Selection -> individual graph
@app.callback(Output('individual_graph', 'figure'),
[Input('main_graph', 'selectedData'),
Input('year_slider', 'value')])
def make_individual_figure(main_graph_data, year_slider):
df = data.iloc[year_slider[0]:year_slider[1]]
# df2 = df1[year_slider[0]:year_slider[1],:]
layout_individual = copy.deepcopy(layout)
layout_individual['title'] = 'Histogram from index %i to %i' % (year_slider[0], year_slider[1])
layout_individual['updatemenus'] = []
# custom histogram code:
hist = np.histogram(df['score'], bins=num_bin)
traces = [dict(
hoverinfo='none',
type='bar',
x = hist[1][:-1],
y = hist[0],
marker = dict(
color = hist[1][:-1],
colorscale = [[0.0, 'rgb(165,0,38)'], [0.1111111111111111, 'rgb(215,48,39)'], [0.2222222222222222, 'rgb(244,109,67)'], [0.3333333333333333, 'rgb(253,174,97)'], [0.4444444444444444, 'rgb(254,224,144)'], [0.5555555555555556, 'rgb(224,243,248)'], [0.6666666666666666, 'rgb(171,217,233)'], [0.7777777777777778, 'rgb(116,173,209)'], [0.8888888888888888, 'rgb(69,117,180)'], [1.0, 'rgb(49,54,149)']]
),
)]
figure = dict(data=traces, layout=layout_individual)
return figure
# Main
if __name__ == '__main__':
app.run_server(debug=True)
# app.server.run( threaded=True)
| en | 0.393073 | #from flask_cors import CORS #app.scripts.config.serve_locally = True # noqa: E501 #server = app.server #CORS(server) #if 'DYNO' in os.environ: # app.scripts.append_script({ # 'external_url': 'https://cdn.rawgit.com/chriddyp/ca0d8f02a1659981a0ea7f013a378bbd/raw/e79f3f789517deec58f41251f7dbb6bee72c44ab/plotly_ga.js' # noqa: E501 # }) # Create global chart template # noqa: E501 #data = pd.read_csv("https://www.dropbox.com/s/3x1b7glfpuwn794/tweet_global_warming.csv?dl=1", encoding="latin") #data = pd.read_csv("sample_prediction.csv", encoding="latin") #print (data['clean_text']) #Change size of points # 4 is the smallest size a point can be #twit image # Create app layout #className='eight columns', #'color':'blue', #'columnCount':2, # html.Button('Reload Data', id='button'), # html.Div(id='hidden_div') # functions that help with cleaning / filtering data # function that reloads the data #@app.callback(Output('slider_holder','children'),[Input('button','n_clicks')]) #def fetch_data(n_clicks): # print(n_clicks) # if n_clicks is not None: # data = pd.read_csv("https://www.dropbox.com/s/3a31qflbppy3ob8/sample_prediction.csv?dl=1", encoding="latin") # #data = pd.read_csv("sample_prediction.csv", encoding="latin") # #print (data['clean_text']) # # #Change size of points # data['score'] = data['positive']-data['negative'] # data['var_mean'] = np.sqrt(data['retweets']/data['retweets'].max())*20 # sizes = data['var_mean']+4 # print(len(data)) ## return html.Div([]) # return html.Div([ # html.Br(), # html.P('Filter by Date:'), # dcc.RangeSlider( # id='year_slider', # min=0, # max=len(data), # value=[len(data)//10,len(data)*2//10], # marks={ # 0: data['time'].min(), # len(data): data['time'].max() # } # ), # html.Br(), # ], # className='twelve columns', # id='slider_holder' # ) # else: # return html.Div([ # html.Br(), # html.P('Filter by Date:'), # dcc.RangeSlider( # id='year_slider', # min=0, # max=len(data), # value=[len(data)//10,len(data)*2//10], # marks={ # 0: data['time'].min(), # len(data): data['time'].max() # } # ), # html.Br(), # ], # className='twelve columns', # id='slider_holder' # ) # start the callbacks # Main Graph -> update # the below code uses a heatmap to render the data points ###slect first thingy in json and grab x as min ###slelect last thingy in json and grab x as max ####return that cheese to the filter function as [min, max] ###we'll call that funciton in the main graph callback ####and then business as usuall..... # change this if you change bin size doood #text='can customize text', # print(main_graph_layout) #Update Text on Screen # Slider -> year text # Slider / Selection -> individual graph # df2 = df1[year_slider[0]:year_slider[1],:] # custom histogram code: # Main # app.server.run( threaded=True) | 2.520674 | 3 |
generate_calibration_checkerboard.py | Jichao-Wang/Calibration_ZhangZhengyou_Method | 2 | 6622304 | <reponame>Jichao-Wang/Calibration_ZhangZhengyou_Method
import cv2
import numpy as np
cube = 90
row_corner = 9
col_corner = 12
img = np.zeros((row_corner * cube, col_corner * cube, 1), dtype="uint8")
for i in range(img.shape[0]):
for j in range(img.shape[1]):
img[i, j] = 255
if (int(i / cube) % 2 == 0) and (int(j / cube) % 2 == 0):
img[i, j] = 0
if (int(i / cube) % 2 == 1) and (int(j / cube) % 2 == 1):
img[i, j] = 0
cv2.imwrite("board.jpg", img)
| import cv2
import numpy as np
cube = 90
row_corner = 9
col_corner = 12
img = np.zeros((row_corner * cube, col_corner * cube, 1), dtype="uint8")
for i in range(img.shape[0]):
for j in range(img.shape[1]):
img[i, j] = 255
if (int(i / cube) % 2 == 0) and (int(j / cube) % 2 == 0):
img[i, j] = 0
if (int(i / cube) % 2 == 1) and (int(j / cube) % 2 == 1):
img[i, j] = 0
cv2.imwrite("board.jpg", img) | none | 1 | 2.833773 | 3 | |
jh_server/apps/jidou_hikki/utils/demo.py | agent-whisper/Jidou-Hikki-Django | 0 | 6622305 | <gh_stars>0
import logging
from typing import Dict, Tuple, List
import jamdict
from jamdict import Jamdict
from ..tokenizer import get_tokenizer
from ..tokenizer.base import Token
from ..tokenizer.sudachi import MODE_B
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
_TOKENIZER = get_tokenizer()
_DICTIONARY = Jamdict()
class DryVocabulary:
"""
Pseuodo Vocabulary model without DB connection.
"""
def __init__(self, *args, **kwargs):
self.dict_id = kwargs.get("idseq")
self.word = kwargs.get("word")
self.kanji = kwargs.get("kanji")
self.furigana = kwargs.get("furigana")
self.okurigana = kwargs.get("okurigana")
self.reading = kwargs.get("reading_form")
self._jmd_lookup = kwargs.get("jmd_lookup")
def __str__(self):
return f"{self.word}"
def as_token(self) -> Token:
token = _TOKENIZER.tokenize_text(self.word)
return token[0] if token else None
def as_html(self) -> str:
token = self.as_token()
return token.as_html() if token else ""
@property
def jmdict(self) -> jamdict.util.LookupResult:
if not self._jmd_lookup:
self._jmd_lookup = _DICTIONARY.lookup(f"id#{self.dict_id}")
return self._jmd_lookup
def as_text(self) -> str:
if self.kanji:
return self._reading_template.format(
first=self.furigana,
second=("." + self.okurigana) if self.okurigana else "",
)
return self.word
def token_2_vocab(token) -> Tuple[List[DryVocabulary], List[str]]:
vocabs = []
failed = []
normalized_tokens = _TOKENIZER.normalize_token(token)
logger.debug(f"Normalized {token} -> {normalized_tokens}")
for normalized_tkn in normalized_tokens:
# Assume the first entry to be the best match
jmd_info = _DICTIONARY.lookup(normalized_tkn.word)
if len(jmd_info.entries) > 0:
# Some tokens may be a set of expressions, and not available in
# JMDict. Example cases:
# - キャラ作り
jmd_entry = jmd_info.entries[0]
vocabs.append(
DryVocabulary(
dict_id=jmd_entry.idseq,
word=normalized_tkn.word,
kanji=normalized_tkn.kanji,
furigana=normalized_tkn.furigana,
okurigana=normalized_tkn.okurigana,
reading=normalized_tkn.reading_form,
jmd_lookup=jmd_info,
)
)
else:
failed.append(normalized_tkn.word)
logger.error(
f"Cannot process ({token} -> {normalized_tkn}) into vocabulary."
)
return vocabs, failed
def analyze_text(text: str) -> Tuple[str, List[DryVocabulary], List[str]]:
"""Similar to NotePage.analyze(), but returns the HTML text and list of DryVocabulary."""
lines = text.split("\n")
html_lines = []
vocabularies = []
failed_analysis = []
for line in lines:
if line:
tokens = _TOKENIZER.tokenize_text(line.strip(), MODE_B)
for tkn in tokens:
if tkn.contains_kanji():
vocabs, failed = token_2_vocab(tkn)
failed_analysis += failed
vocabularies += vocabs
html = [tkn.as_html() for tkn in tokens]
html_lines.append("".join(html))
return "<br>".join(html_lines), vocabularies, failed_analysis
| import logging
from typing import Dict, Tuple, List
import jamdict
from jamdict import Jamdict
from ..tokenizer import get_tokenizer
from ..tokenizer.base import Token
from ..tokenizer.sudachi import MODE_B
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
_TOKENIZER = get_tokenizer()
_DICTIONARY = Jamdict()
class DryVocabulary:
"""
Pseuodo Vocabulary model without DB connection.
"""
def __init__(self, *args, **kwargs):
self.dict_id = kwargs.get("idseq")
self.word = kwargs.get("word")
self.kanji = kwargs.get("kanji")
self.furigana = kwargs.get("furigana")
self.okurigana = kwargs.get("okurigana")
self.reading = kwargs.get("reading_form")
self._jmd_lookup = kwargs.get("jmd_lookup")
def __str__(self):
return f"{self.word}"
def as_token(self) -> Token:
token = _TOKENIZER.tokenize_text(self.word)
return token[0] if token else None
def as_html(self) -> str:
token = self.as_token()
return token.as_html() if token else ""
@property
def jmdict(self) -> jamdict.util.LookupResult:
if not self._jmd_lookup:
self._jmd_lookup = _DICTIONARY.lookup(f"id#{self.dict_id}")
return self._jmd_lookup
def as_text(self) -> str:
if self.kanji:
return self._reading_template.format(
first=self.furigana,
second=("." + self.okurigana) if self.okurigana else "",
)
return self.word
def token_2_vocab(token) -> Tuple[List[DryVocabulary], List[str]]:
vocabs = []
failed = []
normalized_tokens = _TOKENIZER.normalize_token(token)
logger.debug(f"Normalized {token} -> {normalized_tokens}")
for normalized_tkn in normalized_tokens:
# Assume the first entry to be the best match
jmd_info = _DICTIONARY.lookup(normalized_tkn.word)
if len(jmd_info.entries) > 0:
# Some tokens may be a set of expressions, and not available in
# JMDict. Example cases:
# - キャラ作り
jmd_entry = jmd_info.entries[0]
vocabs.append(
DryVocabulary(
dict_id=jmd_entry.idseq,
word=normalized_tkn.word,
kanji=normalized_tkn.kanji,
furigana=normalized_tkn.furigana,
okurigana=normalized_tkn.okurigana,
reading=normalized_tkn.reading_form,
jmd_lookup=jmd_info,
)
)
else:
failed.append(normalized_tkn.word)
logger.error(
f"Cannot process ({token} -> {normalized_tkn}) into vocabulary."
)
return vocabs, failed
def analyze_text(text: str) -> Tuple[str, List[DryVocabulary], List[str]]:
"""Similar to NotePage.analyze(), but returns the HTML text and list of DryVocabulary."""
lines = text.split("\n")
html_lines = []
vocabularies = []
failed_analysis = []
for line in lines:
if line:
tokens = _TOKENIZER.tokenize_text(line.strip(), MODE_B)
for tkn in tokens:
if tkn.contains_kanji():
vocabs, failed = token_2_vocab(tkn)
failed_analysis += failed
vocabularies += vocabs
html = [tkn.as_html() for tkn in tokens]
html_lines.append("".join(html))
return "<br>".join(html_lines), vocabularies, failed_analysis | en | 0.615992 | Pseuodo Vocabulary model without DB connection. #{self.dict_id}") # Assume the first entry to be the best match # Some tokens may be a set of expressions, and not available in # JMDict. Example cases: # - キャラ作り Similar to NotePage.analyze(), but returns the HTML text and list of DryVocabulary. | 2.208233 | 2 |
tests/tests.py | dalemyers/libmonzo | 7 | 6622306 | #!/usr/bin/env python3
"""Tests for the package."""
#pylint: disable=line-too-long
import filecmp
import json
import os
import random
import sys
import tempfile
from typing import ClassVar, Dict
import unittest
import uuid
import requests
sys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..")))
#pylint: disable=wrong-import-position
import libmonzo
#pylint: enable=wrong-import-position
class LibMonzoTests(unittest.TestCase):
"""Test the library."""
config: ClassVar[Dict[str, str]]
client: ClassVar[libmonzo.MonzoClient]
@classmethod
def setUpClass(cls):
cls.config = LibMonzoTests.load_configuration()
cls.client = libmonzo.MonzoClient(cls.config["client_id"], cls.config["owner_id"], cls.config["client_secret"])
#cls.client.authenticate()
#print(cls.client.access_token)
cls.client.access_token = cls.config["access_token"]
@staticmethod
def load_configuration() -> Dict[str, str]:
"""Load the configuration."""
config_path = os.path.expanduser("~/.libmonzo")
with open(config_path, 'r') as config_file:
return json.load(config_file)
def test_who_am_i(self):
"""Test whoami."""
whoami = LibMonzoTests.client.whoami()
self.assertTrue(isinstance(whoami, libmonzo.types.WhoAmI))
self.assertTrue(whoami.authenticated)
self.assertEqual(LibMonzoTests.config["user_id"], whoami.user_id)
self.assertEqual(LibMonzoTests.config["client_id"], whoami.client_id)
def test_accounts(self):
"""Test accounts."""
accounts = LibMonzoTests.client.accounts()
expected_accounts = LibMonzoTests.config["accounts"]
self.assertTrue(len(accounts) == len(expected_accounts))
for account in accounts:
matching_account_dict = None
matching_account = None
for expected_account in expected_accounts:
if account.identifier == expected_account["id"]:
matching_account_dict = expected_account
break
self.assertIsNotNone(matching_account_dict, f"Failed to find matching account for ID: {account.identifier}")
matching_account = libmonzo.types.Account.from_json(matching_account_dict)[0]
self.assertEqual(account.identifier, matching_account.identifier)
self.assertEqual(account.description, matching_account.description)
self.assertEqual(account.created, matching_account.created)
self.assertEqual(account.is_closed, matching_account.is_closed)
self.assertEqual(account.account_type, matching_account.account_type)
self.assertEqual(account.owners, matching_account.owners)
self.assertEqual(account.account_number, matching_account.account_number)
self.assertEqual(account.sort_code, matching_account.sort_code)
self.assertEqual(account, matching_account)
def test_balances(self):
"""Test balances."""
accounts = LibMonzoTests.client.accounts()
for account in accounts:
balance = LibMonzoTests.client.balance(account_id=account.identifier)
self.assertIsNotNone(balance)
self.assertTrue(balance.currency == "GBP")
def test_pots(self):
"""Test pots."""
pots = LibMonzoTests.client.pots()
expected_pots = LibMonzoTests.config["pots"]
self.assertTrue(len(pots) == len(expected_pots))
for pot in pots:
matching_pot_dict = None
matching_pot = None
for expected_pot in expected_pots:
if pot.identifier == expected_pot["id"]:
matching_pot_dict = expected_pot
break
self.assertIsNotNone(matching_pot_dict, f"Failed to find matching pot for ID: {pot.identifier}")
matching_pot = libmonzo.types.Pot.from_json(matching_pot_dict)[0]
self.assertEqual(pot.identifier, matching_pot.identifier)
self.assertEqual(pot.name, matching_pot.name)
self.assertEqual(pot.style, matching_pot.style)
self.assertEqual(pot.currency, matching_pot.currency)
self.assertEqual(pot.round_up, matching_pot.round_up)
self.assertEqual(pot.created, matching_pot.created)
self.assertEqual(pot.deleted, matching_pot.deleted)
def test_pot_deposit(self):
"""Test pot depositing/withdrawing."""
account_id = LibMonzoTests.config["test_account_id"]
pot_id = LibMonzoTests.config["pot_deposit_pot_id"]
perform_disruptive_tests = LibMonzoTests.config["perform_disruptive_tests"]
if not perform_disruptive_tests:
return
initial_pot = [pot for pot in LibMonzoTests.client.pots() if pot.identifier == pot_id][0]
initial_account = [account for account in LibMonzoTests.client.accounts() if account.identifier == account_id][0]
initial_account_balance = LibMonzoTests.client.balance(account_id=initial_account.identifier)
# Perform the deposit (1 penny)
LibMonzoTests.client.deposit_into_pot(pot_id=initial_pot.identifier, source_account_id=initial_account.identifier, amount=1)
# Get the pot and account again
mid_pot = [pot for pot in LibMonzoTests.client.pots() if pot.identifier == pot_id][0]
mid_account = [account for account in LibMonzoTests.client.accounts() if account.identifier == account_id][0]
mid_account_balance = LibMonzoTests.client.balance(account_id=mid_account.identifier)
# Check the values
self.assertTrue(mid_pot.balance == initial_pot.balance + 1)
self.assertTrue(mid_account_balance.balance == initial_account_balance.balance - 1)
self.assertTrue(mid_account_balance.total_balance == initial_account_balance.total_balance)
# Now do the transfer the other way
LibMonzoTests.client.withdraw_from_pot(pot_id=initial_pot.identifier, destination_account_id=initial_account.identifier, amount=1)
# Get the pot and account again
post_pot = [pot for pot in LibMonzoTests.client.pots() if pot.identifier == pot_id][0]
post_account = [account for account in LibMonzoTests.client.accounts() if account.identifier == account_id][0]
post_account_balance = LibMonzoTests.client.balance(account_id=post_account.identifier)
# Check the values
self.assertTrue(post_pot.balance == mid_pot.balance - 1)
self.assertTrue(post_pot.balance == initial_pot.balance)
self.assertTrue(post_account_balance.balance == mid_account_balance.balance + 1)
self.assertTrue(post_account_balance.balance == initial_account_balance.balance)
def test_transactions(self):
"""Test transactions."""
accounts = LibMonzoTests.client.accounts()
for account in accounts:
transactions = LibMonzoTests.client.transactions(account_id=account.identifier)
self.assertIsNotNone(transactions)
transaction = random.choice(transactions)
detailed_transaction = LibMonzoTests.client.transaction(identifier=transaction.identifier)
self.assertEqual(detailed_transaction.identifier, transaction.identifier)
def test_annotations(self):
"""Test annotating transactions."""
perform_annotations_test = LibMonzoTests.config["perform_annotations_test"]
if not perform_annotations_test:
return
account_id = LibMonzoTests.config["test_account_id"]
transactions = LibMonzoTests.client.transactions(account_id=account_id)
transaction = random.choice(transactions)
annotation_key = "libmonzo_annotation_test"
annotation_value = "1"
# Add an annotation to the transaction
LibMonzoTests.client.annotate_transaction(
identifier=transaction.identifier,
key=annotation_key,
value=annotation_value
)
# Read it back to confirm it worked
annotated_transaction = LibMonzoTests.client.transaction(identifier=transaction.identifier)
metadata = annotated_transaction.raw_data.get("metadata")
self.assertIsNotNone(metadata)
self.assertEqual(metadata.get(annotation_key), annotation_value)
# Remove the annotation
LibMonzoTests.client.remove_transaction_annotation(
identifier=transaction.identifier,
key=annotation_key
)
# Read it back to confirm it worked
cleared_transaction = LibMonzoTests.client.transaction(identifier=transaction.identifier)
with self.assertRaises(ValueError):
_ = cleared_transaction.raw_data["metadata"][annotation_key]
def test_add_feed_item(self):
"""Test adding a feed item."""
perform_disruptive_tests = LibMonzoTests.config["perform_disruptive_tests"]
if not perform_disruptive_tests:
return
account_id = LibMonzoTests.config["test_account_id"]
try:
LibMonzoTests.client.create_feed_item(
account_id=account_id,
title="Hello world",
image_url="http://via.placeholder.com/64x64?text=X",
background_color=libmonzo.types.Color(hex_code="#000088"),
title_color=libmonzo.types.Color(hex_code="#FFFFFF"),
body_color=libmonzo.types.Color(hex_code="#AAAAAA"),
body="This is a feed test",
url="https://google.com"
)
except libmonzo.exceptions.MonzoAPIError as ex:
self.fail(f"Exception was raised: {ex}")
def test_attachment_registration(self):
"""Test adding an attachment"""
identifier = LibMonzoTests.config["attachment_transaction_id"]
# Get the transaction
transaction = LibMonzoTests.client.transaction(identifier=identifier)
try:
# Confirm there are no attachments:
self.assertEqual(0, len(transaction.attachments))
# Register the attachment
LibMonzoTests.client.register_attachment(
transaction_id=transaction.identifier,
url="http://via.placeholder.com/400x400?text=Transaction%20Sample%20Attachment",
mime_type="image/png"
)
# Confirm there is 1 attachment:
transaction = LibMonzoTests.client.transaction(identifier=identifier)
self.assertEqual(1, len(transaction.attachments))
finally:
# Unregister the attachments
for attachment in transaction.attachments:
LibMonzoTests.client.unregister_attachment(attachment_id=attachment.identifier)
# Confirm there are no attachments:
transaction = LibMonzoTests.client.transaction(identifier=identifier)
self.assertEqual(0, len(transaction.attachments))
def test_upload_attachment(self):
"""Test uploading an attachment"""
perform_attachment_upload_test = LibMonzoTests.config["perform_attachment_upload_test"]
if not perform_attachment_upload_test:
return
file_path = os.path.realpath(__file__)
folder_path = os.path.dirname(file_path)
image_path = os.path.join(folder_path, "upload_sample.png")
attachment_url = LibMonzoTests.client.upload_attachment(file_path=image_path, mime_type="image/png")
temp_name = str(uuid.uuid4()) + ".png"
temp_location = os.path.join(tempfile.gettempdir(), temp_name)
response = requests.get(attachment_url)
with open(temp_location, 'wb') as temp_file:
temp_file.write(response.content)
try:
self.assertTrue(filecmp.cmp(temp_location, image_path))
finally:
os.remove(temp_location)
def test_webhooks(self):
"""Test webhooks."""
account_id = LibMonzoTests.config["test_account_id"]
# Get the current hooks
current_hooks = LibMonzoTests.client.list_webhooks(account_id=account_id)
# Register a new hook
created_hook = LibMonzoTests.client.register_webhook(account_id=account_id, url="https://example.com")
# Get the latest hooks
new_hooks = LibMonzoTests.client.list_webhooks(account_id=account_id)
# Confirm that the old ones are there
for old_hook in current_hooks:
# Try and find the old hook in the new ones
found_previous = False
for new_hook in new_hooks:
if new_hook.identifier == old_hook.identifier:
found_previous = True
break
self.assertTrue(found_previous, "Failed to find previous hook")
# Confirm that the new one is there
found_new_hook = False
for hook in new_hooks:
if hook.identifier == created_hook.identifier:
found_new_hook = True
break
self.assertTrue(found_new_hook, "Failed to find new hook")
# Finally we can delete it
LibMonzoTests.client.delete_webhook(webhook_id=created_hook.identifier)
final_hooks = LibMonzoTests.client.list_webhooks(account_id=account_id)
# Confirm that our old ones are still there
for old_hook in current_hooks:
# Try and find the old hook in the new ones
found_previous = False
for final_hook in final_hooks:
if final_hook.identifier == old_hook.identifier:
found_previous = True
break
self.assertTrue(found_previous, "Failed to find previous hook")
# Confirm that the new one is NOT there
found_new_hook = False
for hook in final_hooks:
if hook.identifier == created_hook.identifier:
found_new_hook = True
break
self.assertFalse(found_new_hook, "Found new hook after deletion")
if __name__ == "__main__":
unittest.main(verbosity=2)
| #!/usr/bin/env python3
"""Tests for the package."""
#pylint: disable=line-too-long
import filecmp
import json
import os
import random
import sys
import tempfile
from typing import ClassVar, Dict
import unittest
import uuid
import requests
sys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..")))
#pylint: disable=wrong-import-position
import libmonzo
#pylint: enable=wrong-import-position
class LibMonzoTests(unittest.TestCase):
"""Test the library."""
config: ClassVar[Dict[str, str]]
client: ClassVar[libmonzo.MonzoClient]
@classmethod
def setUpClass(cls):
cls.config = LibMonzoTests.load_configuration()
cls.client = libmonzo.MonzoClient(cls.config["client_id"], cls.config["owner_id"], cls.config["client_secret"])
#cls.client.authenticate()
#print(cls.client.access_token)
cls.client.access_token = cls.config["access_token"]
@staticmethod
def load_configuration() -> Dict[str, str]:
"""Load the configuration."""
config_path = os.path.expanduser("~/.libmonzo")
with open(config_path, 'r') as config_file:
return json.load(config_file)
def test_who_am_i(self):
"""Test whoami."""
whoami = LibMonzoTests.client.whoami()
self.assertTrue(isinstance(whoami, libmonzo.types.WhoAmI))
self.assertTrue(whoami.authenticated)
self.assertEqual(LibMonzoTests.config["user_id"], whoami.user_id)
self.assertEqual(LibMonzoTests.config["client_id"], whoami.client_id)
def test_accounts(self):
"""Test accounts."""
accounts = LibMonzoTests.client.accounts()
expected_accounts = LibMonzoTests.config["accounts"]
self.assertTrue(len(accounts) == len(expected_accounts))
for account in accounts:
matching_account_dict = None
matching_account = None
for expected_account in expected_accounts:
if account.identifier == expected_account["id"]:
matching_account_dict = expected_account
break
self.assertIsNotNone(matching_account_dict, f"Failed to find matching account for ID: {account.identifier}")
matching_account = libmonzo.types.Account.from_json(matching_account_dict)[0]
self.assertEqual(account.identifier, matching_account.identifier)
self.assertEqual(account.description, matching_account.description)
self.assertEqual(account.created, matching_account.created)
self.assertEqual(account.is_closed, matching_account.is_closed)
self.assertEqual(account.account_type, matching_account.account_type)
self.assertEqual(account.owners, matching_account.owners)
self.assertEqual(account.account_number, matching_account.account_number)
self.assertEqual(account.sort_code, matching_account.sort_code)
self.assertEqual(account, matching_account)
def test_balances(self):
"""Test balances."""
accounts = LibMonzoTests.client.accounts()
for account in accounts:
balance = LibMonzoTests.client.balance(account_id=account.identifier)
self.assertIsNotNone(balance)
self.assertTrue(balance.currency == "GBP")
def test_pots(self):
"""Test pots."""
pots = LibMonzoTests.client.pots()
expected_pots = LibMonzoTests.config["pots"]
self.assertTrue(len(pots) == len(expected_pots))
for pot in pots:
matching_pot_dict = None
matching_pot = None
for expected_pot in expected_pots:
if pot.identifier == expected_pot["id"]:
matching_pot_dict = expected_pot
break
self.assertIsNotNone(matching_pot_dict, f"Failed to find matching pot for ID: {pot.identifier}")
matching_pot = libmonzo.types.Pot.from_json(matching_pot_dict)[0]
self.assertEqual(pot.identifier, matching_pot.identifier)
self.assertEqual(pot.name, matching_pot.name)
self.assertEqual(pot.style, matching_pot.style)
self.assertEqual(pot.currency, matching_pot.currency)
self.assertEqual(pot.round_up, matching_pot.round_up)
self.assertEqual(pot.created, matching_pot.created)
self.assertEqual(pot.deleted, matching_pot.deleted)
def test_pot_deposit(self):
"""Test pot depositing/withdrawing."""
account_id = LibMonzoTests.config["test_account_id"]
pot_id = LibMonzoTests.config["pot_deposit_pot_id"]
perform_disruptive_tests = LibMonzoTests.config["perform_disruptive_tests"]
if not perform_disruptive_tests:
return
initial_pot = [pot for pot in LibMonzoTests.client.pots() if pot.identifier == pot_id][0]
initial_account = [account for account in LibMonzoTests.client.accounts() if account.identifier == account_id][0]
initial_account_balance = LibMonzoTests.client.balance(account_id=initial_account.identifier)
# Perform the deposit (1 penny)
LibMonzoTests.client.deposit_into_pot(pot_id=initial_pot.identifier, source_account_id=initial_account.identifier, amount=1)
# Get the pot and account again
mid_pot = [pot for pot in LibMonzoTests.client.pots() if pot.identifier == pot_id][0]
mid_account = [account for account in LibMonzoTests.client.accounts() if account.identifier == account_id][0]
mid_account_balance = LibMonzoTests.client.balance(account_id=mid_account.identifier)
# Check the values
self.assertTrue(mid_pot.balance == initial_pot.balance + 1)
self.assertTrue(mid_account_balance.balance == initial_account_balance.balance - 1)
self.assertTrue(mid_account_balance.total_balance == initial_account_balance.total_balance)
# Now do the transfer the other way
LibMonzoTests.client.withdraw_from_pot(pot_id=initial_pot.identifier, destination_account_id=initial_account.identifier, amount=1)
# Get the pot and account again
post_pot = [pot for pot in LibMonzoTests.client.pots() if pot.identifier == pot_id][0]
post_account = [account for account in LibMonzoTests.client.accounts() if account.identifier == account_id][0]
post_account_balance = LibMonzoTests.client.balance(account_id=post_account.identifier)
# Check the values
self.assertTrue(post_pot.balance == mid_pot.balance - 1)
self.assertTrue(post_pot.balance == initial_pot.balance)
self.assertTrue(post_account_balance.balance == mid_account_balance.balance + 1)
self.assertTrue(post_account_balance.balance == initial_account_balance.balance)
def test_transactions(self):
"""Test transactions."""
accounts = LibMonzoTests.client.accounts()
for account in accounts:
transactions = LibMonzoTests.client.transactions(account_id=account.identifier)
self.assertIsNotNone(transactions)
transaction = random.choice(transactions)
detailed_transaction = LibMonzoTests.client.transaction(identifier=transaction.identifier)
self.assertEqual(detailed_transaction.identifier, transaction.identifier)
def test_annotations(self):
"""Test annotating transactions."""
perform_annotations_test = LibMonzoTests.config["perform_annotations_test"]
if not perform_annotations_test:
return
account_id = LibMonzoTests.config["test_account_id"]
transactions = LibMonzoTests.client.transactions(account_id=account_id)
transaction = random.choice(transactions)
annotation_key = "libmonzo_annotation_test"
annotation_value = "1"
# Add an annotation to the transaction
LibMonzoTests.client.annotate_transaction(
identifier=transaction.identifier,
key=annotation_key,
value=annotation_value
)
# Read it back to confirm it worked
annotated_transaction = LibMonzoTests.client.transaction(identifier=transaction.identifier)
metadata = annotated_transaction.raw_data.get("metadata")
self.assertIsNotNone(metadata)
self.assertEqual(metadata.get(annotation_key), annotation_value)
# Remove the annotation
LibMonzoTests.client.remove_transaction_annotation(
identifier=transaction.identifier,
key=annotation_key
)
# Read it back to confirm it worked
cleared_transaction = LibMonzoTests.client.transaction(identifier=transaction.identifier)
with self.assertRaises(ValueError):
_ = cleared_transaction.raw_data["metadata"][annotation_key]
def test_add_feed_item(self):
"""Test adding a feed item."""
perform_disruptive_tests = LibMonzoTests.config["perform_disruptive_tests"]
if not perform_disruptive_tests:
return
account_id = LibMonzoTests.config["test_account_id"]
try:
LibMonzoTests.client.create_feed_item(
account_id=account_id,
title="Hello world",
image_url="http://via.placeholder.com/64x64?text=X",
background_color=libmonzo.types.Color(hex_code="#000088"),
title_color=libmonzo.types.Color(hex_code="#FFFFFF"),
body_color=libmonzo.types.Color(hex_code="#AAAAAA"),
body="This is a feed test",
url="https://google.com"
)
except libmonzo.exceptions.MonzoAPIError as ex:
self.fail(f"Exception was raised: {ex}")
def test_attachment_registration(self):
"""Test adding an attachment"""
identifier = LibMonzoTests.config["attachment_transaction_id"]
# Get the transaction
transaction = LibMonzoTests.client.transaction(identifier=identifier)
try:
# Confirm there are no attachments:
self.assertEqual(0, len(transaction.attachments))
# Register the attachment
LibMonzoTests.client.register_attachment(
transaction_id=transaction.identifier,
url="http://via.placeholder.com/400x400?text=Transaction%20Sample%20Attachment",
mime_type="image/png"
)
# Confirm there is 1 attachment:
transaction = LibMonzoTests.client.transaction(identifier=identifier)
self.assertEqual(1, len(transaction.attachments))
finally:
# Unregister the attachments
for attachment in transaction.attachments:
LibMonzoTests.client.unregister_attachment(attachment_id=attachment.identifier)
# Confirm there are no attachments:
transaction = LibMonzoTests.client.transaction(identifier=identifier)
self.assertEqual(0, len(transaction.attachments))
def test_upload_attachment(self):
"""Test uploading an attachment"""
perform_attachment_upload_test = LibMonzoTests.config["perform_attachment_upload_test"]
if not perform_attachment_upload_test:
return
file_path = os.path.realpath(__file__)
folder_path = os.path.dirname(file_path)
image_path = os.path.join(folder_path, "upload_sample.png")
attachment_url = LibMonzoTests.client.upload_attachment(file_path=image_path, mime_type="image/png")
temp_name = str(uuid.uuid4()) + ".png"
temp_location = os.path.join(tempfile.gettempdir(), temp_name)
response = requests.get(attachment_url)
with open(temp_location, 'wb') as temp_file:
temp_file.write(response.content)
try:
self.assertTrue(filecmp.cmp(temp_location, image_path))
finally:
os.remove(temp_location)
def test_webhooks(self):
"""Test webhooks."""
account_id = LibMonzoTests.config["test_account_id"]
# Get the current hooks
current_hooks = LibMonzoTests.client.list_webhooks(account_id=account_id)
# Register a new hook
created_hook = LibMonzoTests.client.register_webhook(account_id=account_id, url="https://example.com")
# Get the latest hooks
new_hooks = LibMonzoTests.client.list_webhooks(account_id=account_id)
# Confirm that the old ones are there
for old_hook in current_hooks:
# Try and find the old hook in the new ones
found_previous = False
for new_hook in new_hooks:
if new_hook.identifier == old_hook.identifier:
found_previous = True
break
self.assertTrue(found_previous, "Failed to find previous hook")
# Confirm that the new one is there
found_new_hook = False
for hook in new_hooks:
if hook.identifier == created_hook.identifier:
found_new_hook = True
break
self.assertTrue(found_new_hook, "Failed to find new hook")
# Finally we can delete it
LibMonzoTests.client.delete_webhook(webhook_id=created_hook.identifier)
final_hooks = LibMonzoTests.client.list_webhooks(account_id=account_id)
# Confirm that our old ones are still there
for old_hook in current_hooks:
# Try and find the old hook in the new ones
found_previous = False
for final_hook in final_hooks:
if final_hook.identifier == old_hook.identifier:
found_previous = True
break
self.assertTrue(found_previous, "Failed to find previous hook")
# Confirm that the new one is NOT there
found_new_hook = False
for hook in final_hooks:
if hook.identifier == created_hook.identifier:
found_new_hook = True
break
self.assertFalse(found_new_hook, "Found new hook after deletion")
if __name__ == "__main__":
unittest.main(verbosity=2)
| en | 0.815696 | #!/usr/bin/env python3 Tests for the package. #pylint: disable=line-too-long #pylint: disable=wrong-import-position #pylint: enable=wrong-import-position Test the library. #cls.client.authenticate() #print(cls.client.access_token) Load the configuration. Test whoami. Test accounts. Test balances. Test pots. Test pot depositing/withdrawing. # Perform the deposit (1 penny) # Get the pot and account again # Check the values # Now do the transfer the other way # Get the pot and account again # Check the values Test transactions. Test annotating transactions. # Add an annotation to the transaction # Read it back to confirm it worked # Remove the annotation # Read it back to confirm it worked Test adding a feed item. Test adding an attachment # Get the transaction # Confirm there are no attachments: # Register the attachment # Confirm there is 1 attachment: # Unregister the attachments # Confirm there are no attachments: Test uploading an attachment Test webhooks. # Get the current hooks # Register a new hook # Get the latest hooks # Confirm that the old ones are there # Try and find the old hook in the new ones # Confirm that the new one is there # Finally we can delete it # Confirm that our old ones are still there # Try and find the old hook in the new ones # Confirm that the new one is NOT there | 2.23144 | 2 |
yandisk-downloader.py | ProgramYazar/yandex_downloader | 3 | 6622307 | <filename>yandisk-downloader.py
import os
import requests
URL_TEMPLATE = 'https://cloud-api.yandex.net/v1/disk/public/resources?public_key={pk}&limit=10000000'
def recursive_list(public_key: str, path=''):
files = []
_url = URL_TEMPLATE.format(pk=public_key)
if path != '':
_url += '&path=' + path
contents = requests.get(_url).json()['_embedded']['items']
for content in contents:
if content['type'] == 'dir':
files.extend(recursive_list(public_key, content['path']))
elif content['type'] == 'file':
files.append({
'path': os.path.join(path, content['name']).lstrip('/'),
'url': content['file']
})
return files
def download_not_exists(filename: str, url: str):
if os.path.exists(filename):
return
path, _file = os.path.split(filename)
if not os.path.exists(path):
os.makedirs(path)
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
if __name__ == "__main__":
url = input('Please enter yandex disk url: ').strip()
files = recursive_list(url)
for file in files:
filename, file_url = file['path'], file['url']
try:
print(f"{filename} downloading...")
download_not_exists(filename, file_url)
except:
print(f"!!! Error when download: {filename} !!!")
continue
| <filename>yandisk-downloader.py
import os
import requests
URL_TEMPLATE = 'https://cloud-api.yandex.net/v1/disk/public/resources?public_key={pk}&limit=10000000'
def recursive_list(public_key: str, path=''):
files = []
_url = URL_TEMPLATE.format(pk=public_key)
if path != '':
_url += '&path=' + path
contents = requests.get(_url).json()['_embedded']['items']
for content in contents:
if content['type'] == 'dir':
files.extend(recursive_list(public_key, content['path']))
elif content['type'] == 'file':
files.append({
'path': os.path.join(path, content['name']).lstrip('/'),
'url': content['file']
})
return files
def download_not_exists(filename: str, url: str):
if os.path.exists(filename):
return
path, _file = os.path.split(filename)
if not os.path.exists(path):
os.makedirs(path)
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
if __name__ == "__main__":
url = input('Please enter yandex disk url: ').strip()
files = recursive_list(url)
for file in files:
filename, file_url = file['path'], file['url']
try:
print(f"{filename} downloading...")
download_not_exists(filename, file_url)
except:
print(f"!!! Error when download: {filename} !!!")
continue
| none | 1 | 3.208523 | 3 | |
numerical/matrix/linear_sys.py | luizmugnaini/numerical | 0 | 6622308 | """
Authors: <NAME> (nUSP: 11809746)
<NAME> (nUSP: 11807702)
<NAME> (nUSP: 11809090)
Computacao III (CCM):
EP 2 Cubic interpolating splines: SquareMatrix, Tridiagonal, Periodic
EP 3 QR Factorization: Qr
"""
from numerical.matrix.linear_space import RealSpace
import numpy as np
class SquareMatrix:
"""Methods for square matrices"""
@classmethod
def gaussian_elim(
cls, mat: np.ndarray, vec: np.ndarray, lu_decomp: bool = False
) -> None:
"""General, in-place, gaussian elimination.
If `lu_decomp` is set as `True`, the method will use the upper
triangular part of `mat` for U and the lower part for L"""
if mat.shape[0] != mat.shape[1]:
raise Exception("Matrix not square")
def pivot_selection(mat: np.ndarray, col: int) -> int:
"""Partial pivot selection:
Returns the row index of the pivot given a specific column."""
pivot_row = 0
for row in range(1, mat.shape[0]):
if abs(mat[row, col]) > abs(mat[pivot_row, col]):
pivot_row = row
if mat[pivot_row, col] == 0:
raise Exception("The matrix is singular!")
return pivot_row
def switch_rows(mat: np.ndarray, row0: int, row1: int) -> None:
"""In-place switch rows: `row0` and `row1`"""
if row0 == row1:
return
for col in range(mat.shape[1]):
aux = mat[row0, col]
mat[row0, col] = mat[row1, col]
mat[row1, col] = aux
# For each column, select the `pivot`, switch rows if need be. For each
# row below the `pivot_row`, subtract element-wise the multiple `mult`
# in order to make the pivot the only non-zero element in the column.
# Pivot selection is done only for the first diagonal element,
# otherwise we simply use the current diagonal. This is acceptable if
# `mat` is equilibrated.
for diag in range(mat.shape[1]):
if diag == 0:
pivot_row = pivot_selection(mat, diag)
pivot = mat[pivot_row, diag]
switch_rows(mat, diag, pivot_row)
else:
pivot = mat[diag, diag]
for row in range(diag + 1, mat.shape[0]):
mult = mat[row, diag] / pivot
vec[row] -= mult * vec[diag]
for col in range(diag, mat.shape[1]):
mat[row, col] -= mult * mat[diag, col]
# If LU decomposition is wanted, store the multipliers in the
# lower matrix (this creates the lower tridiagonal matrix)
if lu_decomp:
mat[row, diag] = mult
@classmethod
def back_substitution(cls, mat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""Back substitution method."""
if mat.shape[0] != mat.shape[1]:
raise Exception("Matrix not square")
n = len(vec)
sol = np.zeros(n)
sol[-1] = vec[-1] / mat[-1, -1]
for i in range(n - 2, -1, -1):
acc = 0
for j in range(i, n):
acc += sol[j] * mat[i, j]
sol[i] = (vec[i] - acc) / mat[i, i]
return sol
@classmethod
def solve(cls, mat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""Solves the system `mat * X = vec` for `X`.
The algorithm is stable for diagonal dominant `mat` matrices.
"""
if mat.shape[0] != mat.shape[1]:
raise Exception("Matrix not square")
# Triangularization of `mat` and `vec`
cls.gaussian_elim(mat, vec)
return cls.back_substitution(mat, vec)
class Tridiagonal(SquareMatrix):
"""A class for methods concerning tridiagonal matrices"""
@classmethod
def gaussian_elim(
cls, mat: np.ndarray, vec: np.ndarray, lu_decomp: bool = False
) -> None:
"""In-place gaussian elimination algorithm.
If `lu_decomp` is set as `True`, the method will use the upper
triangular part of `mat` for U and the lower part for L"""
if mat.shape[1] != len(vec):
raise Exception("Lengths do not match")
for i in range(1, len(vec)):
mult = mat[i, i - 1] / mat[i - 1, i - 1]
mat[i, i] -= mult * mat[i - 1, i]
# If LU decomposition is wanted, store the multipliers in the
# lower matrix (this creates the lower tridiagonal matrix)
if lu_decomp:
mat[i, i - 1] = mult
else:
mat[i, i - 1] = 0
vec[i] -= mult * vec[i - 1]
class Periodic(SquareMatrix):
"""A class for methods concerning periodic matrices"""
@classmethod
def solve(cls, mat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""In-place solve a periodic linear system and returns the solution"""
# Before in-place operations, store needed information
v_tilde = np.copy(mat[-1, :-1])
# Solve for the y solution and find the multipliers
SquareMatrix.gaussian_elim(mat[:-1, :-1], mat[:-1, -1], True)
y_sol = SquareMatrix.back_substitution(mat[:-1, :-1], mat[:-1, -1])
# Use the multipliers on `z_vec`
z_vec = vec[:-1]
for i in range(1, mat.shape[1] - 1):
z_vec[i] -= z_vec[i - 1] * mat[i, i - 1]
# Now that `vec` is corrected, we can simply find the z solution by
# doing the back substitution
z_sol = SquareMatrix.back_substitution(mat[:-1, :-1], z_vec)
last = (vec[-1] - RealSpace.inner_product(v_tilde, z_sol)) / (
mat[-1, -1] - RealSpace.inner_product(v_tilde, y_sol)
)
# `sol0` contains the inner solutions, insert the first and last (equal)
# elements (`last`) when returning
sol0 = np.zeros(len(vec))
sol0 = z_sol - last * y_sol
return np.insert(sol0, [0, len(sol0)], last)
class Qr:
"""
The goal is to solve the system A x = b where A is an m by n matrix. If A
has linearly independent columns, the solution is unique.
"""
@classmethod
def factorization(cls, mat: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""QR factorization algorithm"""
m, n = mat.shape
mn = min(m, n)
q = np.column_stack([mat[:, j] for j in range(mn)]).reshape((m, mn))
r = np.zeros((mn, n))
for j in range(mn):
for i in range(j):
x = RealSpace.inner_product(q[:, i], mat[:, j])
q[:, j] -= x * q[:, i]
r[i, j] = x
norm = RealSpace.norm(q[:, j])
if norm == 0:
raise Exception("The matrix contains a set of LD columns")
q[:, j] /= norm
r[j, j] = RealSpace.inner_product(q[:, j], mat[:, j])
# remaining columns for the case m < n
if m < n:
for j in range(mn, n):
for i in range(j):
if i < r.shape[0]:
r[i, j] = RealSpace.inner_product(q[:, i], mat[:, j])
else:
break
return q, r
@classmethod
def solve(cls, mat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""Solve the linear system ``mat @ sol = vec``"""
q, r = cls.factorization(mat)
m, n = mat.shape
# Assert the correctness of the arguments
if m < n:
raise Exception("The system has no solution")
# solve the system ``r @ sol = z``
# `r` is a triangular square matrix of order `n`
z = np.zeros(n)
b = np.copy(vec)
for i in range(n):
z[i] = RealSpace.inner_product(q[:, i], b)
b -= z[i] * q[:, i]
return SquareMatrix.back_substitution(r, z)
| """
Authors: <NAME> (nUSP: 11809746)
<NAME> (nUSP: 11807702)
<NAME> (nUSP: 11809090)
Computacao III (CCM):
EP 2 Cubic interpolating splines: SquareMatrix, Tridiagonal, Periodic
EP 3 QR Factorization: Qr
"""
from numerical.matrix.linear_space import RealSpace
import numpy as np
class SquareMatrix:
"""Methods for square matrices"""
@classmethod
def gaussian_elim(
cls, mat: np.ndarray, vec: np.ndarray, lu_decomp: bool = False
) -> None:
"""General, in-place, gaussian elimination.
If `lu_decomp` is set as `True`, the method will use the upper
triangular part of `mat` for U and the lower part for L"""
if mat.shape[0] != mat.shape[1]:
raise Exception("Matrix not square")
def pivot_selection(mat: np.ndarray, col: int) -> int:
"""Partial pivot selection:
Returns the row index of the pivot given a specific column."""
pivot_row = 0
for row in range(1, mat.shape[0]):
if abs(mat[row, col]) > abs(mat[pivot_row, col]):
pivot_row = row
if mat[pivot_row, col] == 0:
raise Exception("The matrix is singular!")
return pivot_row
def switch_rows(mat: np.ndarray, row0: int, row1: int) -> None:
"""In-place switch rows: `row0` and `row1`"""
if row0 == row1:
return
for col in range(mat.shape[1]):
aux = mat[row0, col]
mat[row0, col] = mat[row1, col]
mat[row1, col] = aux
# For each column, select the `pivot`, switch rows if need be. For each
# row below the `pivot_row`, subtract element-wise the multiple `mult`
# in order to make the pivot the only non-zero element in the column.
# Pivot selection is done only for the first diagonal element,
# otherwise we simply use the current diagonal. This is acceptable if
# `mat` is equilibrated.
for diag in range(mat.shape[1]):
if diag == 0:
pivot_row = pivot_selection(mat, diag)
pivot = mat[pivot_row, diag]
switch_rows(mat, diag, pivot_row)
else:
pivot = mat[diag, diag]
for row in range(diag + 1, mat.shape[0]):
mult = mat[row, diag] / pivot
vec[row] -= mult * vec[diag]
for col in range(diag, mat.shape[1]):
mat[row, col] -= mult * mat[diag, col]
# If LU decomposition is wanted, store the multipliers in the
# lower matrix (this creates the lower tridiagonal matrix)
if lu_decomp:
mat[row, diag] = mult
@classmethod
def back_substitution(cls, mat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""Back substitution method."""
if mat.shape[0] != mat.shape[1]:
raise Exception("Matrix not square")
n = len(vec)
sol = np.zeros(n)
sol[-1] = vec[-1] / mat[-1, -1]
for i in range(n - 2, -1, -1):
acc = 0
for j in range(i, n):
acc += sol[j] * mat[i, j]
sol[i] = (vec[i] - acc) / mat[i, i]
return sol
@classmethod
def solve(cls, mat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""Solves the system `mat * X = vec` for `X`.
The algorithm is stable for diagonal dominant `mat` matrices.
"""
if mat.shape[0] != mat.shape[1]:
raise Exception("Matrix not square")
# Triangularization of `mat` and `vec`
cls.gaussian_elim(mat, vec)
return cls.back_substitution(mat, vec)
class Tridiagonal(SquareMatrix):
"""A class for methods concerning tridiagonal matrices"""
@classmethod
def gaussian_elim(
cls, mat: np.ndarray, vec: np.ndarray, lu_decomp: bool = False
) -> None:
"""In-place gaussian elimination algorithm.
If `lu_decomp` is set as `True`, the method will use the upper
triangular part of `mat` for U and the lower part for L"""
if mat.shape[1] != len(vec):
raise Exception("Lengths do not match")
for i in range(1, len(vec)):
mult = mat[i, i - 1] / mat[i - 1, i - 1]
mat[i, i] -= mult * mat[i - 1, i]
# If LU decomposition is wanted, store the multipliers in the
# lower matrix (this creates the lower tridiagonal matrix)
if lu_decomp:
mat[i, i - 1] = mult
else:
mat[i, i - 1] = 0
vec[i] -= mult * vec[i - 1]
class Periodic(SquareMatrix):
"""A class for methods concerning periodic matrices"""
@classmethod
def solve(cls, mat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""In-place solve a periodic linear system and returns the solution"""
# Before in-place operations, store needed information
v_tilde = np.copy(mat[-1, :-1])
# Solve for the y solution and find the multipliers
SquareMatrix.gaussian_elim(mat[:-1, :-1], mat[:-1, -1], True)
y_sol = SquareMatrix.back_substitution(mat[:-1, :-1], mat[:-1, -1])
# Use the multipliers on `z_vec`
z_vec = vec[:-1]
for i in range(1, mat.shape[1] - 1):
z_vec[i] -= z_vec[i - 1] * mat[i, i - 1]
# Now that `vec` is corrected, we can simply find the z solution by
# doing the back substitution
z_sol = SquareMatrix.back_substitution(mat[:-1, :-1], z_vec)
last = (vec[-1] - RealSpace.inner_product(v_tilde, z_sol)) / (
mat[-1, -1] - RealSpace.inner_product(v_tilde, y_sol)
)
# `sol0` contains the inner solutions, insert the first and last (equal)
# elements (`last`) when returning
sol0 = np.zeros(len(vec))
sol0 = z_sol - last * y_sol
return np.insert(sol0, [0, len(sol0)], last)
class Qr:
"""
The goal is to solve the system A x = b where A is an m by n matrix. If A
has linearly independent columns, the solution is unique.
"""
@classmethod
def factorization(cls, mat: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""QR factorization algorithm"""
m, n = mat.shape
mn = min(m, n)
q = np.column_stack([mat[:, j] for j in range(mn)]).reshape((m, mn))
r = np.zeros((mn, n))
for j in range(mn):
for i in range(j):
x = RealSpace.inner_product(q[:, i], mat[:, j])
q[:, j] -= x * q[:, i]
r[i, j] = x
norm = RealSpace.norm(q[:, j])
if norm == 0:
raise Exception("The matrix contains a set of LD columns")
q[:, j] /= norm
r[j, j] = RealSpace.inner_product(q[:, j], mat[:, j])
# remaining columns for the case m < n
if m < n:
for j in range(mn, n):
for i in range(j):
if i < r.shape[0]:
r[i, j] = RealSpace.inner_product(q[:, i], mat[:, j])
else:
break
return q, r
@classmethod
def solve(cls, mat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""Solve the linear system ``mat @ sol = vec``"""
q, r = cls.factorization(mat)
m, n = mat.shape
# Assert the correctness of the arguments
if m < n:
raise Exception("The system has no solution")
# solve the system ``r @ sol = z``
# `r` is a triangular square matrix of order `n`
z = np.zeros(n)
b = np.copy(vec)
for i in range(n):
z[i] = RealSpace.inner_product(q[:, i], b)
b -= z[i] * q[:, i]
return SquareMatrix.back_substitution(r, z)
| en | 0.752554 | Authors: <NAME> (nUSP: 11809746) <NAME> (nUSP: 11807702) <NAME> (nUSP: 11809090) Computacao III (CCM): EP 2 Cubic interpolating splines: SquareMatrix, Tridiagonal, Periodic EP 3 QR Factorization: Qr Methods for square matrices General, in-place, gaussian elimination. If `lu_decomp` is set as `True`, the method will use the upper triangular part of `mat` for U and the lower part for L Partial pivot selection: Returns the row index of the pivot given a specific column. In-place switch rows: `row0` and `row1` # For each column, select the `pivot`, switch rows if need be. For each # row below the `pivot_row`, subtract element-wise the multiple `mult` # in order to make the pivot the only non-zero element in the column. # Pivot selection is done only for the first diagonal element, # otherwise we simply use the current diagonal. This is acceptable if # `mat` is equilibrated. # If LU decomposition is wanted, store the multipliers in the # lower matrix (this creates the lower tridiagonal matrix) Back substitution method. Solves the system `mat * X = vec` for `X`. The algorithm is stable for diagonal dominant `mat` matrices. # Triangularization of `mat` and `vec` A class for methods concerning tridiagonal matrices In-place gaussian elimination algorithm. If `lu_decomp` is set as `True`, the method will use the upper triangular part of `mat` for U and the lower part for L # If LU decomposition is wanted, store the multipliers in the # lower matrix (this creates the lower tridiagonal matrix) A class for methods concerning periodic matrices In-place solve a periodic linear system and returns the solution # Before in-place operations, store needed information # Solve for the y solution and find the multipliers # Use the multipliers on `z_vec` # Now that `vec` is corrected, we can simply find the z solution by # doing the back substitution # `sol0` contains the inner solutions, insert the first and last (equal) # elements (`last`) when returning The goal is to solve the system A x = b where A is an m by n matrix. If A has linearly independent columns, the solution is unique. QR factorization algorithm # remaining columns for the case m < n Solve the linear system ``mat @ sol = vec`` # Assert the correctness of the arguments # solve the system ``r @ sol = z`` # `r` is a triangular square matrix of order `n` | 3.840154 | 4 |
profiles/forms.py | vkendurkar/StudentCouncil | 1 | 6622309 | from django import forms
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
class UserForm(forms.Form):
username = forms.CharField(max_length=20)
name = forms.CharField(max_length=50)
email = forms.EmailField()
class ProfileForm(forms.Form):
BRANCH_LIST = [('CH', 'Chemical Engineering'),
('CO', 'Computer Engineering'),
('CV', 'Civil Engineering'),
('EC', 'Electronics and Communications Engineering'),
('EE', 'Elelctrical and Electronics Engineering'),
('IT', 'Information Technology'),
('ME', 'Mechanical Engineering'),
('MN', 'Mining Engineering'),
('MT', 'Materials and Metallurgical Engineering'),
]
rollno = forms.CharField(max_length=8)
branch = forms.ChoiceField(choices = BRANCH_LIST)
birth_date = forms.DateField()
hostel_block = forms.CharField(max_length=20)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '9876543210'. Up to 10 digits allowed.")
phone_num = forms.CharField(max_length=10)
bio = forms.CharField(max_length=500) | from django import forms
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
class UserForm(forms.Form):
username = forms.CharField(max_length=20)
name = forms.CharField(max_length=50)
email = forms.EmailField()
class ProfileForm(forms.Form):
BRANCH_LIST = [('CH', 'Chemical Engineering'),
('CO', 'Computer Engineering'),
('CV', 'Civil Engineering'),
('EC', 'Electronics and Communications Engineering'),
('EE', 'Elelctrical and Electronics Engineering'),
('IT', 'Information Technology'),
('ME', 'Mechanical Engineering'),
('MN', 'Mining Engineering'),
('MT', 'Materials and Metallurgical Engineering'),
]
rollno = forms.CharField(max_length=8)
branch = forms.ChoiceField(choices = BRANCH_LIST)
birth_date = forms.DateField()
hostel_block = forms.CharField(max_length=20)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '9876543210'. Up to 10 digits allowed.")
phone_num = forms.CharField(max_length=10)
bio = forms.CharField(max_length=500) | none | 1 | 2.465864 | 2 | |
tests/plugins/test_beattv.py | mattrick/streamlink | 2 | 6622310 | <gh_stars>1-10
import unittest
from streamlink.plugins.beattv import BeatTV
class TestPluginBeatTV(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
'http://be-at.tv/video/adam_beyer_hyte_nye_germany_2018',
'https://www.be-at.tv/videos/ben-klock-great-wall-festival-2019'
]
for url in should_match:
self.assertTrue(BeatTV.can_handle_url(url), url)
def test_can_handle_url_negative(self):
should_not_match = [
'https://example.com/index.html',
'https://www.be-at.tv/series/extrema-outdoor-belgium-2019'
]
for url in should_not_match:
self.assertFalse(BeatTV.can_handle_url(url))
| import unittest
from streamlink.plugins.beattv import BeatTV
class TestPluginBeatTV(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
'http://be-at.tv/video/adam_beyer_hyte_nye_germany_2018',
'https://www.be-at.tv/videos/ben-klock-great-wall-festival-2019'
]
for url in should_match:
self.assertTrue(BeatTV.can_handle_url(url), url)
def test_can_handle_url_negative(self):
should_not_match = [
'https://example.com/index.html',
'https://www.be-at.tv/series/extrema-outdoor-belgium-2019'
]
for url in should_not_match:
self.assertFalse(BeatTV.can_handle_url(url)) | none | 1 | 3.059801 | 3 | |
Beginner/03. Python/DoubleIndex.py | ankita080208/Hacktoberfest | 1 | 6622311 | <gh_stars>1-10
"""
Create a function named double_index that has two parameters: a list named lst and a single number named index.
The function should return a new list where all elements are the same as in lst except for the element at index. The element at index should be double the value of the element at index of the original lst.
If index is not a valid index, the function should return the original list.
For example, the following code should return [1,2,6,4] because the element at index 2 has been doubled:
double_index([1, 2, 3, 4], 2)
After writing your function, un-comment the call to the function that we’ve provided for you to test your results.
"""
def double_index(lst,index):
if index>=len(lst):
return lst
lst[index]*=2
return lst
print(double_index([3, 8, -10, 12], 2)) | """
Create a function named double_index that has two parameters: a list named lst and a single number named index.
The function should return a new list where all elements are the same as in lst except for the element at index. The element at index should be double the value of the element at index of the original lst.
If index is not a valid index, the function should return the original list.
For example, the following code should return [1,2,6,4] because the element at index 2 has been doubled:
double_index([1, 2, 3, 4], 2)
After writing your function, un-comment the call to the function that we’ve provided for you to test your results.
"""
def double_index(lst,index):
if index>=len(lst):
return lst
lst[index]*=2
return lst
print(double_index([3, 8, -10, 12], 2)) | en | 0.842734 | Create a function named double_index that has two parameters: a list named lst and a single number named index. The function should return a new list where all elements are the same as in lst except for the element at index. The element at index should be double the value of the element at index of the original lst. If index is not a valid index, the function should return the original list. For example, the following code should return [1,2,6,4] because the element at index 2 has been doubled: double_index([1, 2, 3, 4], 2) After writing your function, un-comment the call to the function that we’ve provided for you to test your results. | 4.288657 | 4 |
tests/test_itemDef_define.py | swhume/odmlib | 9 | 6622312 | <reponame>swhume/odmlib
from unittest import TestCase
import json
import odmlib.define_2_0.model as DEFINE
class TestItemDef(TestCase):
def setUp(self) -> None:
attrs = self.set_item_attributes()
self.item = DEFINE.ItemDef(**attrs)
def test_required_attributes_only(self):
attrs = {"OID": "ODM.IT.AE.AEYN", "Name": "Any AEs?", "DataType": "text"}
self.item = DEFINE.ItemDef(**attrs)
self.assertEqual(self.item.OID, "ODM.IT.AE.AEYN")
def test_add_value_list_ref(self):
vlr = DEFINE.ValueListRef(ValueListOID="VL.DA.DAORRES")
attrs = {"OID": "IT.DA.DAORRES", "Name": "DAORRES", "DataType": "text", "Length": "2", "SASFieldName": "DAORRES"}
itd = DEFINE.ItemDef(**attrs)
tt1 = DEFINE.TranslatedText(_content="Assessment Result in Original Units", lang="en")
desc = DEFINE.Description()
desc.TranslatedText.append(tt1)
itd.Description = desc
itd.ValueListRef = vlr
self.assertEqual(itd.ValueListRef.ValueListOID, "VL.DA.DAORRES")
self.assertEqual(itd.OID, "IT.DA.DAORRES")
def test_set_description(self):
attrs = {"_content": "Assessment Result in Original Units", "lang": "en"}
tt1 = DEFINE.TranslatedText(**attrs)
self.item.Description.TranslatedText.append(tt1)
self.assertEqual(self.item.Description.TranslatedText[0].lang, "en")
self.assertEqual(self.item.Description.TranslatedText[0]._content, "Assessment Result in Original Units")
def test_set_invalid_description(self):
rc = DEFINE.RangeCheck(Comparator="EQ", SoftHard="Soft", ItemOID="IT.DA.DAORRES")
rc.CheckValue = [DEFINE.CheckValue(_content="DIABP")]
self.item.RangeCheck = [rc]
# Description requires a Description object, not a RangeCheck object
with self.assertRaises(TypeError):
self.item.Description = rc
def test_add_description(self):
attrs = {"_content": "this is the first test description", "lang": "en"}
tt1 = DEFINE.TranslatedText(**attrs)
attrs = {"_content": "this is the second test description", "lang": "en"}
tt2 = DEFINE.TranslatedText(**attrs)
self.item.Description.TranslatedText.append(tt1)
self.item.Description.TranslatedText.append(tt2)
self.assertEqual(self.item.Description.TranslatedText[1]._content, "this is the second test description")
def test_codelist_ref(self):
self.item.CodeListRef = DEFINE.CodeListRef(CodeListOID="CL.NY_SUB_Y_N_2011-10-24")
self.assertEqual(self.item.CodeListRef.CodeListOID, "CL.NY_SUB_Y_N_2011-10-24")
def test_origin(self):
self.item.Origin = DEFINE.Origin(Type="Assigned")
self.assertEqual(self.item.Origin.Type, "Assigned")
def test_add_alias(self):
self.item.Alias = [DEFINE.Alias(Context="CDASH", Name="AEYN")]
self.assertEqual(self.item.Alias[0].Name, "AEYN")
def test_to_json(self):
attrs = self.set_item_attributes()
item = DEFINE.ItemDef(**attrs)
item.Description.TranslatedText.append(DEFINE.TranslatedText(_content="this is the first test description", lang="en"))
item.Question.TranslatedText = [DEFINE.TranslatedText(_content="Any AEs?", lang="en")]
item.CodeListRef = DEFINE.CodeListRef(CodeListOID="CL.NY_SUB_Y_N_2011-10-24")
item_json = item.to_json()
item_dict = json.loads(item_json)
self.assertEqual(item_dict["OID"], "ODM.IT.AE.AEYN")
def test_to_dict(self):
attrs = self.set_item_attributes()
item = DEFINE.ItemDef(**attrs)
item.Description.TranslatedText = [DEFINE.TranslatedText(_content="this is the first test description", lang="en")]
item.Question.TranslatedText = [DEFINE.TranslatedText(_content="Any AEs?", lang="en")]
item.CodeListRef = DEFINE.CodeListRef(CodeListOID="CL.NY_SUB_Y_N_2011-10-24")
item_dict = item.to_dict()
expected_dict = {'OID': 'ODM.IT.AE.AEYN', 'Name': 'Any AEs?', 'DataType': 'text', 'Length': 1,
'SASFieldName': 'AEYN', "CommentOID": "ODM.CO.120",
'Description': {'TranslatedText': [{'_content': 'this is the first test description',
'lang': 'en'}]},
'Question': {'TranslatedText': [{'_content': 'Any AEs?', 'lang': 'en'}]},
'CodeListRef': {'CodeListOID': 'CL.NY_SUB_Y_N_2011-10-24'}}
self.assertDictEqual(item_dict, expected_dict)
def test_to_dict_description(self):
tt1 = DEFINE.TranslatedText(_content="this is the first test description", lang="en")
tt2 = DEFINE.TranslatedText(_content="this is the second test description", lang="en")
desc = DEFINE.Description()
desc.TranslatedText = [tt1, tt2]
desc_dict = desc.to_dict()
print(desc_dict)
self.assertDictEqual(desc_dict["TranslatedText"][1],
{'_content': 'this is the second test description', 'lang': 'en'})
def test_to_xml_description(self):
tt1 = DEFINE.TranslatedText(_content="this is the first test description", lang="en")
tt2 = DEFINE.TranslatedText(_content="this is the second test description", lang="en")
desc = DEFINE.Description()
desc.TranslatedText = [tt1, tt2]
desc_xml = desc.to_xml()
tts = desc_xml.findall("TranslatedText")
self.assertEqual(tts[0].text, "this is the first test description")
def test_to_xml(self):
attrs = self.set_item_attributes()
item = DEFINE.ItemDef(**attrs)
item.Description.TranslatedText = [DEFINE.TranslatedText(_content="this is the first test description", lang="en")]
item.CodeListRef = DEFINE.CodeListRef(CodeListOID="CL.NY_SUB_Y_N_2011-10-24")
item.RangeCheck = [DEFINE.RangeCheck(Comparator="EQ", SoftHard="Soft", ItemOID="IT.DA.DAORRES")]
item.RangeCheck[0].CheckValue = [DEFINE.CheckValue(_content="DIABP")]
item_xml = item.to_xml()
self.assertEqual(item_xml.attrib["OID"], "ODM.IT.AE.AEYN")
cv = item_xml.find("*/CheckValue")
self.assertEqual(cv.text, "DIABP")
dt = item_xml.findall("Description/TranslatedText")
self.assertEqual(len(dt), 1)
def test_missing_itemdef_attributes(self):
attrs = {"OID": "ODM.IT.AE.AEYN", "Name": "Any AEs?"}
with self.assertRaises(ValueError):
DEFINE.ItemDef(**attrs)
def test_invalid_attribute_data_type(self):
attrs = {"OID": "ODM.IT.AE.AEYN", "Name": "Any AEs?", "DataType": "text", "SignificantDigits": "A"}
with self.assertRaises(TypeError):
self.item = DEFINE.ItemDef(**attrs)
def set_item_attributes(self):
"""
set some ItemDef element attributes using test data
:return: dictionary with ItemDef attribute information
"""
return {"OID": "ODM.IT.AE.AEYN", "Name": "Any AEs?", "DataType": "text", "Length": 1, "SASFieldName": "AEYN",
"CommentOID": "ODM.CO.120"}
| from unittest import TestCase
import json
import odmlib.define_2_0.model as DEFINE
class TestItemDef(TestCase):
def setUp(self) -> None:
attrs = self.set_item_attributes()
self.item = DEFINE.ItemDef(**attrs)
def test_required_attributes_only(self):
attrs = {"OID": "ODM.IT.AE.AEYN", "Name": "Any AEs?", "DataType": "text"}
self.item = DEFINE.ItemDef(**attrs)
self.assertEqual(self.item.OID, "ODM.IT.AE.AEYN")
def test_add_value_list_ref(self):
vlr = DEFINE.ValueListRef(ValueListOID="VL.DA.DAORRES")
attrs = {"OID": "IT.DA.DAORRES", "Name": "DAORRES", "DataType": "text", "Length": "2", "SASFieldName": "DAORRES"}
itd = DEFINE.ItemDef(**attrs)
tt1 = DEFINE.TranslatedText(_content="Assessment Result in Original Units", lang="en")
desc = DEFINE.Description()
desc.TranslatedText.append(tt1)
itd.Description = desc
itd.ValueListRef = vlr
self.assertEqual(itd.ValueListRef.ValueListOID, "VL.DA.DAORRES")
self.assertEqual(itd.OID, "IT.DA.DAORRES")
def test_set_description(self):
attrs = {"_content": "Assessment Result in Original Units", "lang": "en"}
tt1 = DEFINE.TranslatedText(**attrs)
self.item.Description.TranslatedText.append(tt1)
self.assertEqual(self.item.Description.TranslatedText[0].lang, "en")
self.assertEqual(self.item.Description.TranslatedText[0]._content, "Assessment Result in Original Units")
def test_set_invalid_description(self):
rc = DEFINE.RangeCheck(Comparator="EQ", SoftHard="Soft", ItemOID="IT.DA.DAORRES")
rc.CheckValue = [DEFINE.CheckValue(_content="DIABP")]
self.item.RangeCheck = [rc]
# Description requires a Description object, not a RangeCheck object
with self.assertRaises(TypeError):
self.item.Description = rc
def test_add_description(self):
attrs = {"_content": "this is the first test description", "lang": "en"}
tt1 = DEFINE.TranslatedText(**attrs)
attrs = {"_content": "this is the second test description", "lang": "en"}
tt2 = DEFINE.TranslatedText(**attrs)
self.item.Description.TranslatedText.append(tt1)
self.item.Description.TranslatedText.append(tt2)
self.assertEqual(self.item.Description.TranslatedText[1]._content, "this is the second test description")
def test_codelist_ref(self):
self.item.CodeListRef = DEFINE.CodeListRef(CodeListOID="CL.NY_SUB_Y_N_2011-10-24")
self.assertEqual(self.item.CodeListRef.CodeListOID, "CL.NY_SUB_Y_N_2011-10-24")
def test_origin(self):
self.item.Origin = DEFINE.Origin(Type="Assigned")
self.assertEqual(self.item.Origin.Type, "Assigned")
def test_add_alias(self):
self.item.Alias = [DEFINE.Alias(Context="CDASH", Name="AEYN")]
self.assertEqual(self.item.Alias[0].Name, "AEYN")
def test_to_json(self):
attrs = self.set_item_attributes()
item = DEFINE.ItemDef(**attrs)
item.Description.TranslatedText.append(DEFINE.TranslatedText(_content="this is the first test description", lang="en"))
item.Question.TranslatedText = [DEFINE.TranslatedText(_content="Any AEs?", lang="en")]
item.CodeListRef = DEFINE.CodeListRef(CodeListOID="CL.NY_SUB_Y_N_2011-10-24")
item_json = item.to_json()
item_dict = json.loads(item_json)
self.assertEqual(item_dict["OID"], "ODM.IT.AE.AEYN")
def test_to_dict(self):
attrs = self.set_item_attributes()
item = DEFINE.ItemDef(**attrs)
item.Description.TranslatedText = [DEFINE.TranslatedText(_content="this is the first test description", lang="en")]
item.Question.TranslatedText = [DEFINE.TranslatedText(_content="Any AEs?", lang="en")]
item.CodeListRef = DEFINE.CodeListRef(CodeListOID="CL.NY_SUB_Y_N_2011-10-24")
item_dict = item.to_dict()
expected_dict = {'OID': 'ODM.IT.AE.AEYN', 'Name': 'Any AEs?', 'DataType': 'text', 'Length': 1,
'SASFieldName': 'AEYN', "CommentOID": "ODM.CO.120",
'Description': {'TranslatedText': [{'_content': 'this is the first test description',
'lang': 'en'}]},
'Question': {'TranslatedText': [{'_content': 'Any AEs?', 'lang': 'en'}]},
'CodeListRef': {'CodeListOID': 'CL.NY_SUB_Y_N_2011-10-24'}}
self.assertDictEqual(item_dict, expected_dict)
def test_to_dict_description(self):
tt1 = DEFINE.TranslatedText(_content="this is the first test description", lang="en")
tt2 = DEFINE.TranslatedText(_content="this is the second test description", lang="en")
desc = DEFINE.Description()
desc.TranslatedText = [tt1, tt2]
desc_dict = desc.to_dict()
print(desc_dict)
self.assertDictEqual(desc_dict["TranslatedText"][1],
{'_content': 'this is the second test description', 'lang': 'en'})
def test_to_xml_description(self):
tt1 = DEFINE.TranslatedText(_content="this is the first test description", lang="en")
tt2 = DEFINE.TranslatedText(_content="this is the second test description", lang="en")
desc = DEFINE.Description()
desc.TranslatedText = [tt1, tt2]
desc_xml = desc.to_xml()
tts = desc_xml.findall("TranslatedText")
self.assertEqual(tts[0].text, "this is the first test description")
def test_to_xml(self):
attrs = self.set_item_attributes()
item = DEFINE.ItemDef(**attrs)
item.Description.TranslatedText = [DEFINE.TranslatedText(_content="this is the first test description", lang="en")]
item.CodeListRef = DEFINE.CodeListRef(CodeListOID="CL.NY_SUB_Y_N_2011-10-24")
item.RangeCheck = [DEFINE.RangeCheck(Comparator="EQ", SoftHard="Soft", ItemOID="IT.DA.DAORRES")]
item.RangeCheck[0].CheckValue = [DEFINE.CheckValue(_content="DIABP")]
item_xml = item.to_xml()
self.assertEqual(item_xml.attrib["OID"], "ODM.IT.AE.AEYN")
cv = item_xml.find("*/CheckValue")
self.assertEqual(cv.text, "DIABP")
dt = item_xml.findall("Description/TranslatedText")
self.assertEqual(len(dt), 1)
def test_missing_itemdef_attributes(self):
attrs = {"OID": "ODM.IT.AE.AEYN", "Name": "Any AEs?"}
with self.assertRaises(ValueError):
DEFINE.ItemDef(**attrs)
def test_invalid_attribute_data_type(self):
attrs = {"OID": "ODM.IT.AE.AEYN", "Name": "Any AEs?", "DataType": "text", "SignificantDigits": "A"}
with self.assertRaises(TypeError):
self.item = DEFINE.ItemDef(**attrs)
def set_item_attributes(self):
"""
set some ItemDef element attributes using test data
:return: dictionary with ItemDef attribute information
"""
return {"OID": "ODM.IT.AE.AEYN", "Name": "Any AEs?", "DataType": "text", "Length": 1, "SASFieldName": "AEYN",
"CommentOID": "ODM.CO.120"} | en | 0.474383 | # Description requires a Description object, not a RangeCheck object set some ItemDef element attributes using test data :return: dictionary with ItemDef attribute information | 2.688236 | 3 |
src/_Utils/urlValidator.py | krisHans3n/ifd_standardised_api_prod | 0 | 6622313 | <filename>src/_Utils/urlValidator.py
import validators
def validate_url_string(url_arr):
for url in url_arr:
if not validators.url(url):
url_arr.remove(url)
return url_arr
| <filename>src/_Utils/urlValidator.py
import validators
def validate_url_string(url_arr):
for url in url_arr:
if not validators.url(url):
url_arr.remove(url)
return url_arr
| none | 1 | 2.768481 | 3 | |
create_data.py | Emocial-NLP-Depression-Detection/Emocial-AI-Thai | 1 | 6622314 | <filename>create_data.py
from pythainlp.sentiment import sentiment
import twint
import pandas as pd
import os
import emoji
import re
c = twint.Config()
c.Search = "โรคซึมเศร้า"
c.Limit = 100000
c.Store_csv = True
c.Output = "./data/raw_depressed_data.csv"
c.Lang = 'th'
p = twint.Config()
p.Search = "เรา"
p.Limit = 100000
p.Store_csv = True
p.Output = "./data/raw_everyday_data.csv"
p.Lang = 'th'
twint.run.Search(c)
twint.run.Search(p)
# def translate(x):
# return TextBlob(x).translate(to="th")
print("\nImporting Data\n")
df = pd.read_csv("./data/raw_depressed_data.csv")
pos = pd.read_csv("./data/raw_everyday_data.csv")
print("\nDone Importing Data\n")
label = []
analysed = 0
print("\n Sentiment Analysing the tweets\n")
for tweets in df['tweet']:
if sentiment(tweets) == 'pos':
label.append(0)
else:
label.append(1)
analysed = analysed + 1
if analysed % 100 == 0:
print(f"Analysed {analysed} so far...")
pos_label = []
for tweets in pos['tweet']:
if sentiment(tweets) == 'pos':
pos_label.append(0)
else:
pos_label.append(1)
analysed = analysed + 1
if analysed % 100 == 0:
print(f"Analysed {analysed} so far...")
print("\n Finished Sentiment Analysing the tweets\n")
df2 = pd.DataFrame({'Tweets': df['tweet'], 'label': label})
pos2 = pd.DataFrame({'Tweets': pos['tweet'], 'label': pos_label})
is_pos = pos2['label'] == 0
pos2 = pos2[is_pos]
df3 = df2.append(pos2, ignore_index=True, sort=True)
print("\nStart Cleaning..\n")
for index, i in df3.iterrows():
# print(i)
if df3.label.value_counts()[1] > df3.label.value_counts()[0] and i['label'] == 1:
df3 = df3.drop(index, errors='ignore')
# print(f"Index: {index}\n I: {i}")
elif df3.label.value_counts()[1] < df3.label.value_counts()[0] and i['label'] == 0:
df3 = df3.drop(index, errors='ignore')
print("\Done Cleaning..\n")
print(f"Depressed Tweets: {df3.label.value_counts()[1]}")
print(f"Positive Tweets: {df3.label.value_counts()[0]}")
df3.to_csv("./data/data.csv", index=False)
os.remove("./data/raw_depressed_data.csv")
os.remove("./data/raw_everyday_data.csv")
| <filename>create_data.py
from pythainlp.sentiment import sentiment
import twint
import pandas as pd
import os
import emoji
import re
c = twint.Config()
c.Search = "โรคซึมเศร้า"
c.Limit = 100000
c.Store_csv = True
c.Output = "./data/raw_depressed_data.csv"
c.Lang = 'th'
p = twint.Config()
p.Search = "เรา"
p.Limit = 100000
p.Store_csv = True
p.Output = "./data/raw_everyday_data.csv"
p.Lang = 'th'
twint.run.Search(c)
twint.run.Search(p)
# def translate(x):
# return TextBlob(x).translate(to="th")
print("\nImporting Data\n")
df = pd.read_csv("./data/raw_depressed_data.csv")
pos = pd.read_csv("./data/raw_everyday_data.csv")
print("\nDone Importing Data\n")
label = []
analysed = 0
print("\n Sentiment Analysing the tweets\n")
for tweets in df['tweet']:
if sentiment(tweets) == 'pos':
label.append(0)
else:
label.append(1)
analysed = analysed + 1
if analysed % 100 == 0:
print(f"Analysed {analysed} so far...")
pos_label = []
for tweets in pos['tweet']:
if sentiment(tweets) == 'pos':
pos_label.append(0)
else:
pos_label.append(1)
analysed = analysed + 1
if analysed % 100 == 0:
print(f"Analysed {analysed} so far...")
print("\n Finished Sentiment Analysing the tweets\n")
df2 = pd.DataFrame({'Tweets': df['tweet'], 'label': label})
pos2 = pd.DataFrame({'Tweets': pos['tweet'], 'label': pos_label})
is_pos = pos2['label'] == 0
pos2 = pos2[is_pos]
df3 = df2.append(pos2, ignore_index=True, sort=True)
print("\nStart Cleaning..\n")
for index, i in df3.iterrows():
# print(i)
if df3.label.value_counts()[1] > df3.label.value_counts()[0] and i['label'] == 1:
df3 = df3.drop(index, errors='ignore')
# print(f"Index: {index}\n I: {i}")
elif df3.label.value_counts()[1] < df3.label.value_counts()[0] and i['label'] == 0:
df3 = df3.drop(index, errors='ignore')
print("\Done Cleaning..\n")
print(f"Depressed Tweets: {df3.label.value_counts()[1]}")
print(f"Positive Tweets: {df3.label.value_counts()[0]}")
df3.to_csv("./data/data.csv", index=False)
os.remove("./data/raw_depressed_data.csv")
os.remove("./data/raw_everyday_data.csv")
| en | 0.134495 | # def translate(x): # return TextBlob(x).translate(to="th") # print(i) # print(f"Index: {index}\n I: {i}") | 3.102421 | 3 |
hvm/vm/forks/frontier/transactions.py | hyperevo/py-helios-node | 0 | 6622315 | import rlp_cython as rlp
from hvm.constants import (
CREATE_CONTRACT_ADDRESS,
GAS_TX,
GAS_TXDATAZERO,
GAS_TXDATANONZERO,
)
from hvm.validation import (
validate_uint256,
validate_is_integer,
validate_is_bytes,
validate_lt_secpk1n,
validate_lte,
validate_gte,
validate_canonical_address,
)
from hvm.rlp.transactions import (
BaseTransaction,
)
from hvm.utils.transactions import (
create_transaction_signature,
extract_transaction_sender,
validate_transaction_signature,
)
class FrontierTransaction(BaseTransaction):
v_max = 28
v_min = 27
def validate(self):
validate_uint256(self.nonce, title="Transaction.nonce")
validate_uint256(self.gas_price, title="Transaction.gas_price")
validate_uint256(self.gas, title="Transaction.gas")
if self.to != CREATE_CONTRACT_ADDRESS:
validate_canonical_address(self.to, title="Transaction.to")
validate_uint256(self.value, title="Transaction.value")
validate_is_bytes(self.data, title="Transaction.data")
validate_uint256(self.v, title="Transaction.v")
validate_uint256(self.r, title="Transaction.r")
validate_uint256(self.s, title="Transaction.s")
validate_lt_secpk1n(self.r, title="Transaction.r")
validate_gte(self.r, minimum=1, title="Transaction.r")
validate_lt_secpk1n(self.s, title="Transaction.s")
validate_gte(self.s, minimum=1, title="Transaction.s")
validate_gte(self.v, minimum=self.v_min, title="Transaction.v")
validate_lte(self.v, maximum=self.v_max, title="Transaction.v")
super(FrontierTransaction, self).validate()
def check_signature_validity(self):
validate_transaction_signature(self)
def get_sender(self):
return extract_transaction_sender(self)
def get_intrinsic_gas(self):
return _get_frontier_intrinsic_gas(self.data)
def get_message_for_signing(self):
return rlp.encode(FrontierUnsignedTransaction(
nonce=self.nonce,
gas_price=self.gas_price,
gas=self.gas,
to=self.to,
value=self.value,
data=self.data,
))
def _get_frontier_intrinsic_gas(transaction_data):
num_zero_bytes = transaction_data.count(b'\x00')
num_non_zero_bytes = len(transaction_data) - num_zero_bytes
return (
GAS_TX +
num_zero_bytes * GAS_TXDATAZERO +
num_non_zero_bytes * GAS_TXDATANONZERO
)
| import rlp_cython as rlp
from hvm.constants import (
CREATE_CONTRACT_ADDRESS,
GAS_TX,
GAS_TXDATAZERO,
GAS_TXDATANONZERO,
)
from hvm.validation import (
validate_uint256,
validate_is_integer,
validate_is_bytes,
validate_lt_secpk1n,
validate_lte,
validate_gte,
validate_canonical_address,
)
from hvm.rlp.transactions import (
BaseTransaction,
)
from hvm.utils.transactions import (
create_transaction_signature,
extract_transaction_sender,
validate_transaction_signature,
)
class FrontierTransaction(BaseTransaction):
v_max = 28
v_min = 27
def validate(self):
validate_uint256(self.nonce, title="Transaction.nonce")
validate_uint256(self.gas_price, title="Transaction.gas_price")
validate_uint256(self.gas, title="Transaction.gas")
if self.to != CREATE_CONTRACT_ADDRESS:
validate_canonical_address(self.to, title="Transaction.to")
validate_uint256(self.value, title="Transaction.value")
validate_is_bytes(self.data, title="Transaction.data")
validate_uint256(self.v, title="Transaction.v")
validate_uint256(self.r, title="Transaction.r")
validate_uint256(self.s, title="Transaction.s")
validate_lt_secpk1n(self.r, title="Transaction.r")
validate_gte(self.r, minimum=1, title="Transaction.r")
validate_lt_secpk1n(self.s, title="Transaction.s")
validate_gte(self.s, minimum=1, title="Transaction.s")
validate_gte(self.v, minimum=self.v_min, title="Transaction.v")
validate_lte(self.v, maximum=self.v_max, title="Transaction.v")
super(FrontierTransaction, self).validate()
def check_signature_validity(self):
validate_transaction_signature(self)
def get_sender(self):
return extract_transaction_sender(self)
def get_intrinsic_gas(self):
return _get_frontier_intrinsic_gas(self.data)
def get_message_for_signing(self):
return rlp.encode(FrontierUnsignedTransaction(
nonce=self.nonce,
gas_price=self.gas_price,
gas=self.gas,
to=self.to,
value=self.value,
data=self.data,
))
def _get_frontier_intrinsic_gas(transaction_data):
num_zero_bytes = transaction_data.count(b'\x00')
num_non_zero_bytes = len(transaction_data) - num_zero_bytes
return (
GAS_TX +
num_zero_bytes * GAS_TXDATAZERO +
num_non_zero_bytes * GAS_TXDATANONZERO
)
| none | 1 | 2.053425 | 2 | |
Datacamp Assignments/Data Engineer Track/3. Software Engineering & Data Science/2_leveraging_documentation.py | Ali-Parandeh/Data_Science_Playground | 0 | 6622316 | # load the Counter function into our environment
from collections import Counter
# View the documentation for Counter.most_common
help(Counter.most_common)
'''
Help on function most_common in module collections:
most_common(self, n=None)
List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# use Counter to find the top 5 most common words
top_5_words = Counter(words).most_common(5)
# display the top 5 most common words
print(top_5_words)
'''
<script.py> output:
[('@DataCamp', 299), ('to', 263), ('the', 251), ('in', 164), ('RT', 158)]
''' | # load the Counter function into our environment
from collections import Counter
# View the documentation for Counter.most_common
help(Counter.most_common)
'''
Help on function most_common in module collections:
most_common(self, n=None)
List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# use Counter to find the top 5 most common words
top_5_words = Counter(words).most_common(5)
# display the top 5 most common words
print(top_5_words)
'''
<script.py> output:
[('@DataCamp', 299), ('to', 263), ('the', 251), ('in', 164), ('RT', 158)]
''' | en | 0.711798 | # load the Counter function into our environment # View the documentation for Counter.most_common Help on function most_common in module collections: most_common(self, n=None) List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)] # use Counter to find the top 5 most common words # display the top 5 most common words <script.py> output: [('@DataCamp', 299), ('to', 263), ('the', 251), ('in', 164), ('RT', 158)] | 4.117953 | 4 |
pycon_project/apps/oauth_callbacks.py | pytexas/pycon | 1 | 6622317 | from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.shortcuts import render_to_response, redirect
from django.utils.translation import ugettext
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from pinax.apps.account.forms import SignupForm as PinaxSignupForm
from pinax.apps.account.utils import get_default_redirect, user_display
from oauth_access.access import OAuthAccess
def twitter_callback(request, access, token):
if not request.user.is_authenticated():
url = "https://twitter.com/account/verify_credentials.json"
user_data = access.make_api_call("json", url, token)
user = access.lookup_user(identifier=user_data["screen_name"])
if user is None:
request.session["oauth_signup_data"] = {
"token": token,
"user_data": user_data,
}
return redirect(
reverse(
"oauth_access_finish_signup", kwargs={
"service": access.service
}
)
)
else:
user.backend = "django.contrib.auth.backends.ModelBackend"
login(request, user)
else:
user = request.user
redirect_to = get_default_redirect(request)
access.persist(user, token)
return redirect(redirect_to)
def facebook_callback(request, access, token):
if not request.user.is_authenticated():
user_data = access.make_api_call("json", "https://graph.facebook.com/me", token)
user = access.lookup_user(identifier=user_data["id"])
if user is None:
request.session["oauth_signup_data"] = {
"token": token,
"user_data": user_data,
}
return redirect(
reverse(
"oauth_access_finish_signup", kwargs={
"service": access.service
}
)
)
else:
user.backend = "django.contrib.auth.backends.ModelBackend"
login(request, user)
else:
user = request.user
redirect_to = get_default_redirect(request)
access.persist(user, token)
return redirect(redirect_to)
class SignupForm(PinaxSignupForm):
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
del self.fields["password1"]
del self.fields["password2"]
def finish_signup(request, service):
access = OAuthAccess(service)
data = request.session.get("oauth_signup_data", None)
ctx = {}
if data["token"]:
if request.method == "POST":
form = SignupForm(request.POST)
# @@@ pulled from Pinax (a class based view would be awesome here
# to reduce duplication)
if form.is_valid():
success_url = get_default_redirect(request)
user = form.save(request=request)
if service == "twitter":
identifier = data["user_data"]["screen_name"]
elif service == "facebook":
identifier = data["user_data"]["id"]
access.persist(user, data["token"], identifier=identifier)
# del request.session["oauth_signup_data"]
if settings.ACCOUNT_EMAIL_VERIFICATION:
return render_to_response("account/verification_sent.html", {
"email": form.cleaned_data["email"],
}, context_instance=RequestContext(request))
else:
form.login(request, user)
messages.add_message(request, messages.SUCCESS,
ugettext("Successfully logged in as %(user)s.") % {
"user": user_display(user)
}
)
return redirect(success_url)
else:
initial = {}
if service == "twitter":
username = data["user_data"]["screen_name"]
if not User.objects.filter(username=username).exists():
initial["username"] = data["user_data"]["screen_name"]
else:
ctx["username_taken"] = username
form = SignupForm(initial=initial)
ctx.update({
"service": service,
"form": form,
})
ctx = RequestContext(request, ctx)
return render_to_response("oauth_access/finish_signup.html", ctx)
else:
return HttpResponse("no token!")
| from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.shortcuts import render_to_response, redirect
from django.utils.translation import ugettext
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from pinax.apps.account.forms import SignupForm as PinaxSignupForm
from pinax.apps.account.utils import get_default_redirect, user_display
from oauth_access.access import OAuthAccess
def twitter_callback(request, access, token):
if not request.user.is_authenticated():
url = "https://twitter.com/account/verify_credentials.json"
user_data = access.make_api_call("json", url, token)
user = access.lookup_user(identifier=user_data["screen_name"])
if user is None:
request.session["oauth_signup_data"] = {
"token": token,
"user_data": user_data,
}
return redirect(
reverse(
"oauth_access_finish_signup", kwargs={
"service": access.service
}
)
)
else:
user.backend = "django.contrib.auth.backends.ModelBackend"
login(request, user)
else:
user = request.user
redirect_to = get_default_redirect(request)
access.persist(user, token)
return redirect(redirect_to)
def facebook_callback(request, access, token):
if not request.user.is_authenticated():
user_data = access.make_api_call("json", "https://graph.facebook.com/me", token)
user = access.lookup_user(identifier=user_data["id"])
if user is None:
request.session["oauth_signup_data"] = {
"token": token,
"user_data": user_data,
}
return redirect(
reverse(
"oauth_access_finish_signup", kwargs={
"service": access.service
}
)
)
else:
user.backend = "django.contrib.auth.backends.ModelBackend"
login(request, user)
else:
user = request.user
redirect_to = get_default_redirect(request)
access.persist(user, token)
return redirect(redirect_to)
class SignupForm(PinaxSignupForm):
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
del self.fields["password1"]
del self.fields["password2"]
def finish_signup(request, service):
access = OAuthAccess(service)
data = request.session.get("oauth_signup_data", None)
ctx = {}
if data["token"]:
if request.method == "POST":
form = SignupForm(request.POST)
# @@@ pulled from Pinax (a class based view would be awesome here
# to reduce duplication)
if form.is_valid():
success_url = get_default_redirect(request)
user = form.save(request=request)
if service == "twitter":
identifier = data["user_data"]["screen_name"]
elif service == "facebook":
identifier = data["user_data"]["id"]
access.persist(user, data["token"], identifier=identifier)
# del request.session["oauth_signup_data"]
if settings.ACCOUNT_EMAIL_VERIFICATION:
return render_to_response("account/verification_sent.html", {
"email": form.cleaned_data["email"],
}, context_instance=RequestContext(request))
else:
form.login(request, user)
messages.add_message(request, messages.SUCCESS,
ugettext("Successfully logged in as %(user)s.") % {
"user": user_display(user)
}
)
return redirect(success_url)
else:
initial = {}
if service == "twitter":
username = data["user_data"]["screen_name"]
if not User.objects.filter(username=username).exists():
initial["username"] = data["user_data"]["screen_name"]
else:
ctx["username_taken"] = username
form = SignupForm(initial=initial)
ctx.update({
"service": service,
"form": form,
})
ctx = RequestContext(request, ctx)
return render_to_response("oauth_access/finish_signup.html", ctx)
else:
return HttpResponse("no token!")
| en | 0.836155 | # @@@ pulled from Pinax (a class based view would be awesome here # to reduce duplication) # del request.session["oauth_signup_data"] | 2.175012 | 2 |
python/run_app.py | tadayoni1/books | 0 | 6622318 | <reponame>tadayoni1/books
import os
from api._01_manual_response_class import app
# from api._02_make_response_helper import app
# from api._03_post_method import app
# from api._04_delete_method import app
# from api._05_flask_restful_simple import app
if __name__ == '__main__':
app.debug = True
app.config['DATABASE_NAME'] = 'library.db'
host = os.environ.get('IP', '0.0.0.0')
port = int(os.environ.get('PORT', 8080))
app.run(host=host, port=port)
| import os
from api._01_manual_response_class import app
# from api._02_make_response_helper import app
# from api._03_post_method import app
# from api._04_delete_method import app
# from api._05_flask_restful_simple import app
if __name__ == '__main__':
app.debug = True
app.config['DATABASE_NAME'] = 'library.db'
host = os.environ.get('IP', '0.0.0.0')
port = int(os.environ.get('PORT', 8080))
app.run(host=host, port=port) | en | 0.520443 | # from api._02_make_response_helper import app # from api._03_post_method import app # from api._04_delete_method import app # from api._05_flask_restful_simple import app | 1.92224 | 2 |
export_readiness/migrations/0039_auto_20190411_1206.py | uktrade/directory-cms | 6 | 6622319 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-04-11 12:06
from __future__ import unicode_literals
import core.model_fields
import core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('export_readiness', '0038_auto_20190402_1221'),
]
operations = [
migrations.AddField(
model_name='topiclandingpage',
name='banner_text',
field=core.model_fields.MarkdownField(blank=True, validators=[core.validators.slug_hyperlinks]),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-04-11 12:06
from __future__ import unicode_literals
import core.model_fields
import core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('export_readiness', '0038_auto_20190402_1221'),
]
operations = [
migrations.AddField(
model_name='topiclandingpage',
name='banner_text',
field=core.model_fields.MarkdownField(blank=True, validators=[core.validators.slug_hyperlinks]),
),
]
| en | 0.63279 | # -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-04-11 12:06 | 1.583027 | 2 |
code/dataset/base.py | lindsey98/Proxy-Anchor-CVPR2020 | 0 | 6622320 |
from __future__ import print_function
from __future__ import division
import os
import torch
import torchvision
import numpy as np
import PIL.Image
from shutil import copyfile
import time
from distutils.dir_util import copy_tree
class BaseDataset(torch.utils.data.Dataset):
def __init__(self, root, mode, transform = None):
self.root = root
self.mode = mode
self.transform = transform
self.ys, self.im_paths, self.I = [], [], []
def nb_classes(self):
assert set(self.ys) == set(self.classes)
return len(self.classes)
def __len__(self):
return len(self.ys)
def __getitem__(self, index):
def img_load(index):
im = PIL.Image.open(self.im_paths[index])
# convert gray to rgb
if len(list(im.split())) == 1 : im = im.convert('RGB')
if self.transform is not None:
im = self.transform(im)
return im
im = img_load(index)
target = self.ys[index]
return im, target
def get_label(self, index):
return self.ys[index]
def set_subset(self, I):
self.ys = [self.ys[i] for i in I]
self.I = [self.I[i] for i in I]
self.im_paths = [self.im_paths[i] for i in I]
class BaseDatasetMod(torch.utils.data.Dataset):
def __init__(self, root, source, classes, transform = None):
self.classes = classes
self.root = root
self.transform = transform
self.ys, self.im_paths, self.I = [], [], []
if not os.path.exists(root):
print('copying file from source to root')
print('from:', source)
print('to:', root)
c_time = time.time()
copy_tree(source, root)
elapsed = time.time() - c_time
print('done copying file: %.2fs', elapsed)
def nb_classes(self):
#print(self.classes)
#print(len(set(self.ys)), len(set(self.classes)))
#print(type(self.ys))
#print(len(set(self.ys) & set(self.classes)))
assert set(self.ys) == set(self.classes)
return len(self.classes)
def __len__(self):
return len(self.ys)
def __getitem__(self, index):
im = PIL.Image.open(self.im_paths[index])
# convert gray to rgb
if len(list(im.split())) == 1 : im = im.convert('RGB')
if self.transform is not None:
im = self.transform(im)
return im, self.ys[index], index
def get_label(self, index):
return self.ys[index]
def set_subset(self, I):
self.ys = [self.ys[i] for i in I]
self.I = [self.I[i] for i in I]
self.im_paths = [self.im_paths[i] for i in I]
|
from __future__ import print_function
from __future__ import division
import os
import torch
import torchvision
import numpy as np
import PIL.Image
from shutil import copyfile
import time
from distutils.dir_util import copy_tree
class BaseDataset(torch.utils.data.Dataset):
def __init__(self, root, mode, transform = None):
self.root = root
self.mode = mode
self.transform = transform
self.ys, self.im_paths, self.I = [], [], []
def nb_classes(self):
assert set(self.ys) == set(self.classes)
return len(self.classes)
def __len__(self):
return len(self.ys)
def __getitem__(self, index):
def img_load(index):
im = PIL.Image.open(self.im_paths[index])
# convert gray to rgb
if len(list(im.split())) == 1 : im = im.convert('RGB')
if self.transform is not None:
im = self.transform(im)
return im
im = img_load(index)
target = self.ys[index]
return im, target
def get_label(self, index):
return self.ys[index]
def set_subset(self, I):
self.ys = [self.ys[i] for i in I]
self.I = [self.I[i] for i in I]
self.im_paths = [self.im_paths[i] for i in I]
class BaseDatasetMod(torch.utils.data.Dataset):
def __init__(self, root, source, classes, transform = None):
self.classes = classes
self.root = root
self.transform = transform
self.ys, self.im_paths, self.I = [], [], []
if not os.path.exists(root):
print('copying file from source to root')
print('from:', source)
print('to:', root)
c_time = time.time()
copy_tree(source, root)
elapsed = time.time() - c_time
print('done copying file: %.2fs', elapsed)
def nb_classes(self):
#print(self.classes)
#print(len(set(self.ys)), len(set(self.classes)))
#print(type(self.ys))
#print(len(set(self.ys) & set(self.classes)))
assert set(self.ys) == set(self.classes)
return len(self.classes)
def __len__(self):
return len(self.ys)
def __getitem__(self, index):
im = PIL.Image.open(self.im_paths[index])
# convert gray to rgb
if len(list(im.split())) == 1 : im = im.convert('RGB')
if self.transform is not None:
im = self.transform(im)
return im, self.ys[index], index
def get_label(self, index):
return self.ys[index]
def set_subset(self, I):
self.ys = [self.ys[i] for i in I]
self.I = [self.I[i] for i in I]
self.im_paths = [self.im_paths[i] for i in I]
| en | 0.066712 | # convert gray to rgb #print(self.classes) #print(len(set(self.ys)), len(set(self.classes))) #print(type(self.ys)) #print(len(set(self.ys) & set(self.classes))) # convert gray to rgb | 2.481269 | 2 |
pylogflow/Pylogflow.py | JacobMaldonado/pylogflow | 0 | 6622321 | class IntentMap():
# Default constructor for init class
def __init__(self):
self.__map = {}
# Matches one intent to a method to execute
def add(self, intentName, method):
self.__map[intentName] = method
# execute an intent that matches with given in the response,
# the response will be an error method if an intent does not match
# return will be an dictionary
def execute_intent(self, request):
intentName = request["queryResult"]["intent"]["displayName"]
if intentName in self.__map:
return self.__map[intentName](request)
else:
return self.errorMethod()
# Error method triggered when intent does not match
def errorMethod(self):
agent = Agent()
agent.add_message("Intent does not found on intentMap")
return agent.get_response()
class Agent():
# Constructor of message building class
def __init__(self, req=None):
self.__message = {}
self.__request = req
# This mettod appends a message on the response
def add_message(self, msg):
if not "fulfillmentText" in self.__message:
self.__message["fulfillmentText"] = msg
if not "fulfillmentMessages" in self.__message:
self.__message["fulfillmentMessages"] = []
# Appends message in message array section for multiple response
self.__message["fulfillmentMessages"].append(
{"text": {
"text": [
msg
]
}}
)
# Add card to response
def add_card(self, title, subtitle, imageUri, buttonName, buttonLink):
if not "fulfillmentMessages" in self.__message:
self.__message["fulfillmentMessages"] = []
self.__message["fulfillmentMessages"].append(
{
"card": {
"title": title,
"subtitle": subtitle,
"imageUri": imageUri,
"buttons": [
{
"text": buttonName,
"postback": buttonLink
}
]
}
}
)
# Add custom payload response
def add_custom_response(self, response):
if not "fulfillmentMessages" in self.__message:
self.__message["fulfillmentMessages"] = []
self.__message["fulfillmentMessages"].append(response)
# Add custon payload
def add_custom_payload(self, response):
if not "payload" in self.__message:
self.__message["payload"] = {}
self.__message["payload"].update(response)
# Add Context
def add_context(self, name, lifespan, **params):
if not self.__request:
# TODO: Add exception
pass
if not 'outputContexts' in self.__message:
self.__message['outputContexts'] = []
self.__message['outputContexts'].append({
'name': self.__request.get('session') + '/contexts/' + name,
'lifespanCount': lifespan,
'parameters': params
})
# Get Response method
def get_response(self):
return self.__message
# To String method
def __str__(self):
return str(self.__message)
class DialogflowRequest():
# Constructor that accepts request
def __init__(self, request):
self.request = request
# Get all contexts
def get_contexts(self):
contexts = []
for elem in self.request.get('queryResult').get('outputContexts'):
elem['simpleName'] = elem.get('name')[elem.get('name').rfind('/') + 1:]
contexts.append(elem)
return contexts
# Get context by name if it exist or return None
def get_context_by_name(self, name):
for elem in self.request.get('queryResult').get('outputContexts'):
if name == elem.get('name')[elem.get('name').rfind('/') + 1:]:
return name
return None
# Return all parameters present in request
def get_params(self):
return self.request.get('queryResult').get('parameters')
# Return parameter by name
def get_param_by_name(self, name):
res = self.request.get('queryResult').get('parameters').get(name)
if res:
return {name : res}
else:
return None
class GoogleResponse():
# Constructor that defines if google must expet user response
def __init__(self, expectResponse=True):
self.hasSimpleResponse = False
self.hasSuggestionChips = False
self.hasDefaultSimpleResponse = False
self.hasDefaultSuggestionChip = False
self.__googleMessage = {
"google": {
"expectUserResponse": expectResponse,
"richResponse": {
"items": []
}
}
}
# Add Simple response
def add_simple_response(self, text):
# Change default message if its present
if self.hasDefaultSimpleResponse:
# search index of default response
for val,item in enumerate(self.__googleMessage["google"]["richResponse"]["items"]):
if "simpleResponse" in item:
index = val
break
self.__googleMessage["google"]["richResponse"]["items"][index]["simpleResponse"]["textToSpeech"] = text
self.hasDefaultSimpleResponse = False
else:
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__simple_response(text)
)
self.hasSimpleResponse = True
# Add card with ActionsOnGoogle style
def add_card(self, title, subtitle, imageUri, imageAccecibilityText, *objButtons):
self.__add_default_simple_response()
# Append card response
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__basic_card(title, subtitle, imageUri, imageAccecibilityText, *objButtons)
)
# Add browse carrousel to response
def add_browse_carrousel(self, *items):
self.__add_default_simple_response()
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__browse_carrousel(*items)
)
# Add Media Response
def add_media_response(self, name, description, iconUrl, iconAccessibilityText, mediaUrl):
# Required simple response
self.__add_default_simple_response()
# Required suggestion chip
self.__add_default_suggestion_chip()
# Append media response
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__media_response( name, description, iconUrl, iconAccessibilityText, mediaUrl)
)
# Add Suggestion Chip to Response
def add_suggestion_chips(self, *names):
# Required default empty response
self.__add_default_simple_response()
# Sets the Suggestions array
if not "suggestions" in self.__googleMessage["google"]["richResponse"]:
self.__googleMessage["google"]["richResponse"]["suggestions"] = []
# Drop default suggestion chip
if self.hasDefaultSuggestionChip:
self.__googleMessage["google"]["richResponse"]["suggestions"].pop()
self.hasDefaultSuggestionChip = False
# Add suggestions
for name in names:
self.__googleMessage["google"]["richResponse"]["suggestions"].append(
self.__suggestion_chip(name)
)
self.hasSuggestionChips = True
# Add table to response
def add_table(self, header, *rows, **extraElements):
# Required simple response
self.__add_default_simple_response()
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__complex_table(header, *rows, **extraElements)
)
# Add list to response
def add_list(self, *items, **extraElements):
# Set up systemIntent if there is not present
if not "systemIntent" in self.__googleMessage["google"]:
self.__googleMessage["google"]["systemIntent"] = {}
self.__googleMessage["google"]["systemIntent"]["intent"] = "actions.intent.OPTION"
self.__googleMessage["google"]["systemIntent"]["data"] = {}
self.__googleMessage["google"]["systemIntent"]["data"]["@type"] = "type.googleapis.com/google.actions.v2.OptionValueSpec"
# Required simple response
self.__add_default_simple_response()
# append list response
self.__googleMessage["google"]["systemIntent"]["data"].update(
self.__list(*items,**extraElements)
)
# Add Carrousel to response
def add_carrousel(self, *items):
# Set up systemIntent if there is not present
if not "systemIntent" in self.__googleMessage["google"]:
self.__googleMessage["google"]["systemIntent"] = {}
self.__googleMessage["google"]["systemIntent"]["intent"] = "actions.intent.OPTION"
self.__googleMessage["google"]["systemIntent"]["data"] = {}
self.__googleMessage["google"]["systemIntent"]["data"]["@type"] = "type.googleapis.com/google.actions.v2.OptionValueSpec"
# Required simple response
self.__add_default_simple_response()
# append list response
self.__googleMessage["google"]["systemIntent"]["data"].update(
self.__carrousel(*items)
)
# Add default simple response
def __add_default_simple_response(self):
# Add a white message because Google assistant need at least one simple message to display card
if not self.hasSimpleResponse:
self.add_simple_response(" ")
self.hasDefaultSimpleResponse = True
# Add default suggestion chips
def __add_default_suggestion_chip(self):
# Add suggestion chip named "Required suggestion" for media response and others that neeed suggestions
if not self.hasSuggestionChips:
# Add suggestions and set hasSuggestionChips to True
self.add_suggestion_chips("Required Suggestion")
self.hasDefaultSuggestionChip = True
# Simple response dictionary format
def __simple_response(self, text):
return {
"simpleResponse": {
"textToSpeech": text
}
}
# Basic Card dictionary format
def __basic_card(self, title, subtitle, imageUri, imageAccecibilityText, *buttons):
card = {
"basicCard": {
"title": title,
"subtitle": subtitle,
"formattedText": "",
"image": {
"url": imageUri,
"accessibilityText": imageAccecibilityText
},
"buttons": [],
"imageDisplayOptions": "WHITE"
}
}
for button in buttons:
card["basicCard"]["buttons"].append(button)
return card
# Browse Carrousel dictionary format
def __browse_carrousel(self, *items):
result = {
"carouselBrowse": {
"items": []
}
}
for item in items:
result["carouselBrowse"]["items"].append(item)
return result
# Media Response dictioonary format
def __media_response(self, name, description, iconUrl, iconAccessibilityText, mediaUrl):
return {
"mediaResponse": {
"mediaType": "AUDIO",
"mediaObjects": [
{
"contentUrl": mediaUrl,
"description": description,
"icon": {
"url": iconUrl,
"accessibilityText": iconAccessibilityText
},
"name": name
}
]
}
}
# Suggestion chips dictionary format
def __suggestion_chip(self, name):
return {
"title": name
}
# Simple Table in dictionary format
def __simple_table(self, header, *rows):
result = {
"tableCard":{
"rows": []
}
}
# append header and rows
result["tableCard"].update(header)
for row in rows:
result["tableCard"]["rows"].append(row)
return result
# Complex Table in dictionary format
def __complex_table(self, header, *rows, **extraElements):
result = self.__simple_table(header, *rows)
# if it has a subtitle, it needs title
if "title" in extraElements and "subtitle" in extraElements:
result["tableCard"]["title"] = extraElements["title"]
result["tableCard"]["subtitle"] = extraElements["subtitle"]
elif "title" in extraElements:
result["tableCard"]["title"] = extraElements["title"]
# if there is an image
if "imageUrl" in extraElements and "imageAccessibilityText" in extraElements:
result["tableCard"]["image"] = {
"url": extraElements["imageUrl"],
"accessibilityText": extraElements["imageAccessibilityText"]
}
# If there is not accessibilityText
elif "imageUrl" in extraElements:
result["tableCard"]["image"] = {
"url": extraElements["imageUrl"],
"accessibilityText": "Alt Text"
}
# if there is a button
if "buttonText" in extraElements and "buttonUrl":
result["tableCard"]["buttons"] = [self.generate_button(extraElements["buttonText"], extraElements["buttonUrl"])]
return result
# List in dictionary Format
def __list(self, *items, **extraElements ):
result = {
"listSelect": {
"items": []
}
}
# if Extra parameter "title" is there
if "title" in extraElements:
result["listSelect"]["title"] = extraElements["title"]
# append every item found
for item in items:
result["listSelect"]["items"].append(
item
)
return result
# Carrousel in dictionary Format
def __carrousel(self, *items):
result = {
"carouselSelect": {
"items": []
}
}
# append every item found
for item in items:
result["carouselSelect"]["items"].append(
item
)
return result
# Generate carrousel item in dictionary format
def generate_carrousel_item(self, title, key, synonymsList = [], description = "", imageUrl = "", imageAccecibilityText ="Alt Text"):
# These are same items, so we return an item list
return self.generate_list_item(title, key, synonymsList, description, imageUrl, imageAccecibilityText)
# Generate item list in dictionary format
def generate_list_item(self, title, key, synonymsList = [], description = "", imageUrl = "", imageAccecibilityText ="Alt Text"):
result = {
"optionInfo": {
"key": key
},
"title": title
}
if len(synonymsList) > 0:
result["optionInfo"]["synonyms"] = synonymsList
if description:
result["description"] = description
if imageUrl:
result["image"] = {}
result["image"]["url"] = imageUrl
result["image"]["accessibilityText"] = imageAccecibilityText
return result
# Row for Table response in dictionary format
def generate_table_row(self,*texts, **kwargs):
dividerAfter = True
if "dividerAfter" in kwargs:
dividerAfter = kwargs["dividerAfter"]
result = {
"cells": [],
"dividerAfter": dividerAfter
}
for text in texts:
result["cells"].append({"text": text})
return result
# Row of Headers for Table Response in dictionary format
def generate_table_header_row(self,*items):
result = {
"columnProperties": []
}
for item in items:
result["columnProperties"].append(item)
return result
# Header item for Table in dictionary format
def generate_table_header(self, text, alignment="CENTER"):
# TODO: add enum for alignment options
return {
"header": text,
"horizontalAlignment": alignment
}
# Item dictionary format
def generate_browse_carrousel_item(self, title, description, footer, imageUrl, imageAccecibilityText, urlAction):
return {
"title": title,
"description": description,
"footer": footer,
"image": {
"url": imageUrl,
"accessibilityText": imageAccecibilityText
},
"openUrlAction": {
"url": urlAction
}
}
# Generate a button of Actions on Google format
def generate_button(self, title, url):
return {
"title": title,
"openUrlAction": {
"url": url
}
}
def get_response(self):
return self.__googleMessage
# Class designed to manage request for Google Assistant
class GoogleRequest():
# Constructor with request in dictionary format
def __init__(self, request):
self.__request = request
# Search Arguments to handle input like list or carrousel
def get_option_arguments(self):
result = []
# get inputs
for element in self.__request["originalDetectIntentRequest"]["payload"]["inputs"]:
# get args
for arg in element["arguments"]:
# search for OPTION
if "name" in arg:
if arg["name"] == "OPTION":
result.append(arg["textValue"])
return result
# Search Capabilities of Google Assistant
def get_capabilities(self):
if "availableSurfaces" in self.__request["originalDetectIntentRequest"]["payload"]:
return self.__request["originalDetectIntentRequest"]["payload"]["availableSurfaces"][0]["capabilities"]
else:
return self.__request["originalDetectIntentRequest"]["payload"]["surface"]["capabilities"]
| class IntentMap():
# Default constructor for init class
def __init__(self):
self.__map = {}
# Matches one intent to a method to execute
def add(self, intentName, method):
self.__map[intentName] = method
# execute an intent that matches with given in the response,
# the response will be an error method if an intent does not match
# return will be an dictionary
def execute_intent(self, request):
intentName = request["queryResult"]["intent"]["displayName"]
if intentName in self.__map:
return self.__map[intentName](request)
else:
return self.errorMethod()
# Error method triggered when intent does not match
def errorMethod(self):
agent = Agent()
agent.add_message("Intent does not found on intentMap")
return agent.get_response()
class Agent():
# Constructor of message building class
def __init__(self, req=None):
self.__message = {}
self.__request = req
# This mettod appends a message on the response
def add_message(self, msg):
if not "fulfillmentText" in self.__message:
self.__message["fulfillmentText"] = msg
if not "fulfillmentMessages" in self.__message:
self.__message["fulfillmentMessages"] = []
# Appends message in message array section for multiple response
self.__message["fulfillmentMessages"].append(
{"text": {
"text": [
msg
]
}}
)
# Add card to response
def add_card(self, title, subtitle, imageUri, buttonName, buttonLink):
if not "fulfillmentMessages" in self.__message:
self.__message["fulfillmentMessages"] = []
self.__message["fulfillmentMessages"].append(
{
"card": {
"title": title,
"subtitle": subtitle,
"imageUri": imageUri,
"buttons": [
{
"text": buttonName,
"postback": buttonLink
}
]
}
}
)
# Add custom payload response
def add_custom_response(self, response):
if not "fulfillmentMessages" in self.__message:
self.__message["fulfillmentMessages"] = []
self.__message["fulfillmentMessages"].append(response)
# Add custon payload
def add_custom_payload(self, response):
if not "payload" in self.__message:
self.__message["payload"] = {}
self.__message["payload"].update(response)
# Add Context
def add_context(self, name, lifespan, **params):
if not self.__request:
# TODO: Add exception
pass
if not 'outputContexts' in self.__message:
self.__message['outputContexts'] = []
self.__message['outputContexts'].append({
'name': self.__request.get('session') + '/contexts/' + name,
'lifespanCount': lifespan,
'parameters': params
})
# Get Response method
def get_response(self):
return self.__message
# To String method
def __str__(self):
return str(self.__message)
class DialogflowRequest():
# Constructor that accepts request
def __init__(self, request):
self.request = request
# Get all contexts
def get_contexts(self):
contexts = []
for elem in self.request.get('queryResult').get('outputContexts'):
elem['simpleName'] = elem.get('name')[elem.get('name').rfind('/') + 1:]
contexts.append(elem)
return contexts
# Get context by name if it exist or return None
def get_context_by_name(self, name):
for elem in self.request.get('queryResult').get('outputContexts'):
if name == elem.get('name')[elem.get('name').rfind('/') + 1:]:
return name
return None
# Return all parameters present in request
def get_params(self):
return self.request.get('queryResult').get('parameters')
# Return parameter by name
def get_param_by_name(self, name):
res = self.request.get('queryResult').get('parameters').get(name)
if res:
return {name : res}
else:
return None
class GoogleResponse():
# Constructor that defines if google must expet user response
def __init__(self, expectResponse=True):
self.hasSimpleResponse = False
self.hasSuggestionChips = False
self.hasDefaultSimpleResponse = False
self.hasDefaultSuggestionChip = False
self.__googleMessage = {
"google": {
"expectUserResponse": expectResponse,
"richResponse": {
"items": []
}
}
}
# Add Simple response
def add_simple_response(self, text):
# Change default message if its present
if self.hasDefaultSimpleResponse:
# search index of default response
for val,item in enumerate(self.__googleMessage["google"]["richResponse"]["items"]):
if "simpleResponse" in item:
index = val
break
self.__googleMessage["google"]["richResponse"]["items"][index]["simpleResponse"]["textToSpeech"] = text
self.hasDefaultSimpleResponse = False
else:
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__simple_response(text)
)
self.hasSimpleResponse = True
# Add card with ActionsOnGoogle style
def add_card(self, title, subtitle, imageUri, imageAccecibilityText, *objButtons):
self.__add_default_simple_response()
# Append card response
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__basic_card(title, subtitle, imageUri, imageAccecibilityText, *objButtons)
)
# Add browse carrousel to response
def add_browse_carrousel(self, *items):
self.__add_default_simple_response()
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__browse_carrousel(*items)
)
# Add Media Response
def add_media_response(self, name, description, iconUrl, iconAccessibilityText, mediaUrl):
# Required simple response
self.__add_default_simple_response()
# Required suggestion chip
self.__add_default_suggestion_chip()
# Append media response
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__media_response( name, description, iconUrl, iconAccessibilityText, mediaUrl)
)
# Add Suggestion Chip to Response
def add_suggestion_chips(self, *names):
# Required default empty response
self.__add_default_simple_response()
# Sets the Suggestions array
if not "suggestions" in self.__googleMessage["google"]["richResponse"]:
self.__googleMessage["google"]["richResponse"]["suggestions"] = []
# Drop default suggestion chip
if self.hasDefaultSuggestionChip:
self.__googleMessage["google"]["richResponse"]["suggestions"].pop()
self.hasDefaultSuggestionChip = False
# Add suggestions
for name in names:
self.__googleMessage["google"]["richResponse"]["suggestions"].append(
self.__suggestion_chip(name)
)
self.hasSuggestionChips = True
# Add table to response
def add_table(self, header, *rows, **extraElements):
# Required simple response
self.__add_default_simple_response()
self.__googleMessage["google"]["richResponse"]["items"].append(
self.__complex_table(header, *rows, **extraElements)
)
# Add list to response
def add_list(self, *items, **extraElements):
# Set up systemIntent if there is not present
if not "systemIntent" in self.__googleMessage["google"]:
self.__googleMessage["google"]["systemIntent"] = {}
self.__googleMessage["google"]["systemIntent"]["intent"] = "actions.intent.OPTION"
self.__googleMessage["google"]["systemIntent"]["data"] = {}
self.__googleMessage["google"]["systemIntent"]["data"]["@type"] = "type.googleapis.com/google.actions.v2.OptionValueSpec"
# Required simple response
self.__add_default_simple_response()
# append list response
self.__googleMessage["google"]["systemIntent"]["data"].update(
self.__list(*items,**extraElements)
)
# Add Carrousel to response
def add_carrousel(self, *items):
# Set up systemIntent if there is not present
if not "systemIntent" in self.__googleMessage["google"]:
self.__googleMessage["google"]["systemIntent"] = {}
self.__googleMessage["google"]["systemIntent"]["intent"] = "actions.intent.OPTION"
self.__googleMessage["google"]["systemIntent"]["data"] = {}
self.__googleMessage["google"]["systemIntent"]["data"]["@type"] = "type.googleapis.com/google.actions.v2.OptionValueSpec"
# Required simple response
self.__add_default_simple_response()
# append list response
self.__googleMessage["google"]["systemIntent"]["data"].update(
self.__carrousel(*items)
)
# Add default simple response
def __add_default_simple_response(self):
# Add a white message because Google assistant need at least one simple message to display card
if not self.hasSimpleResponse:
self.add_simple_response(" ")
self.hasDefaultSimpleResponse = True
# Add default suggestion chips
def __add_default_suggestion_chip(self):
# Add suggestion chip named "Required suggestion" for media response and others that neeed suggestions
if not self.hasSuggestionChips:
# Add suggestions and set hasSuggestionChips to True
self.add_suggestion_chips("Required Suggestion")
self.hasDefaultSuggestionChip = True
# Simple response dictionary format
def __simple_response(self, text):
return {
"simpleResponse": {
"textToSpeech": text
}
}
# Basic Card dictionary format
def __basic_card(self, title, subtitle, imageUri, imageAccecibilityText, *buttons):
card = {
"basicCard": {
"title": title,
"subtitle": subtitle,
"formattedText": "",
"image": {
"url": imageUri,
"accessibilityText": imageAccecibilityText
},
"buttons": [],
"imageDisplayOptions": "WHITE"
}
}
for button in buttons:
card["basicCard"]["buttons"].append(button)
return card
# Browse Carrousel dictionary format
def __browse_carrousel(self, *items):
result = {
"carouselBrowse": {
"items": []
}
}
for item in items:
result["carouselBrowse"]["items"].append(item)
return result
# Media Response dictioonary format
def __media_response(self, name, description, iconUrl, iconAccessibilityText, mediaUrl):
return {
"mediaResponse": {
"mediaType": "AUDIO",
"mediaObjects": [
{
"contentUrl": mediaUrl,
"description": description,
"icon": {
"url": iconUrl,
"accessibilityText": iconAccessibilityText
},
"name": name
}
]
}
}
# Suggestion chips dictionary format
def __suggestion_chip(self, name):
return {
"title": name
}
# Simple Table in dictionary format
def __simple_table(self, header, *rows):
result = {
"tableCard":{
"rows": []
}
}
# append header and rows
result["tableCard"].update(header)
for row in rows:
result["tableCard"]["rows"].append(row)
return result
# Complex Table in dictionary format
def __complex_table(self, header, *rows, **extraElements):
result = self.__simple_table(header, *rows)
# if it has a subtitle, it needs title
if "title" in extraElements and "subtitle" in extraElements:
result["tableCard"]["title"] = extraElements["title"]
result["tableCard"]["subtitle"] = extraElements["subtitle"]
elif "title" in extraElements:
result["tableCard"]["title"] = extraElements["title"]
# if there is an image
if "imageUrl" in extraElements and "imageAccessibilityText" in extraElements:
result["tableCard"]["image"] = {
"url": extraElements["imageUrl"],
"accessibilityText": extraElements["imageAccessibilityText"]
}
# If there is not accessibilityText
elif "imageUrl" in extraElements:
result["tableCard"]["image"] = {
"url": extraElements["imageUrl"],
"accessibilityText": "Alt Text"
}
# if there is a button
if "buttonText" in extraElements and "buttonUrl":
result["tableCard"]["buttons"] = [self.generate_button(extraElements["buttonText"], extraElements["buttonUrl"])]
return result
# List in dictionary Format
def __list(self, *items, **extraElements ):
result = {
"listSelect": {
"items": []
}
}
# if Extra parameter "title" is there
if "title" in extraElements:
result["listSelect"]["title"] = extraElements["title"]
# append every item found
for item in items:
result["listSelect"]["items"].append(
item
)
return result
# Carrousel in dictionary Format
def __carrousel(self, *items):
result = {
"carouselSelect": {
"items": []
}
}
# append every item found
for item in items:
result["carouselSelect"]["items"].append(
item
)
return result
# Generate carrousel item in dictionary format
def generate_carrousel_item(self, title, key, synonymsList = [], description = "", imageUrl = "", imageAccecibilityText ="Alt Text"):
# These are same items, so we return an item list
return self.generate_list_item(title, key, synonymsList, description, imageUrl, imageAccecibilityText)
# Generate item list in dictionary format
def generate_list_item(self, title, key, synonymsList = [], description = "", imageUrl = "", imageAccecibilityText ="Alt Text"):
result = {
"optionInfo": {
"key": key
},
"title": title
}
if len(synonymsList) > 0:
result["optionInfo"]["synonyms"] = synonymsList
if description:
result["description"] = description
if imageUrl:
result["image"] = {}
result["image"]["url"] = imageUrl
result["image"]["accessibilityText"] = imageAccecibilityText
return result
# Row for Table response in dictionary format
def generate_table_row(self,*texts, **kwargs):
dividerAfter = True
if "dividerAfter" in kwargs:
dividerAfter = kwargs["dividerAfter"]
result = {
"cells": [],
"dividerAfter": dividerAfter
}
for text in texts:
result["cells"].append({"text": text})
return result
# Row of Headers for Table Response in dictionary format
def generate_table_header_row(self,*items):
result = {
"columnProperties": []
}
for item in items:
result["columnProperties"].append(item)
return result
# Header item for Table in dictionary format
def generate_table_header(self, text, alignment="CENTER"):
# TODO: add enum for alignment options
return {
"header": text,
"horizontalAlignment": alignment
}
# Item dictionary format
def generate_browse_carrousel_item(self, title, description, footer, imageUrl, imageAccecibilityText, urlAction):
return {
"title": title,
"description": description,
"footer": footer,
"image": {
"url": imageUrl,
"accessibilityText": imageAccecibilityText
},
"openUrlAction": {
"url": urlAction
}
}
# Generate a button of Actions on Google format
def generate_button(self, title, url):
return {
"title": title,
"openUrlAction": {
"url": url
}
}
def get_response(self):
return self.__googleMessage
# Class designed to manage request for Google Assistant
class GoogleRequest():
# Constructor with request in dictionary format
def __init__(self, request):
self.__request = request
# Search Arguments to handle input like list or carrousel
def get_option_arguments(self):
result = []
# get inputs
for element in self.__request["originalDetectIntentRequest"]["payload"]["inputs"]:
# get args
for arg in element["arguments"]:
# search for OPTION
if "name" in arg:
if arg["name"] == "OPTION":
result.append(arg["textValue"])
return result
# Search Capabilities of Google Assistant
def get_capabilities(self):
if "availableSurfaces" in self.__request["originalDetectIntentRequest"]["payload"]:
return self.__request["originalDetectIntentRequest"]["payload"]["availableSurfaces"][0]["capabilities"]
else:
return self.__request["originalDetectIntentRequest"]["payload"]["surface"]["capabilities"]
| en | 0.685899 | # Default constructor for init class # Matches one intent to a method to execute # execute an intent that matches with given in the response, # the response will be an error method if an intent does not match # return will be an dictionary # Error method triggered when intent does not match # Constructor of message building class # This mettod appends a message on the response # Appends message in message array section for multiple response # Add card to response # Add custom payload response # Add custon payload # Add Context # TODO: Add exception # Get Response method # To String method # Constructor that accepts request # Get all contexts # Get context by name if it exist or return None # Return all parameters present in request # Return parameter by name # Constructor that defines if google must expet user response # Add Simple response # Change default message if its present # search index of default response # Add card with ActionsOnGoogle style # Append card response # Add browse carrousel to response # Add Media Response # Required simple response # Required suggestion chip # Append media response # Add Suggestion Chip to Response # Required default empty response # Sets the Suggestions array # Drop default suggestion chip # Add suggestions # Add table to response # Required simple response # Add list to response # Set up systemIntent if there is not present # Required simple response # append list response # Add Carrousel to response # Set up systemIntent if there is not present # Required simple response # append list response # Add default simple response # Add a white message because Google assistant need at least one simple message to display card # Add default suggestion chips # Add suggestion chip named "Required suggestion" for media response and others that neeed suggestions # Add suggestions and set hasSuggestionChips to True # Simple response dictionary format # Basic Card dictionary format # Browse Carrousel dictionary format # Media Response dictioonary format # Suggestion chips dictionary format # Simple Table in dictionary format # append header and rows # Complex Table in dictionary format # if it has a subtitle, it needs title # if there is an image # If there is not accessibilityText # if there is a button # List in dictionary Format # if Extra parameter "title" is there # append every item found # Carrousel in dictionary Format # append every item found # Generate carrousel item in dictionary format # These are same items, so we return an item list # Generate item list in dictionary format # Row for Table response in dictionary format # Row of Headers for Table Response in dictionary format # Header item for Table in dictionary format # TODO: add enum for alignment options # Item dictionary format # Generate a button of Actions on Google format # Class designed to manage request for Google Assistant # Constructor with request in dictionary format # Search Arguments to handle input like list or carrousel # get inputs # get args # search for OPTION # Search Capabilities of Google Assistant | 3.077306 | 3 |
app/main.py | hadaskedar2020/calendar | 1 | 6622322 | <reponame>hadaskedar2020/calendar
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/")
def home(request: Request):
return templates.TemplateResponse("home.html", {
"request": request,
"message": "Hello, World!"
})
| from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/")
def home(request: Request):
return templates.TemplateResponse("home.html", {
"request": request,
"message": "Hello, World!"
}) | none | 1 | 2.558193 | 3 | |
world_model.py | dohyun1411/gpt3-sandbox | 0 | 6622323 | <gh_stars>0
from api import GPT, Example, set_openai_key
set_openai_key('<KEY>')
| from api import GPT, Example, set_openai_key
set_openai_key('<KEY>') | none | 1 | 1.277703 | 1 | |
mgui/mgui_root.py | Dreagonmon/micropython-mgui | 1 | 6622324 | from mgui import mgui_const as C
from mgui.mgui_utils import get_context
from mgui.utils.bmfont import FontDrawAscii
try:
import uasyncio as asyncio
from utime import ticks_ms as time_ms
from usys import print_exception
is_debug = False
except:
import asyncio
from time import time_ns as _time_ns
def time_ms():
return _time_ns() // 1_000_000
from traceback import print_exc as _p_e
def print_exception(*args, **kws):
_p_e()
is_debug = True
# useless import for type hints
try:
from typing import NoReturn, Coroutine, Any, Optional
from mgui.mgui_class import MGuiView, MGuiScreen, MGuiContext, MGuiEvent
from mgui.dev.framebuf import Color
from mgui.utils.bmfont import FontDraw
except: pass
class MGuiRoot(object):
def __init__(self, context=None):
# type: (Optional[MGuiContext]) -> None
if context == None:
context = dict()
context[C.CONTEXT_BG_COLOR] = get_context(context, C.CONTEXT_BG_COLOR, 0) # type Color
context[C.CONTEXT_FG_COLOR] = get_context(context, C.CONTEXT_FG_COLOR, 1) # type Color
context[C.CONTEXT_FRAME_RATE] = get_context(context, C.CONTEXT_FRAME_RATE, 15) # type int
context[C.CONTEXT_FRAME_DURATION] = get_context(context, C.CONTEXT_FRAME_DURATION, 1) # type int
context[C.CONTEXT_FONT_DRAW_OBJ] = get_context(context, C.CONTEXT_FONT_DRAW_OBJ, FontDrawAscii()) # type FontDraw
self.__context = context
self.__running = False
self.__lasttime = 0
def get_context(self):
return self.__context
def mainloop(self, root_view, screen):
loop = asyncio.get_event_loop()
if loop == None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.__running = True
loop.create_task(self.render_loop(root_view, screen))
loop.run_forever()
def stop(self):
self.__running = False
loop = asyncio.get_event_loop()
if loop != None:
loop.stop()
async def render_loop(self, root_view, screen):
# type: (MGuiView, MGuiScreen) -> Coroutine[Any, Any, NoReturn]
self.__context[C.CONTEXT_ROOT] = self
self.__context[C.CONTEXT_ROOT_VIEW] = root_view
try:
self.__lasttime = time_ms()
while self.__running:
await self.render_once(root_view, screen)
except KeyboardInterrupt:
# print("Abort.")
self.stop()
pass
async def render_once(self, root_view, screen):
s_w, s_h = screen.get_size()
frame = screen.get_framebuffer()
target_duration = 1000 // self.__context[C.CONTEXT_FRAME_RATE]
now = time_ms()
if now - self.__lasttime < target_duration:
await asyncio.sleep(0.0)
return
self.__context[C.CONTEXT_FRAME_DURATION] = now - self.__lasttime
self.__lasttime = now
# print(self.__context[CONTEXT_FRAME_DURATION])
try:
if root_view.need_render(self.__context):
effect_area = await root_view.render(self.__context, frame, (0, 0, s_w, s_h))
await screen.refresh(self.__context, effect_area)
except Exception as e:
if is_debug:
print_exception(e)
self.stop()
return
async def send_event(self, event):
# type: (MGuiEvent) -> bool
view = get_context(self.__context, C.CONTEXT_ROOT_VIEW, None)
if not isinstance(view, MGuiView):
return False
else:
return await view.on_event(self.__context, event)
| from mgui import mgui_const as C
from mgui.mgui_utils import get_context
from mgui.utils.bmfont import FontDrawAscii
try:
import uasyncio as asyncio
from utime import ticks_ms as time_ms
from usys import print_exception
is_debug = False
except:
import asyncio
from time import time_ns as _time_ns
def time_ms():
return _time_ns() // 1_000_000
from traceback import print_exc as _p_e
def print_exception(*args, **kws):
_p_e()
is_debug = True
# useless import for type hints
try:
from typing import NoReturn, Coroutine, Any, Optional
from mgui.mgui_class import MGuiView, MGuiScreen, MGuiContext, MGuiEvent
from mgui.dev.framebuf import Color
from mgui.utils.bmfont import FontDraw
except: pass
class MGuiRoot(object):
def __init__(self, context=None):
# type: (Optional[MGuiContext]) -> None
if context == None:
context = dict()
context[C.CONTEXT_BG_COLOR] = get_context(context, C.CONTEXT_BG_COLOR, 0) # type Color
context[C.CONTEXT_FG_COLOR] = get_context(context, C.CONTEXT_FG_COLOR, 1) # type Color
context[C.CONTEXT_FRAME_RATE] = get_context(context, C.CONTEXT_FRAME_RATE, 15) # type int
context[C.CONTEXT_FRAME_DURATION] = get_context(context, C.CONTEXT_FRAME_DURATION, 1) # type int
context[C.CONTEXT_FONT_DRAW_OBJ] = get_context(context, C.CONTEXT_FONT_DRAW_OBJ, FontDrawAscii()) # type FontDraw
self.__context = context
self.__running = False
self.__lasttime = 0
def get_context(self):
return self.__context
def mainloop(self, root_view, screen):
loop = asyncio.get_event_loop()
if loop == None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.__running = True
loop.create_task(self.render_loop(root_view, screen))
loop.run_forever()
def stop(self):
self.__running = False
loop = asyncio.get_event_loop()
if loop != None:
loop.stop()
async def render_loop(self, root_view, screen):
# type: (MGuiView, MGuiScreen) -> Coroutine[Any, Any, NoReturn]
self.__context[C.CONTEXT_ROOT] = self
self.__context[C.CONTEXT_ROOT_VIEW] = root_view
try:
self.__lasttime = time_ms()
while self.__running:
await self.render_once(root_view, screen)
except KeyboardInterrupt:
# print("Abort.")
self.stop()
pass
async def render_once(self, root_view, screen):
s_w, s_h = screen.get_size()
frame = screen.get_framebuffer()
target_duration = 1000 // self.__context[C.CONTEXT_FRAME_RATE]
now = time_ms()
if now - self.__lasttime < target_duration:
await asyncio.sleep(0.0)
return
self.__context[C.CONTEXT_FRAME_DURATION] = now - self.__lasttime
self.__lasttime = now
# print(self.__context[CONTEXT_FRAME_DURATION])
try:
if root_view.need_render(self.__context):
effect_area = await root_view.render(self.__context, frame, (0, 0, s_w, s_h))
await screen.refresh(self.__context, effect_area)
except Exception as e:
if is_debug:
print_exception(e)
self.stop()
return
async def send_event(self, event):
# type: (MGuiEvent) -> bool
view = get_context(self.__context, C.CONTEXT_ROOT_VIEW, None)
if not isinstance(view, MGuiView):
return False
else:
return await view.on_event(self.__context, event)
| en | 0.408489 | # useless import for type hints # type: (Optional[MGuiContext]) -> None # type Color # type Color # type int # type int # type FontDraw # type: (MGuiView, MGuiScreen) -> Coroutine[Any, Any, NoReturn] # print("Abort.") # print(self.__context[CONTEXT_FRAME_DURATION]) # type: (MGuiEvent) -> bool | 2.132463 | 2 |
unit_test/test_losses.py | One-sixth/model-utils-torch | 0 | 6622325 | import unittest
import torch
import math
from model_utils_torch.losses import *
class TestLosses(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def test_circle_loss(self):
batch_size = 6
feats = torch.rand(batch_size, 16)
classes = torch.randint(high=4, dtype=torch.long, size=(batch_size,))
self.assertTrue(circle_loss(feats, classes, 64, 0.25).item() >= 0)
def test_generalized_dice_loss(self):
pred = torch.rand([3, 5, 10, 10])
label = torch.rand([3, 5, 10, 10])
self.assertTrue(generalized_dice_loss(pred, label).item() >= 0)
| import unittest
import torch
import math
from model_utils_torch.losses import *
class TestLosses(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def test_circle_loss(self):
batch_size = 6
feats = torch.rand(batch_size, 16)
classes = torch.randint(high=4, dtype=torch.long, size=(batch_size,))
self.assertTrue(circle_loss(feats, classes, 64, 0.25).item() >= 0)
def test_generalized_dice_loss(self):
pred = torch.rand([3, 5, 10, 10])
label = torch.rand([3, 5, 10, 10])
self.assertTrue(generalized_dice_loss(pred, label).item() >= 0)
| none | 1 | 2.797864 | 3 | |
source/lambda/graph-modelling/index.py | songhuiming/sagemaker-graph-fraud-detection | 0 | 6622326 | <filename>source/lambda/graph-modelling/index.py<gh_stars>0
import os
import boto3
import tarfile
from time import strftime, gmtime
s3_client = boto3.client('s3')
def process_event(event, context):
print(event)
event_source_s3 = event['Records'][0]['s3']
print("S3 Put event source: {}".format(get_full_path(event_source_s3)))
train_input, msg = verify_modelling_inputs(event_source_s3)
print(msg)
if not train_input:
return msg
timestamp = strftime("%Y-%m-%d-%H-%M-%S", gmtime())
response = run_modelling_job(timestamp, train_input)
return response
def verify_modelling_inputs(event_source_s3):
training_kickoff_signal = "tags.csv"
if training_kickoff_signal not in event_source_s3['object']['key']:
msg = "Event source was not the training signal. Triggered by {} but expected folder to contain {}"
return False, msg.format(get_full_s3_path(event_source_s3['bucket']['name'], event_source_s3['object']['key']),
training_kickoff_signal)
training_folder = os.path.dirname(event_source_s3['object']['key'])
full_s3_training_folder = get_full_s3_path(event_source_s3['bucket']['name'], training_folder)
objects = s3_client.list_objects_v2(Bucket=event_source_s3['bucket']['name'], Prefix=training_folder)
files = [content['Key'] for content in objects['Contents']]
print("Contents of training data folder :")
print("\n".join(files))
minimum_expected_files = ['user_features.csv', 'tags.csv']
if not all([file in [os.path.basename(s3_file) for s3_file in files] for file in minimum_expected_files]):
return False, "Training data absent or incomplete in {}".format(full_s3_training_folder)
return full_s3_training_folder, "Minimum files needed for training present in {}".format(full_s3_training_folder)
def run_modelling_job(timestamp, train_input):
print("Creating SageMaker Training job with inputs from {}".format(train_input))
sagemaker_client = boto3.client('sagemaker')
region = boto3.session.Session().region_name
container = "520713654638.dkr.ecr.{}.amazonaws.com/sagemaker-mxnet:1.4.1-gpu-py3".format(region)
role = os.environ['training_job_role_arn']
training_job_name = "sagemaker-graph-fraud-model-training-{}".format(timestamp)
code_path = tar_and_upload_to_s3('dgl-fraud-detection', os.path.join(os.environ['training_job_output_s3_prefix'],
training_job_name, 'source'))
framework_params = {
'sagemaker_container_log_level': str(20),
'sagemaker_enable_cloudwatch_metrics': 'false',
'sagemaker_job_name': training_job_name,
'sagemaker_program': "train_dgl_entry_point.py",
'sagemaker_region': region,
'sagemaker_submit_directory': code_path
}
model_params = {
'nodes': 'user_features.csv',
'edges': get_edgelist(train_input),
'labels': 'tags.csv',
'model': 'rgcn',
'num-gpus': str(1),
'embedding-size': str(64),
'n-layers': str(1),
'n-epochs': str(100),
'optimizer': 'adam',
'lr': str(1e-2)
}
model_params.update(framework_params)
train_params = \
{
'TrainingJobName': training_job_name,
"AlgorithmSpecification": {
"TrainingImage": container,
"TrainingInputMode": "File"
},
"RoleArn": role,
"OutputDataConfig": {
"S3OutputPath": get_full_s3_path(os.environ['training_job_s3_bucket'],
os.path.join(os.environ['training_job_output_s3_prefix'],
training_job_name, 'output'))
},
"ResourceConfig": {
"InstanceCount": 1,
"InstanceType": os.environ['training_job_instance_type'],
"VolumeSizeInGB": 30
},
"HyperParameters": model_params,
"StoppingCondition": {
"MaxRuntimeInSeconds": 86400
},
"InputDataConfig": [
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": train_input,
"S3DataDistributionType": "FullyReplicated"
}
},
},
]
}
response = sagemaker_client.create_training_job(**train_params)
return response
def tar_and_upload_to_s3(source_file, s3_key):
filename = "/tmp/source.tar.gz"
with tarfile.open(filename, mode="w:gz") as t:
t.add(source_file, arcname=os.path.basename(source_file))
s3_client.upload_file(filename,
os.environ['training_job_s3_bucket'],
s3_key)
return get_full_s3_path(os.environ['training_job_s3_bucket'], s3_key)
def get_edgelist(training_folder):
training_folder = "/".join(training_folder.replace('s3://', '').split("/")[1:])
objects = s3_client.list_objects_v2(Bucket=os.environ['training_job_s3_bucket'], Prefix=training_folder)
files = [content['Key'] for content in objects['Contents']]
bipartite_edges = ",".join(map(lambda x: x.split("/")[-1], [file for file in files if "relation" in file]))
return bipartite_edges
def get_full_s3_path(bucket, key):
return os.path.join('s3://', bucket, key)
def get_full_path(event_source_s3):
return get_full_s3_path(event_source_s3['bucket']['name'], event_source_s3['object']['key'])
| <filename>source/lambda/graph-modelling/index.py<gh_stars>0
import os
import boto3
import tarfile
from time import strftime, gmtime
s3_client = boto3.client('s3')
def process_event(event, context):
print(event)
event_source_s3 = event['Records'][0]['s3']
print("S3 Put event source: {}".format(get_full_path(event_source_s3)))
train_input, msg = verify_modelling_inputs(event_source_s3)
print(msg)
if not train_input:
return msg
timestamp = strftime("%Y-%m-%d-%H-%M-%S", gmtime())
response = run_modelling_job(timestamp, train_input)
return response
def verify_modelling_inputs(event_source_s3):
training_kickoff_signal = "tags.csv"
if training_kickoff_signal not in event_source_s3['object']['key']:
msg = "Event source was not the training signal. Triggered by {} but expected folder to contain {}"
return False, msg.format(get_full_s3_path(event_source_s3['bucket']['name'], event_source_s3['object']['key']),
training_kickoff_signal)
training_folder = os.path.dirname(event_source_s3['object']['key'])
full_s3_training_folder = get_full_s3_path(event_source_s3['bucket']['name'], training_folder)
objects = s3_client.list_objects_v2(Bucket=event_source_s3['bucket']['name'], Prefix=training_folder)
files = [content['Key'] for content in objects['Contents']]
print("Contents of training data folder :")
print("\n".join(files))
minimum_expected_files = ['user_features.csv', 'tags.csv']
if not all([file in [os.path.basename(s3_file) for s3_file in files] for file in minimum_expected_files]):
return False, "Training data absent or incomplete in {}".format(full_s3_training_folder)
return full_s3_training_folder, "Minimum files needed for training present in {}".format(full_s3_training_folder)
def run_modelling_job(timestamp, train_input):
print("Creating SageMaker Training job with inputs from {}".format(train_input))
sagemaker_client = boto3.client('sagemaker')
region = boto3.session.Session().region_name
container = "520713654638.dkr.ecr.{}.amazonaws.com/sagemaker-mxnet:1.4.1-gpu-py3".format(region)
role = os.environ['training_job_role_arn']
training_job_name = "sagemaker-graph-fraud-model-training-{}".format(timestamp)
code_path = tar_and_upload_to_s3('dgl-fraud-detection', os.path.join(os.environ['training_job_output_s3_prefix'],
training_job_name, 'source'))
framework_params = {
'sagemaker_container_log_level': str(20),
'sagemaker_enable_cloudwatch_metrics': 'false',
'sagemaker_job_name': training_job_name,
'sagemaker_program': "train_dgl_entry_point.py",
'sagemaker_region': region,
'sagemaker_submit_directory': code_path
}
model_params = {
'nodes': 'user_features.csv',
'edges': get_edgelist(train_input),
'labels': 'tags.csv',
'model': 'rgcn',
'num-gpus': str(1),
'embedding-size': str(64),
'n-layers': str(1),
'n-epochs': str(100),
'optimizer': 'adam',
'lr': str(1e-2)
}
model_params.update(framework_params)
train_params = \
{
'TrainingJobName': training_job_name,
"AlgorithmSpecification": {
"TrainingImage": container,
"TrainingInputMode": "File"
},
"RoleArn": role,
"OutputDataConfig": {
"S3OutputPath": get_full_s3_path(os.environ['training_job_s3_bucket'],
os.path.join(os.environ['training_job_output_s3_prefix'],
training_job_name, 'output'))
},
"ResourceConfig": {
"InstanceCount": 1,
"InstanceType": os.environ['training_job_instance_type'],
"VolumeSizeInGB": 30
},
"HyperParameters": model_params,
"StoppingCondition": {
"MaxRuntimeInSeconds": 86400
},
"InputDataConfig": [
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": train_input,
"S3DataDistributionType": "FullyReplicated"
}
},
},
]
}
response = sagemaker_client.create_training_job(**train_params)
return response
def tar_and_upload_to_s3(source_file, s3_key):
filename = "/tmp/source.tar.gz"
with tarfile.open(filename, mode="w:gz") as t:
t.add(source_file, arcname=os.path.basename(source_file))
s3_client.upload_file(filename,
os.environ['training_job_s3_bucket'],
s3_key)
return get_full_s3_path(os.environ['training_job_s3_bucket'], s3_key)
def get_edgelist(training_folder):
training_folder = "/".join(training_folder.replace('s3://', '').split("/")[1:])
objects = s3_client.list_objects_v2(Bucket=os.environ['training_job_s3_bucket'], Prefix=training_folder)
files = [content['Key'] for content in objects['Contents']]
bipartite_edges = ",".join(map(lambda x: x.split("/")[-1], [file for file in files if "relation" in file]))
return bipartite_edges
def get_full_s3_path(bucket, key):
return os.path.join('s3://', bucket, key)
def get_full_path(event_source_s3):
return get_full_s3_path(event_source_s3['bucket']['name'], event_source_s3['object']['key'])
| none | 1 | 2.232861 | 2 | |
shakenfist/alembic/versions/6423651f41b1_add_order_to_network_interfaces.py | bradh/shakenfist | 0 | 6622327 | <reponame>bradh/shakenfist
"""Add order to networkinterfaces.
Revision ID: 6423651f41b1
Revises: <KEY>
Create Date: 2020-04-04 12:57:43.336424
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('network_interfaces', sa.Column('order', sa.Integer))
def downgrade():
op.drop_column('instances', 'order')
| """Add order to networkinterfaces.
Revision ID: 6423651f41b1
Revises: <KEY>
Create Date: 2020-04-04 12:57:43.336424
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('network_interfaces', sa.Column('order', sa.Integer))
def downgrade():
op.drop_column('instances', 'order') | en | 0.502213 | Add order to networkinterfaces. Revision ID: 6423651f41b1 Revises: <KEY> Create Date: 2020-04-04 12:57:43.336424 # revision identifiers, used by Alembic. | 1.221995 | 1 |
TestCase/test_search.py | LiuTianen/AppiumTestDemo | 0 | 6622328 | <filename>TestCase/test_search.py
from app import App
import time
class TestSearch:
def setup(self):
self.search_page=App.start().to_search()
def test_search_po(self):
self.search_page.search("alibaba")
assert self.search_page.get_current_price() > "10"
self.search_page.close()
time.sleep(10)
def teardown(self):
App.quit()
| <filename>TestCase/test_search.py
from app import App
import time
class TestSearch:
def setup(self):
self.search_page=App.start().to_search()
def test_search_po(self):
self.search_page.search("alibaba")
assert self.search_page.get_current_price() > "10"
self.search_page.close()
time.sleep(10)
def teardown(self):
App.quit()
| none | 1 | 2.737685 | 3 | |
djangoproject/notifications/models.py | moonmirXD/E-barangay | 0 | 6622329 | <reponame>moonmirXD/E-barangay<gh_stars>0
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.conf import settings
User = settings.AUTH_USER_MODEL
concern_choices = [
('Requested Document','Requested Document'),
('Complaint','Complaint'),
]
class Send_notification(models.Model):
#user_reciever = models.ForeignKey(User,max_length=100,on_delete =models.CASCADE)
title = models.CharField(max_length=100, default='SOMESTRING')
notification_concern = models.CharField(max_length=100,choices=concern_choices,blank=True )
content = models.TextField(max_length=255)
date_sent = models.DateTimeField(default = timezone.now)
sender = models.ForeignKey(User,on_delete=models.CASCADE) # sender to user
def __str__(self):
return self.notification_concern
# def get_absolute_url(self):
# return reverse('post-detail', kwargs={'pk':self.pk})
| from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.conf import settings
User = settings.AUTH_USER_MODEL
concern_choices = [
('Requested Document','Requested Document'),
('Complaint','Complaint'),
]
class Send_notification(models.Model):
#user_reciever = models.ForeignKey(User,max_length=100,on_delete =models.CASCADE)
title = models.CharField(max_length=100, default='SOMESTRING')
notification_concern = models.CharField(max_length=100,choices=concern_choices,blank=True )
content = models.TextField(max_length=255)
date_sent = models.DateTimeField(default = timezone.now)
sender = models.ForeignKey(User,on_delete=models.CASCADE) # sender to user
def __str__(self):
return self.notification_concern
# def get_absolute_url(self):
# return reverse('post-detail', kwargs={'pk':self.pk}) | en | 0.368857 | #user_reciever = models.ForeignKey(User,max_length=100,on_delete =models.CASCADE) # sender to user # def get_absolute_url(self): # return reverse('post-detail', kwargs={'pk':self.pk}) | 2.192868 | 2 |
MacOSX/Firefly Activity Access/python/activity/datastore.py | mpkasp/firefly-ice-api | 0 | 6622330 | import datetime
from dateutil import parser
import json
import os
import struct
class HardwareRange:
def __init__(self, hardware_identifier=None, start=None, end=None):
self.hardware_identifier = hardware_identifier
self.start = start
self.end = end
def __repr__(self):
return "HardwareRange(" + repr(self.hardware_identifier) + ", " + repr(self.start) + ", " + repr(self.end) + ")"
class NameRange:
def __init__(self, name, hardware_ranges):
self.name = name
self.hardware_ranges = hardware_ranges
def __repr__(self):
return "NameRange(" + repr(self.name) + ", " + repr(self.hardware_ranges) + ")"
class Naming:
def __init__(self, name, hardware_identifier, start):
self.name = name
self.hardware_identifier = hardware_identifier
self.start = start
self.hardware_ranges = []
class NameRangeExtractor:
def __init__(self):
self.namingByHardwareIdentifier = {}
def process(self, item):
type = item['type']
try:
method = getattr(self, type)
method(item)
except AttributeError:
pass
def nameDevice(self, item):
date = parser.parse(item['date']).timestamp()
value = item['value']
name = value['name']
hardware_identifier = value['hardwareIdentifier']
naming = self.namingByHardwareIdentifier.get(hardware_identifier)
if naming is None:
self.namingByHardwareIdentifier[hardware_identifier] = Naming(name, hardware_identifier, date)
else:
if naming.hardware_identifier is None:
naming.hardware_identifier = hardware_identifier
naming.start = date
else:
if naming.hardware_identifier != hardware_identifier:
naming.hardware_ranges.append(HardwareRange(naming.hardware_identifier, naming.start, date))
naming.hardware_identifier = hardware_identifier
naming.start = date
def forgetDevice(self, item):
date = parser.parse(item['date']).timestamp()
value = item['value']
name = value['name']
hardware_identifier = value['hardwareIdentifier']
naming = self.namingByHardwareIdentifier.get(hardware_identifier)
if naming is None:
naming = Naming(name, None, None)
self.namingByHardwareIdentifier[hardware_identifier] = naming
naming.hardware_ranges.append(HardwareRange(naming.hardware_identifier, naming.start, date))
naming.hardware_identifier = None
naming.start = None
def name_ranges(self):
name_ranges = []
for hardware_identifier, naming in self.namingByHardwareIdentifier.items():
if naming.start is not None:
naming.hardware_ranges.append(HardwareRange(naming.hardware_identifier, naming.start, None))
name_ranges.append(NameRange(naming.name, naming.hardware_ranges))
return name_ranges
class StudyIdentifierExtractor:
def __init__(self):
self.studyIdentifier = None
def process(self, item):
type = item['type']
try:
method = getattr(self, type)
method(item)
except AttributeError:
pass
def saveStudy(self, item):
value = item['value']
self.studyIdentifier = value['studyIdentifier']
class Datastore:
def __init__(self, path):
self.path = path
def list(self):
installations = []
installation_uuids = os.listdir(self.path)
for installation_uuid in installation_uuids:
installation_uuid_path = os.path.join(self.path, installation_uuid)
name_range_extractor = NameRangeExtractor()
study_identifier_extractor = StudyIdentifierExtractor()
datastores = os.listdir(installation_uuid_path)
for datastore in datastores:
datastore_path = os.path.join(installation_uuid_path, datastore)
if datastore == 'history':
days = sorted(os.listdir(datastore_path))
for day in days:
day_path = os.path.join(datastore_path, day)
with open(day_path) as file:
for _, line in enumerate(file):
item = json.loads(line)
name_range_extractor.process(item)
study_identifier_extractor.process(item)
elif datastore.startswith('FireflyIce-'):
pass
installations.append({
"installationUUID": installation_uuid,
"name_ranges": name_range_extractor.name_ranges(),
'study_identifier': study_identifier_extractor.studyIdentifier
})
return installations
class ActivitySpan:
def __init__(self, time, interval, vmas):
self.time = time
self.interval = interval
self.vmas = vmas
def __repr__(self):
return "ActivitySpan(" + repr(self.time) + ", " + repr(self.interval) + ", " + repr(self.vmas) + ")"
class FDBinary:
def __init__(self, data):
self.data = data
self.index = 0
def get_remaining_length(self):
return len(self.data) - self.index
def get_uint32(self):
value = struct.unpack('<I', self.data[self.index:self.index + 4])[0]
self.index += 4
return value
def get_float32(self):
value = struct.unpack('<f', self.data[self.index:self.index + 4])[0]
self.index += 4
return value
class ActivityDatastore:
def __init__(self, root, installation_uuid, hardware_identifier):
self.bytes_per_record = 8
self.interval = 10
self.extension = ".dat"
self.root = root
self.installation_uuid = installation_uuid
self.hardware_identifier = hardware_identifier
self.data = None
self.start = None
self.end = None
def load(self, day):
start = datetime.datetime.strptime(day + " UTC", "%Y-%m-%d %Z")
self.start = start.timestamp()
self.end = (start + datetime.timedelta(days=1)).timestamp()
path = os.path.join(self.root, self.installation_uuid, self.hardware_identifier, day + self.extension)
with open(path, "rb") as file:
self.data = file.read()
@staticmethod
def days_in_range(start, end):
days = []
start_of_day = datetime.datetime.fromtimestamp(start).replace(hour=0, minute=0, second=0, microsecond=0)
end_datetime = datetime.datetime.fromtimestamp(end)
while start_of_day < end_datetime:
days.append(start_of_day.strftime("%Y-%m-%d"))
start_of_day += datetime.timedelta(days=1)
return days
def query(self, start, end):
spans = []
vmas = []
last_time = 0
days = ActivityDatastore.days_in_range(start, end)
for day in days:
try:
self.load(day)
except:
continue
time = self.start
binary = FDBinary(self.data)
while binary.get_remaining_length() >= self.bytes_per_record:
flags = binary.get_uint32()
vma = binary.get_float32()
if (start < time) and (time < end):
valid = flags != 0
if valid:
if not vmas:
last_time = time
vmas.append(vma)
else:
if vmas:
spans.append(ActivitySpan(last_time, self.interval, list(vmas)))
last_time = 0
vmas.clear()
time += self.interval
if vmas:
spans.append(ActivitySpan(last_time, self.interval, vmas))
return spans
| import datetime
from dateutil import parser
import json
import os
import struct
class HardwareRange:
def __init__(self, hardware_identifier=None, start=None, end=None):
self.hardware_identifier = hardware_identifier
self.start = start
self.end = end
def __repr__(self):
return "HardwareRange(" + repr(self.hardware_identifier) + ", " + repr(self.start) + ", " + repr(self.end) + ")"
class NameRange:
def __init__(self, name, hardware_ranges):
self.name = name
self.hardware_ranges = hardware_ranges
def __repr__(self):
return "NameRange(" + repr(self.name) + ", " + repr(self.hardware_ranges) + ")"
class Naming:
def __init__(self, name, hardware_identifier, start):
self.name = name
self.hardware_identifier = hardware_identifier
self.start = start
self.hardware_ranges = []
class NameRangeExtractor:
def __init__(self):
self.namingByHardwareIdentifier = {}
def process(self, item):
type = item['type']
try:
method = getattr(self, type)
method(item)
except AttributeError:
pass
def nameDevice(self, item):
date = parser.parse(item['date']).timestamp()
value = item['value']
name = value['name']
hardware_identifier = value['hardwareIdentifier']
naming = self.namingByHardwareIdentifier.get(hardware_identifier)
if naming is None:
self.namingByHardwareIdentifier[hardware_identifier] = Naming(name, hardware_identifier, date)
else:
if naming.hardware_identifier is None:
naming.hardware_identifier = hardware_identifier
naming.start = date
else:
if naming.hardware_identifier != hardware_identifier:
naming.hardware_ranges.append(HardwareRange(naming.hardware_identifier, naming.start, date))
naming.hardware_identifier = hardware_identifier
naming.start = date
def forgetDevice(self, item):
date = parser.parse(item['date']).timestamp()
value = item['value']
name = value['name']
hardware_identifier = value['hardwareIdentifier']
naming = self.namingByHardwareIdentifier.get(hardware_identifier)
if naming is None:
naming = Naming(name, None, None)
self.namingByHardwareIdentifier[hardware_identifier] = naming
naming.hardware_ranges.append(HardwareRange(naming.hardware_identifier, naming.start, date))
naming.hardware_identifier = None
naming.start = None
def name_ranges(self):
name_ranges = []
for hardware_identifier, naming in self.namingByHardwareIdentifier.items():
if naming.start is not None:
naming.hardware_ranges.append(HardwareRange(naming.hardware_identifier, naming.start, None))
name_ranges.append(NameRange(naming.name, naming.hardware_ranges))
return name_ranges
class StudyIdentifierExtractor:
def __init__(self):
self.studyIdentifier = None
def process(self, item):
type = item['type']
try:
method = getattr(self, type)
method(item)
except AttributeError:
pass
def saveStudy(self, item):
value = item['value']
self.studyIdentifier = value['studyIdentifier']
class Datastore:
def __init__(self, path):
self.path = path
def list(self):
installations = []
installation_uuids = os.listdir(self.path)
for installation_uuid in installation_uuids:
installation_uuid_path = os.path.join(self.path, installation_uuid)
name_range_extractor = NameRangeExtractor()
study_identifier_extractor = StudyIdentifierExtractor()
datastores = os.listdir(installation_uuid_path)
for datastore in datastores:
datastore_path = os.path.join(installation_uuid_path, datastore)
if datastore == 'history':
days = sorted(os.listdir(datastore_path))
for day in days:
day_path = os.path.join(datastore_path, day)
with open(day_path) as file:
for _, line in enumerate(file):
item = json.loads(line)
name_range_extractor.process(item)
study_identifier_extractor.process(item)
elif datastore.startswith('FireflyIce-'):
pass
installations.append({
"installationUUID": installation_uuid,
"name_ranges": name_range_extractor.name_ranges(),
'study_identifier': study_identifier_extractor.studyIdentifier
})
return installations
class ActivitySpan:
def __init__(self, time, interval, vmas):
self.time = time
self.interval = interval
self.vmas = vmas
def __repr__(self):
return "ActivitySpan(" + repr(self.time) + ", " + repr(self.interval) + ", " + repr(self.vmas) + ")"
class FDBinary:
def __init__(self, data):
self.data = data
self.index = 0
def get_remaining_length(self):
return len(self.data) - self.index
def get_uint32(self):
value = struct.unpack('<I', self.data[self.index:self.index + 4])[0]
self.index += 4
return value
def get_float32(self):
value = struct.unpack('<f', self.data[self.index:self.index + 4])[0]
self.index += 4
return value
class ActivityDatastore:
def __init__(self, root, installation_uuid, hardware_identifier):
self.bytes_per_record = 8
self.interval = 10
self.extension = ".dat"
self.root = root
self.installation_uuid = installation_uuid
self.hardware_identifier = hardware_identifier
self.data = None
self.start = None
self.end = None
def load(self, day):
start = datetime.datetime.strptime(day + " UTC", "%Y-%m-%d %Z")
self.start = start.timestamp()
self.end = (start + datetime.timedelta(days=1)).timestamp()
path = os.path.join(self.root, self.installation_uuid, self.hardware_identifier, day + self.extension)
with open(path, "rb") as file:
self.data = file.read()
@staticmethod
def days_in_range(start, end):
days = []
start_of_day = datetime.datetime.fromtimestamp(start).replace(hour=0, minute=0, second=0, microsecond=0)
end_datetime = datetime.datetime.fromtimestamp(end)
while start_of_day < end_datetime:
days.append(start_of_day.strftime("%Y-%m-%d"))
start_of_day += datetime.timedelta(days=1)
return days
def query(self, start, end):
spans = []
vmas = []
last_time = 0
days = ActivityDatastore.days_in_range(start, end)
for day in days:
try:
self.load(day)
except:
continue
time = self.start
binary = FDBinary(self.data)
while binary.get_remaining_length() >= self.bytes_per_record:
flags = binary.get_uint32()
vma = binary.get_float32()
if (start < time) and (time < end):
valid = flags != 0
if valid:
if not vmas:
last_time = time
vmas.append(vma)
else:
if vmas:
spans.append(ActivitySpan(last_time, self.interval, list(vmas)))
last_time = 0
vmas.clear()
time += self.interval
if vmas:
spans.append(ActivitySpan(last_time, self.interval, vmas))
return spans
| none | 1 | 2.856005 | 3 | |
batch.py | sorz/asstosrt | 240 | 6622331 | from __future__ import print_function
import argparse
import codecs
import sys
import os
import asstosrt
from asstosrt import translate
def _get_args():
parser = argparse.ArgumentParser(description='A useful tool that \
convert Advanced SubStation Alpha (ASS/SSA) subtitle files \
to SubRip (SRT) subtitle files.',
epilog='Auther: @xierch <<EMAIL>>; \
bug report: https://github.com/bluen/asstosrt')
parser.add_argument('-e', '--encoding',
help='charset of input ASS file (default: auto detect)')
parser.add_argument('-t', '--translate-to', dest='language',
help='set "zh-hans" for Simplified Chinese, \
"zh-hant" for Traditional Chinese (need langconv)')
parser.add_argument('-c', '--opencc', dest='opencc_config',
help="Use OpenCC to convert Simplified/Traditional Chinese "
"(need pyopencc)'")
parser.add_argument('-n', '--no-effact', action="store_true",
help='ignore all effact text')
parser.add_argument('-l', '--only-first-line', action="store_true",
help='remove other lines on each dialogue')
parser.add_argument('-s', '--srt-encoding',
help='charset of output SRT file (default: same as ASS)')
parser.add_argument('-o', '--output-dir', default=os.getcwd(),
help='output directory (default: current directory)')
parser.add_argument('-f', '--force', action="store_true",
help='force overwrite exist SRT files')
parser.add_argument('files', nargs='*',
help='paths of ASS/SSA files (default: all on current directory)')
return parser.parse_args()
def _check_chardet():
"""Import chardet or exit."""
global chardet
try:
import chardet
except ImportError:
print('Error: module "chardet" not found.\nPlease install it ' + \
'(pip install chardet) or specify a encoding (-e utf-8).',
file=sys.stderr)
sys.exit(1)
def _detect_charset(file):
"""Try detect the charset of file, return the name of charset or exit."""
bytes = file.read(4096)
file.seek(0)
c = chardet.detect(bytes)
if c['confidence'] < 0.3:
print('Error: unknown file encoding, ' + \
'please specify one by -e.', file=sys.stderr)
sys.exit(1)
elif c['confidence'] < 0.6:
print('Warning: uncertain file encoding, ' + \
'suggest specify one by -e.', file=sys.stderr)
if c['encoding'] == 'GB2312':
return 'GB18030'
return c['encoding']
CODECS_BOM = {
'utf-16': codecs.BOM_UTF16,
'utf-16-le': codecs.BOM_UTF16_LE,
'utf-16-be': codecs.BOM_UTF16_BE,
'utf-32': codecs.BOM_UTF16,
'utf-32-le': codecs.BOM_UTF32_LE,
'utf-32-be': codecs.BOM_UTF32_BE,
}
def get_bom(codec):
"""Return the BOM of UTF-16/32 or empty str."""
if codec.name in CODECS_BOM:
return CODECS_BOM[codec.name]
else:
return b''
def _files_on_cwd():
"""Return all ASS/SSA file on current working directory. """
files = []
for file in os.listdir(os.getcwd()):
if file.startswith('.'):
continue
if file.endswith('.ass'):
files.append(file)
elif file.endswith('.ssa'):
files.append(file)
return files
def _combine_output_file_path(in_files, output_dir):
files = []
for file in in_files:
name = os.path.splitext(os.path.basename(file))[0] + '.srt'
path = os.path.join(output_dir, name)
files.append((file, path))
return files
def _convert_files(files, args):
if args.encoding:
in_codec = codecs.lookup(args.encoding)
else:
in_codec = None
if args.srt_encoding:
out_codec = codecs.lookup(args.srt_encoding)
else:
out_codec = in_codec
sum = len(files)
done = 0
fail = 0
ignore = 0
print("Found {} file(s), converting...".format(sum))
for in_path, out_path in _combine_output_file_path(files, args.output_dir):
print("\t({:02d}/{:02d}) is converting... " \
.format(done + fail + ignore + 1, sum), end='')
if not args.force and os.path.exists(out_path):
print('[ignore] (SRT exists)')
ignore += 1
continue
try:
with open(in_path, 'rb') as in_file:
if args.encoding is None: # Detect file charset.
in_codec = codecs.lookup(_detect_charset(in_file))
if args.srt_encoding is None:
out_codec = in_codec
out_str = asstosrt.convert(in_codec.streamreader(in_file),
args.translator, args.no_effact, args.only_first_line)
with open(out_path, 'wb') as out_file:
out_file.write(get_bom(out_codec))
out_file.write(out_codec.encode(out_str)[0])
done += 1
print('[done]')
except (UnicodeDecodeError, UnicodeEncodeError, LookupError) as e:
print('[fail] (codec error)')
print(e, file=sys.stderr)
fail += 1
except ValueError as e:
print('[fail] (irregular format)')
print(e, file=sys.stderr)
fail += 1
except IOError as e:
print('[fail] (IO error)')
print(e, file=sys.stderr)
fail += 1
print("All done:\n\t{} success, {} ignore, {} fail." \
.format(done, ignore, sum - done - ignore))
def main():
args = _get_args()
if args.encoding is None: # Enable auto detect
_check_chardet()
try:
if args.language is not None:
args.translator = translate.LangconvTranslator(args.language)
elif args.opencc_config is not None:
args.translator = translate.OpenCCTranslator(args.opencc_config)
else:
args.translator = None
except ImportError as e:
print("Error: {}\nPlease install it or disable "
"translation.".format(e.message))
sys.exit(1)
files = args.files
if not files:
files = _files_on_cwd()
if not files:
print('ASS/SSA file no found.\nTry --help for more information',
file=sys.stderr)
sys.exit(1)
_convert_files(files, args)
if __name__ == '__main__':
main() | from __future__ import print_function
import argparse
import codecs
import sys
import os
import asstosrt
from asstosrt import translate
def _get_args():
parser = argparse.ArgumentParser(description='A useful tool that \
convert Advanced SubStation Alpha (ASS/SSA) subtitle files \
to SubRip (SRT) subtitle files.',
epilog='Auther: @xierch <<EMAIL>>; \
bug report: https://github.com/bluen/asstosrt')
parser.add_argument('-e', '--encoding',
help='charset of input ASS file (default: auto detect)')
parser.add_argument('-t', '--translate-to', dest='language',
help='set "zh-hans" for Simplified Chinese, \
"zh-hant" for Traditional Chinese (need langconv)')
parser.add_argument('-c', '--opencc', dest='opencc_config',
help="Use OpenCC to convert Simplified/Traditional Chinese "
"(need pyopencc)'")
parser.add_argument('-n', '--no-effact', action="store_true",
help='ignore all effact text')
parser.add_argument('-l', '--only-first-line', action="store_true",
help='remove other lines on each dialogue')
parser.add_argument('-s', '--srt-encoding',
help='charset of output SRT file (default: same as ASS)')
parser.add_argument('-o', '--output-dir', default=os.getcwd(),
help='output directory (default: current directory)')
parser.add_argument('-f', '--force', action="store_true",
help='force overwrite exist SRT files')
parser.add_argument('files', nargs='*',
help='paths of ASS/SSA files (default: all on current directory)')
return parser.parse_args()
def _check_chardet():
"""Import chardet or exit."""
global chardet
try:
import chardet
except ImportError:
print('Error: module "chardet" not found.\nPlease install it ' + \
'(pip install chardet) or specify a encoding (-e utf-8).',
file=sys.stderr)
sys.exit(1)
def _detect_charset(file):
"""Try detect the charset of file, return the name of charset or exit."""
bytes = file.read(4096)
file.seek(0)
c = chardet.detect(bytes)
if c['confidence'] < 0.3:
print('Error: unknown file encoding, ' + \
'please specify one by -e.', file=sys.stderr)
sys.exit(1)
elif c['confidence'] < 0.6:
print('Warning: uncertain file encoding, ' + \
'suggest specify one by -e.', file=sys.stderr)
if c['encoding'] == 'GB2312':
return 'GB18030'
return c['encoding']
CODECS_BOM = {
'utf-16': codecs.BOM_UTF16,
'utf-16-le': codecs.BOM_UTF16_LE,
'utf-16-be': codecs.BOM_UTF16_BE,
'utf-32': codecs.BOM_UTF16,
'utf-32-le': codecs.BOM_UTF32_LE,
'utf-32-be': codecs.BOM_UTF32_BE,
}
def get_bom(codec):
"""Return the BOM of UTF-16/32 or empty str."""
if codec.name in CODECS_BOM:
return CODECS_BOM[codec.name]
else:
return b''
def _files_on_cwd():
"""Return all ASS/SSA file on current working directory. """
files = []
for file in os.listdir(os.getcwd()):
if file.startswith('.'):
continue
if file.endswith('.ass'):
files.append(file)
elif file.endswith('.ssa'):
files.append(file)
return files
def _combine_output_file_path(in_files, output_dir):
files = []
for file in in_files:
name = os.path.splitext(os.path.basename(file))[0] + '.srt'
path = os.path.join(output_dir, name)
files.append((file, path))
return files
def _convert_files(files, args):
if args.encoding:
in_codec = codecs.lookup(args.encoding)
else:
in_codec = None
if args.srt_encoding:
out_codec = codecs.lookup(args.srt_encoding)
else:
out_codec = in_codec
sum = len(files)
done = 0
fail = 0
ignore = 0
print("Found {} file(s), converting...".format(sum))
for in_path, out_path in _combine_output_file_path(files, args.output_dir):
print("\t({:02d}/{:02d}) is converting... " \
.format(done + fail + ignore + 1, sum), end='')
if not args.force and os.path.exists(out_path):
print('[ignore] (SRT exists)')
ignore += 1
continue
try:
with open(in_path, 'rb') as in_file:
if args.encoding is None: # Detect file charset.
in_codec = codecs.lookup(_detect_charset(in_file))
if args.srt_encoding is None:
out_codec = in_codec
out_str = asstosrt.convert(in_codec.streamreader(in_file),
args.translator, args.no_effact, args.only_first_line)
with open(out_path, 'wb') as out_file:
out_file.write(get_bom(out_codec))
out_file.write(out_codec.encode(out_str)[0])
done += 1
print('[done]')
except (UnicodeDecodeError, UnicodeEncodeError, LookupError) as e:
print('[fail] (codec error)')
print(e, file=sys.stderr)
fail += 1
except ValueError as e:
print('[fail] (irregular format)')
print(e, file=sys.stderr)
fail += 1
except IOError as e:
print('[fail] (IO error)')
print(e, file=sys.stderr)
fail += 1
print("All done:\n\t{} success, {} ignore, {} fail." \
.format(done, ignore, sum - done - ignore))
def main():
args = _get_args()
if args.encoding is None: # Enable auto detect
_check_chardet()
try:
if args.language is not None:
args.translator = translate.LangconvTranslator(args.language)
elif args.opencc_config is not None:
args.translator = translate.OpenCCTranslator(args.opencc_config)
else:
args.translator = None
except ImportError as e:
print("Error: {}\nPlease install it or disable "
"translation.".format(e.message))
sys.exit(1)
files = args.files
if not files:
files = _files_on_cwd()
if not files:
print('ASS/SSA file no found.\nTry --help for more information',
file=sys.stderr)
sys.exit(1)
_convert_files(files, args)
if __name__ == '__main__':
main() | en | 0.551129 | Import chardet or exit. Try detect the charset of file, return the name of charset or exit. Return the BOM of UTF-16/32 or empty str. Return all ASS/SSA file on current working directory. # Detect file charset. # Enable auto detect | 2.690824 | 3 |
rl_suite/algo/sac_rad.py | gauthamvasan/rl_suite | 1 | 6622332 | import torch
import copy
import time
import os
import threading
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp
from copy import deepcopy
from rl_suite.algo.cnn_policies import SACRADActor, SACRADCritic
from rl_suite.algo.replay_buffer import SACRADBuffer
class SAC_RAD:
""" SAC algorithm. """
def __init__(self, cfg, device=torch.device('cpu')):
self.cfg = cfg
self.device = device
self.gamma = cfg.gamma
self.critic_tau = cfg.critic_tau
self.encoder_tau = cfg.encoder_tau
self.actor_update_freq = cfg.actor_update_freq
self.critic_target_update_freq = cfg.critic_target_update_freq
self.rad_offset = cfg.rad_offset
self.actor_lr = cfg.actor_lr
self.critic_lr = cfg.critic_lr
self.alpha_lr = cfg.alpha_lr
self.action_dim = cfg.action_shape[0]
self.actor = SACRADActor(cfg.image_shape, cfg.proprioception_shape, cfg.action_shape[0], cfg.net_params,
cfg.rad_offset, cfg.freeze_cnn).to(device)
self.critic = SACRADCritic(cfg.image_shape, cfg.proprioception_shape, cfg.action_shape[0], cfg.net_params,
cfg.rad_offset, cfg.freeze_cnn).to(device)
self.critic_target = copy.deepcopy(self.critic) # also copies the encoder instance
if hasattr(self.actor.encoder, 'convs'):
self.actor.encoder.convs = self.critic.encoder.convs
self.log_alpha = torch.tensor(np.log(cfg.init_temperature)).to(device)
self.log_alpha.requires_grad = True
# set target entropy to -|A|
self.target_entropy = -np.prod(cfg.action_shape)
self.num_updates = 0
# optimizers
self.init_optimizers()
self.train()
self.critic_target.train()
def train(self, training=True):
self.training = training
self.actor.train(training)
self.critic.train(training)
def share_memory(self):
self.actor.share_memory()
self.critic.share_memory()
self.critic_target.share_memory()
self.log_alpha.share_memory_()
def init_optimizers(self):
self.actor_optimizer = torch.optim.Adam(
self.actor.parameters(), lr=self.actor_lr, betas=(0.9, 0.999)
)
self.critic_optimizer = torch.optim.Adam(
self.critic.parameters(), lr=self.critic_lr, betas=(0.9, 0.999)
)
self.log_alpha_optimizer = torch.optim.Adam(
[self.log_alpha], lr=self.alpha_lr, betas=(0.5, 0.999)
)
@property
def alpha(self):
return self.log_alpha.exp()
def sample_action(self, img, prop, deterministic=False):
with torch.no_grad():
if img is not None:
img = torch.FloatTensor(img).to(self.device)
img = img.unsqueeze(0)
if prop is not None:
prop = torch.FloatTensor(prop).to(self.device)
prop = prop.unsqueeze(0)
mu, action, _, _ = self.actor(img, prop)
if deterministic:
return mu.cpu().data.numpy().flatten()
else:
return action.cpu().data.numpy().flatten()
def update_critic(self, img, prop, action, reward, next_img, next_prop, not_done):
with torch.no_grad():
_, policy_action, log_p, _ = self.actor(next_img, next_prop)
target_Q1, target_Q2 = self.critic_target(next_img, next_prop, policy_action)
target_V = torch.min(target_Q1, target_Q2) - self.alpha.detach() * log_p
target_Q = reward + (not_done * self.gamma * target_V)
# get current Q estimates
current_Q1, current_Q2 = self.critic(img, prop, action, detach_encoder=False)
# Ignore terminal transitions to enable infinite bootstrap
critic_loss = torch.mean(
(current_Q1 - target_Q) ** 2 * not_done + (current_Q2 - target_Q) ** 2 * not_done
#(current_Q1 - target_Q) ** 2 + (current_Q2 - target_Q) ** 2
)
# Optimize the critic
self.critic_optimizer.zero_grad()
critic_loss.backward()
#torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 1)
self.critic_optimizer.step()
critic_stats = {
'train_critic/loss': critic_loss.item()
}
return critic_stats
def update_actor_and_alpha(self, img, prop):
# detach encoder, so we don't update it with the actor loss
_, action, log_p, log_std = self.actor(img, prop, detach_encoder=True)
actor_Q1, actor_Q2 = self.critic(img, prop, action, detach_encoder=True)
actor_Q = torch.min(actor_Q1, actor_Q2)
actor_loss = (self.alpha.detach() * log_p - actor_Q).mean()
entropy = 0.5 * log_std.shape[1] * (1.0 + np.log(2 * np.pi)) + log_std.sum(dim=-1)
# optimize the actor
self.actor_optimizer.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
self.log_alpha_optimizer.zero_grad()
alpha_loss = (self.alpha * (-log_p - self.target_entropy).detach()).mean()
alpha_loss.backward()
self.log_alpha_optimizer.step()
actor_stats = {
'train_actor/loss': actor_loss.item(),
'train_actor/target_entropy': self.target_entropy.item(),
'train_actor/entropy': entropy.mean().item(),
'train_alpha/loss': alpha_loss.item(),
'train_alpha/value': self.alpha.item(),
'train/entropy': entropy.mean().item(),
}
return actor_stats
def update(self, img, prop, action, reward, next_img, next_prop, not_done):
# Move tensors to device
img, prop, action, reward, next_img, next_prop, not_done = img.to(self.device), prop.to(self.device), \
action.to(self.device), reward.to(self.device), next_img.to(self.device), \
next_prop.to(self.device), not_done.to(self.device)
# regular update of SAC_RAD, sequentially augment data and train
stats = self.update_critic(img, prop, action, reward, next_img, next_prop, not_done)
if self.num_updates % self.actor_update_freq == 0:
actor_stats = self.update_actor_and_alpha(img, prop)
stats = {**stats, **actor_stats}
if self.num_updates % self.critic_target_update_freq == 0:
self.soft_update_target()
stats['train/batch_reward'] = reward.mean().item()
stats['train/num_updates'] = self.num_updates
self.num_updates += 1
return stats
@staticmethod
def soft_update_params(net, target_net, tau):
for param, target_param in zip(net.parameters(), target_net.parameters()):
target_param.data.copy_(
tau * param.data + (1 - tau) * target_param.data
)
def soft_update_target(self):
self.soft_update_params(
self.critic.Q1, self.critic_target.Q1, self.critic_tau
)
self.soft_update_params(
self.critic.Q2, self.critic_target.Q2, self.critic_tau
)
self.soft_update_params(
self.critic.encoder, self.critic_target.encoder,
self.encoder_tau
)
def save(self, model_dir, step):
torch.save(
self.actor.state_dict(), '%s/actor_%s.pt' % (model_dir, step)
)
torch.save(
self.critic.state_dict(), '%s/critic_%s.pt' % (model_dir, step)
)
def load(self, model_dir, step):
self.actor.load_state_dict(
torch.load('%s/actor_%s.pt' % (model_dir, step))
)
self.critic.load_state_dict(
torch.load('%s/critic_%s.pt' % (model_dir, step))
)
class SACRADAgent(SAC_RAD):
def __init__(self, cfg, buffer, device=torch.device('cpu')):
super().__init__(cfg, device)
self._replay_buffer = buffer
self.steps = 0
def push_and_update(self, image, propri, action, reward, done):
self._replay_buffer.add(image, propri, action, reward, done)
if self.steps > self.cfg.init_steps and (self.steps % self.cfg.update_every == 0):
for _ in range(self.cfg.update_epochs):
# tic = time.time()
stat = self.update(*self._replay_buffer.sample())
# print(time.time() - tic)
return stat
self.steps += 1
class AsyncSACAgent(SAC_RAD):
def __init__(self, cfg, device=torch.device('cpu')):
""" SAC agent with asynchronous updates using multiprocessing
N.B: Pytorch multiprocessing and replay buffers do not mingle well!
Buffer operations should be taken care of in the main training script
Args:
cfg:
actor_critic:
device:
"""
super(AsyncSACAgent, self).__init__(cfg=cfg, device=device)
self.cfg = cfg
# self.pi = deepcopy(self.actor)
# self.pi.to(device)
self.device = device
self.batch_size = cfg.batch_size
self.running = mp.Value('i', 1)
self.pause = mp.Value('i', 0)
self.steps = mp.Value('i', 0)
self.n_updates = mp.Value('i', 0)
self._nn_lock = mp.Lock()
self._state_dict = {
'actor': self.actor.state_dict(),
'critic': self.critic.state_dict(),
'actor_opt': self.actor_optimizer.state_dict(),
'critic_opt': self.critic_optimizer.state_dict(),
'log_alpha_opt': self.log_alpha_optimizer.state_dict(),
}
def async_recv_model(self, model_queue):
""" Update the performance element (i.e., sync with new model after gradient updates)
Args:
model_queue:
Returns:
"""
while True:
with self.running.get_lock():
if not self.running.value:
print("Exiting async_recv_model thread!")
return
self._state_dict = model_queue.get()
with self._nn_lock:
self.actor.load_state_dict(self._state_dict['actor'])
with self.n_updates.get_lock():
n_updates = self.n_updates.value
if n_updates % 20 == 0:
print("***** Performance element updated!, # learning updates: {} *****".format(n_updates))
def async_update(self, tensor_queue, model_queue):
""" Asynchronous process to update the actor_critic model.
Relies on one other threads spawned from the main process:
- async_recv_model
It also spawns it's own thread `async_recv_data` to receive state transitions from the main interaction process
Args:
tensor_queue: Multiprocessing queue to transfer RL interaction data
model_queue: Multiprocessing queue to send updated models back to main process
Returns:
"""
# TODO: Make buffer a configurable object
# N.B: DO NOT pass the buffer as an arg. Python pickling causes large delays and often crashes
buffer = SACRADBuffer(self.cfg.image_shape, self.cfg.proprioception_shape, self.cfg.action_shape,
self.cfg.replay_buffer_capacity, self.cfg.batch_size)
def async_recv_data():
# TODO: Exit mechanism for buffer
while True:
buffer.add(*tensor_queue.get())
with self.running.get_lock():
if not self.running.value:
break
print("Exiting buffer thread within the async update process")
buffer_t = threading.Thread(target=async_recv_data)
buffer_t.start()
while True:
with self.running.get_lock():
if not self.running.value:
print("Exiting async_update process!")
buffer_t.join()
return
# Warmup block
with self.steps.get_lock():
steps = self.steps.value
if steps < self.cfg.init_steps:
time.sleep(1)
print("Waiting to fill up the buffer before making any updates...")
continue
# Pause learning
with self.pause.get_lock():
pause = self.pause.value
if pause:
time.sleep(0.25)
continue
# Ask for data, make learning updates
tic = time.time()
for i in range(self.cfg.update_epochs):
images, propris, actions, rewards, next_images, next_propris, dones = buffer.sample()
self.update(images.clone(), propris.clone(), actions.clone(),
rewards.clone(), next_images.clone(), next_propris.clone(), dones.clone())
with self.n_updates.get_lock():
self.n_updates.value += 1
if self.n_updates.value % 100 == 0:
print("***** SAC learning update {} took {} *****".format(self.n_updates.value, time.time() - tic))
state_dict = {
'actor': self.actor.state_dict(),
'critic': self.critic.state_dict(),
'actor_opt': self.actor_optimizer.state_dict(),
'critic_opt': self.critic_optimizer.state_dict(),
'log_alpha_opt': self.log_alpha_optimizer.state_dict(),
}
# model_queue.put(state_dict)
def compute_action(self, obs, deterministic=False):
with torch.no_grad():
with self._nn_lock:
action, _ = self.pi(obs, with_lprob=False, det_rad=True)
return action.detach().cpu().numpy()
def state_dict(self):
return self._state_dict
def load_state_dict(self, model):
self.actor_critic.load_state_dict(model['actor_critic'])
self.pi_optimizer.load_state_dict(model['pi_opt'])
self.q_optimizer.load_state_dict(model['q_opt'])
self.pi = deepcopy(self.actor_critic.pi)
for p in self.pi.parameters():
p.requires_grad = False
def set_pause(self, val):
with self.pause.get_lock():
self.pause.value = val
print("Learning paused!" if val else "Resuming async learning ...")
| import torch
import copy
import time
import os
import threading
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp
from copy import deepcopy
from rl_suite.algo.cnn_policies import SACRADActor, SACRADCritic
from rl_suite.algo.replay_buffer import SACRADBuffer
class SAC_RAD:
""" SAC algorithm. """
def __init__(self, cfg, device=torch.device('cpu')):
self.cfg = cfg
self.device = device
self.gamma = cfg.gamma
self.critic_tau = cfg.critic_tau
self.encoder_tau = cfg.encoder_tau
self.actor_update_freq = cfg.actor_update_freq
self.critic_target_update_freq = cfg.critic_target_update_freq
self.rad_offset = cfg.rad_offset
self.actor_lr = cfg.actor_lr
self.critic_lr = cfg.critic_lr
self.alpha_lr = cfg.alpha_lr
self.action_dim = cfg.action_shape[0]
self.actor = SACRADActor(cfg.image_shape, cfg.proprioception_shape, cfg.action_shape[0], cfg.net_params,
cfg.rad_offset, cfg.freeze_cnn).to(device)
self.critic = SACRADCritic(cfg.image_shape, cfg.proprioception_shape, cfg.action_shape[0], cfg.net_params,
cfg.rad_offset, cfg.freeze_cnn).to(device)
self.critic_target = copy.deepcopy(self.critic) # also copies the encoder instance
if hasattr(self.actor.encoder, 'convs'):
self.actor.encoder.convs = self.critic.encoder.convs
self.log_alpha = torch.tensor(np.log(cfg.init_temperature)).to(device)
self.log_alpha.requires_grad = True
# set target entropy to -|A|
self.target_entropy = -np.prod(cfg.action_shape)
self.num_updates = 0
# optimizers
self.init_optimizers()
self.train()
self.critic_target.train()
def train(self, training=True):
self.training = training
self.actor.train(training)
self.critic.train(training)
def share_memory(self):
self.actor.share_memory()
self.critic.share_memory()
self.critic_target.share_memory()
self.log_alpha.share_memory_()
def init_optimizers(self):
self.actor_optimizer = torch.optim.Adam(
self.actor.parameters(), lr=self.actor_lr, betas=(0.9, 0.999)
)
self.critic_optimizer = torch.optim.Adam(
self.critic.parameters(), lr=self.critic_lr, betas=(0.9, 0.999)
)
self.log_alpha_optimizer = torch.optim.Adam(
[self.log_alpha], lr=self.alpha_lr, betas=(0.5, 0.999)
)
@property
def alpha(self):
return self.log_alpha.exp()
def sample_action(self, img, prop, deterministic=False):
with torch.no_grad():
if img is not None:
img = torch.FloatTensor(img).to(self.device)
img = img.unsqueeze(0)
if prop is not None:
prop = torch.FloatTensor(prop).to(self.device)
prop = prop.unsqueeze(0)
mu, action, _, _ = self.actor(img, prop)
if deterministic:
return mu.cpu().data.numpy().flatten()
else:
return action.cpu().data.numpy().flatten()
def update_critic(self, img, prop, action, reward, next_img, next_prop, not_done):
with torch.no_grad():
_, policy_action, log_p, _ = self.actor(next_img, next_prop)
target_Q1, target_Q2 = self.critic_target(next_img, next_prop, policy_action)
target_V = torch.min(target_Q1, target_Q2) - self.alpha.detach() * log_p
target_Q = reward + (not_done * self.gamma * target_V)
# get current Q estimates
current_Q1, current_Q2 = self.critic(img, prop, action, detach_encoder=False)
# Ignore terminal transitions to enable infinite bootstrap
critic_loss = torch.mean(
(current_Q1 - target_Q) ** 2 * not_done + (current_Q2 - target_Q) ** 2 * not_done
#(current_Q1 - target_Q) ** 2 + (current_Q2 - target_Q) ** 2
)
# Optimize the critic
self.critic_optimizer.zero_grad()
critic_loss.backward()
#torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 1)
self.critic_optimizer.step()
critic_stats = {
'train_critic/loss': critic_loss.item()
}
return critic_stats
def update_actor_and_alpha(self, img, prop):
# detach encoder, so we don't update it with the actor loss
_, action, log_p, log_std = self.actor(img, prop, detach_encoder=True)
actor_Q1, actor_Q2 = self.critic(img, prop, action, detach_encoder=True)
actor_Q = torch.min(actor_Q1, actor_Q2)
actor_loss = (self.alpha.detach() * log_p - actor_Q).mean()
entropy = 0.5 * log_std.shape[1] * (1.0 + np.log(2 * np.pi)) + log_std.sum(dim=-1)
# optimize the actor
self.actor_optimizer.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
self.log_alpha_optimizer.zero_grad()
alpha_loss = (self.alpha * (-log_p - self.target_entropy).detach()).mean()
alpha_loss.backward()
self.log_alpha_optimizer.step()
actor_stats = {
'train_actor/loss': actor_loss.item(),
'train_actor/target_entropy': self.target_entropy.item(),
'train_actor/entropy': entropy.mean().item(),
'train_alpha/loss': alpha_loss.item(),
'train_alpha/value': self.alpha.item(),
'train/entropy': entropy.mean().item(),
}
return actor_stats
def update(self, img, prop, action, reward, next_img, next_prop, not_done):
# Move tensors to device
img, prop, action, reward, next_img, next_prop, not_done = img.to(self.device), prop.to(self.device), \
action.to(self.device), reward.to(self.device), next_img.to(self.device), \
next_prop.to(self.device), not_done.to(self.device)
# regular update of SAC_RAD, sequentially augment data and train
stats = self.update_critic(img, prop, action, reward, next_img, next_prop, not_done)
if self.num_updates % self.actor_update_freq == 0:
actor_stats = self.update_actor_and_alpha(img, prop)
stats = {**stats, **actor_stats}
if self.num_updates % self.critic_target_update_freq == 0:
self.soft_update_target()
stats['train/batch_reward'] = reward.mean().item()
stats['train/num_updates'] = self.num_updates
self.num_updates += 1
return stats
@staticmethod
def soft_update_params(net, target_net, tau):
for param, target_param in zip(net.parameters(), target_net.parameters()):
target_param.data.copy_(
tau * param.data + (1 - tau) * target_param.data
)
def soft_update_target(self):
self.soft_update_params(
self.critic.Q1, self.critic_target.Q1, self.critic_tau
)
self.soft_update_params(
self.critic.Q2, self.critic_target.Q2, self.critic_tau
)
self.soft_update_params(
self.critic.encoder, self.critic_target.encoder,
self.encoder_tau
)
def save(self, model_dir, step):
torch.save(
self.actor.state_dict(), '%s/actor_%s.pt' % (model_dir, step)
)
torch.save(
self.critic.state_dict(), '%s/critic_%s.pt' % (model_dir, step)
)
def load(self, model_dir, step):
self.actor.load_state_dict(
torch.load('%s/actor_%s.pt' % (model_dir, step))
)
self.critic.load_state_dict(
torch.load('%s/critic_%s.pt' % (model_dir, step))
)
class SACRADAgent(SAC_RAD):
def __init__(self, cfg, buffer, device=torch.device('cpu')):
super().__init__(cfg, device)
self._replay_buffer = buffer
self.steps = 0
def push_and_update(self, image, propri, action, reward, done):
self._replay_buffer.add(image, propri, action, reward, done)
if self.steps > self.cfg.init_steps and (self.steps % self.cfg.update_every == 0):
for _ in range(self.cfg.update_epochs):
# tic = time.time()
stat = self.update(*self._replay_buffer.sample())
# print(time.time() - tic)
return stat
self.steps += 1
class AsyncSACAgent(SAC_RAD):
def __init__(self, cfg, device=torch.device('cpu')):
""" SAC agent with asynchronous updates using multiprocessing
N.B: Pytorch multiprocessing and replay buffers do not mingle well!
Buffer operations should be taken care of in the main training script
Args:
cfg:
actor_critic:
device:
"""
super(AsyncSACAgent, self).__init__(cfg=cfg, device=device)
self.cfg = cfg
# self.pi = deepcopy(self.actor)
# self.pi.to(device)
self.device = device
self.batch_size = cfg.batch_size
self.running = mp.Value('i', 1)
self.pause = mp.Value('i', 0)
self.steps = mp.Value('i', 0)
self.n_updates = mp.Value('i', 0)
self._nn_lock = mp.Lock()
self._state_dict = {
'actor': self.actor.state_dict(),
'critic': self.critic.state_dict(),
'actor_opt': self.actor_optimizer.state_dict(),
'critic_opt': self.critic_optimizer.state_dict(),
'log_alpha_opt': self.log_alpha_optimizer.state_dict(),
}
def async_recv_model(self, model_queue):
""" Update the performance element (i.e., sync with new model after gradient updates)
Args:
model_queue:
Returns:
"""
while True:
with self.running.get_lock():
if not self.running.value:
print("Exiting async_recv_model thread!")
return
self._state_dict = model_queue.get()
with self._nn_lock:
self.actor.load_state_dict(self._state_dict['actor'])
with self.n_updates.get_lock():
n_updates = self.n_updates.value
if n_updates % 20 == 0:
print("***** Performance element updated!, # learning updates: {} *****".format(n_updates))
def async_update(self, tensor_queue, model_queue):
""" Asynchronous process to update the actor_critic model.
Relies on one other threads spawned from the main process:
- async_recv_model
It also spawns it's own thread `async_recv_data` to receive state transitions from the main interaction process
Args:
tensor_queue: Multiprocessing queue to transfer RL interaction data
model_queue: Multiprocessing queue to send updated models back to main process
Returns:
"""
# TODO: Make buffer a configurable object
# N.B: DO NOT pass the buffer as an arg. Python pickling causes large delays and often crashes
buffer = SACRADBuffer(self.cfg.image_shape, self.cfg.proprioception_shape, self.cfg.action_shape,
self.cfg.replay_buffer_capacity, self.cfg.batch_size)
def async_recv_data():
# TODO: Exit mechanism for buffer
while True:
buffer.add(*tensor_queue.get())
with self.running.get_lock():
if not self.running.value:
break
print("Exiting buffer thread within the async update process")
buffer_t = threading.Thread(target=async_recv_data)
buffer_t.start()
while True:
with self.running.get_lock():
if not self.running.value:
print("Exiting async_update process!")
buffer_t.join()
return
# Warmup block
with self.steps.get_lock():
steps = self.steps.value
if steps < self.cfg.init_steps:
time.sleep(1)
print("Waiting to fill up the buffer before making any updates...")
continue
# Pause learning
with self.pause.get_lock():
pause = self.pause.value
if pause:
time.sleep(0.25)
continue
# Ask for data, make learning updates
tic = time.time()
for i in range(self.cfg.update_epochs):
images, propris, actions, rewards, next_images, next_propris, dones = buffer.sample()
self.update(images.clone(), propris.clone(), actions.clone(),
rewards.clone(), next_images.clone(), next_propris.clone(), dones.clone())
with self.n_updates.get_lock():
self.n_updates.value += 1
if self.n_updates.value % 100 == 0:
print("***** SAC learning update {} took {} *****".format(self.n_updates.value, time.time() - tic))
state_dict = {
'actor': self.actor.state_dict(),
'critic': self.critic.state_dict(),
'actor_opt': self.actor_optimizer.state_dict(),
'critic_opt': self.critic_optimizer.state_dict(),
'log_alpha_opt': self.log_alpha_optimizer.state_dict(),
}
# model_queue.put(state_dict)
def compute_action(self, obs, deterministic=False):
with torch.no_grad():
with self._nn_lock:
action, _ = self.pi(obs, with_lprob=False, det_rad=True)
return action.detach().cpu().numpy()
def state_dict(self):
return self._state_dict
def load_state_dict(self, model):
self.actor_critic.load_state_dict(model['actor_critic'])
self.pi_optimizer.load_state_dict(model['pi_opt'])
self.q_optimizer.load_state_dict(model['q_opt'])
self.pi = deepcopy(self.actor_critic.pi)
for p in self.pi.parameters():
p.requires_grad = False
def set_pause(self, val):
with self.pause.get_lock():
self.pause.value = val
print("Learning paused!" if val else "Resuming async learning ...")
| en | 0.729192 | SAC algorithm. # also copies the encoder instance # set target entropy to -|A| # optimizers # get current Q estimates # Ignore terminal transitions to enable infinite bootstrap #(current_Q1 - target_Q) ** 2 + (current_Q2 - target_Q) ** 2 # Optimize the critic #torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 1) # detach encoder, so we don't update it with the actor loss # optimize the actor # Move tensors to device # regular update of SAC_RAD, sequentially augment data and train # tic = time.time() # print(time.time() - tic) SAC agent with asynchronous updates using multiprocessing N.B: Pytorch multiprocessing and replay buffers do not mingle well! Buffer operations should be taken care of in the main training script Args: cfg: actor_critic: device: # self.pi = deepcopy(self.actor) # self.pi.to(device) Update the performance element (i.e., sync with new model after gradient updates) Args: model_queue: Returns: # learning updates: {} *****".format(n_updates)) Asynchronous process to update the actor_critic model. Relies on one other threads spawned from the main process: - async_recv_model It also spawns it's own thread `async_recv_data` to receive state transitions from the main interaction process Args: tensor_queue: Multiprocessing queue to transfer RL interaction data model_queue: Multiprocessing queue to send updated models back to main process Returns: # TODO: Make buffer a configurable object # N.B: DO NOT pass the buffer as an arg. Python pickling causes large delays and often crashes # TODO: Exit mechanism for buffer # Warmup block # Pause learning # Ask for data, make learning updates # model_queue.put(state_dict) | 2.096735 | 2 |
zonys/core/freebsd/mount/nullfs.py | zonys/zonys | 1 | 6622333 | import pathlib
import subprocess
import zonys
import zonys.core
import zonys.core.freebsd
import zonys.core.freebsd.mount
class Mountpoint(zonys.core.freebsd.mount.Mountpoint):
def __init__(self, source, destination, read_only=True):
super().__init__(destination)
if isinstance(source, str):
source = pathlib.Path(source)
elif not isinstance(source, pathlib.Path):
raise ValueError("source must be instance of type string or Path")
if not isinstance(read_only, bool):
raise ValueError("read_only must be instance of bool")
self.__source = source
self.__read_only = read_only
@property
def source(self):
return self.__source
@property
def read_only(self):
return self.__read_only
def mount(self):
if self.exists():
raise zonys.core.freebsd.mount.AlreadyExistsError(self)
command = ["mount", "-t", "nullfs"]
if self.read_only:
command.append("-r")
else:
command.append("-w")
command.extend([str(self.source), str(self.destination)])
subprocess.run(
command,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return Handle(
self.source,
self.destination,
)
def open(self):
for entry in self._list():
if entry[1] == str(self.destination) and "nullfs" in entry[2]:
return Handle(entry[0], entry[1])
raise zonys.core.freebsd.mount.NotExistsError(self)
class Handle(zonys.core.freebsd.mount.Handle):
def __init__(self, source, *args, **kwargs):
super().__init__(*args, **kwargs)
if isinstance(source, str):
destination = pathlib.Path(source)
elif not isinstance(source, pathlib.Path):
raise ValueError("source must be an instance of type string or Path")
self.__source = source
@property
def source(self):
return self.__source
| import pathlib
import subprocess
import zonys
import zonys.core
import zonys.core.freebsd
import zonys.core.freebsd.mount
class Mountpoint(zonys.core.freebsd.mount.Mountpoint):
def __init__(self, source, destination, read_only=True):
super().__init__(destination)
if isinstance(source, str):
source = pathlib.Path(source)
elif not isinstance(source, pathlib.Path):
raise ValueError("source must be instance of type string or Path")
if not isinstance(read_only, bool):
raise ValueError("read_only must be instance of bool")
self.__source = source
self.__read_only = read_only
@property
def source(self):
return self.__source
@property
def read_only(self):
return self.__read_only
def mount(self):
if self.exists():
raise zonys.core.freebsd.mount.AlreadyExistsError(self)
command = ["mount", "-t", "nullfs"]
if self.read_only:
command.append("-r")
else:
command.append("-w")
command.extend([str(self.source), str(self.destination)])
subprocess.run(
command,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return Handle(
self.source,
self.destination,
)
def open(self):
for entry in self._list():
if entry[1] == str(self.destination) and "nullfs" in entry[2]:
return Handle(entry[0], entry[1])
raise zonys.core.freebsd.mount.NotExistsError(self)
class Handle(zonys.core.freebsd.mount.Handle):
def __init__(self, source, *args, **kwargs):
super().__init__(*args, **kwargs)
if isinstance(source, str):
destination = pathlib.Path(source)
elif not isinstance(source, pathlib.Path):
raise ValueError("source must be an instance of type string or Path")
self.__source = source
@property
def source(self):
return self.__source
| none | 1 | 2.102353 | 2 | |
goalgetter/blueprints/goals/views.py | shingtzewoo/goalgetter | 0 | 6622334 | from flask import Blueprint, render_template, url_for, flash, request, redirect
from flask_login import login_required, current_user
from goalgetter.blueprints.goals.models.values import Value
from goalgetter.blueprints.goals.models.goals import Goal
from goalgetter.blueprints.goals.models.milestones import Milestone
from goalgetter.blueprints.goals.models.tasks import Task
from datetime import *
from dateutil.relativedelta import *
from lib.route_logic import questionnaire_reroute
goals = Blueprint('goals', __name__, template_folder='templates')
@goals.route('/questions/values', methods=['GET', 'POST'])
@questionnaire_reroute
@login_required
def values():
if request.method == "POST":
# https://stackoverflow.com/questions/59656684/how-do-i-store-multiple-checkbox-data-in-a-list-of-array
values = request.form.getlist('value')
if len(values) > 3 or len(values) < 0 or (len(values) < 3 and len(values) >= 0):
flash("Number of values chosen have to be 3", "danger")
return redirect(url_for("goals.values"))
value1, value2, value3 = Value(value=values[0]), Value(value=values[1]), Value(value=values[2])
connected1, connected2, connected3 = value1.connect(current_user.id), value2.connect(current_user.id), value3.connect(current_user.id)
if connected1 and connected2 and connected3:
current_user.questionnaire+=1
current_user.save()
return redirect(url_for("goals.goal"))
else:
if current_user.is_complete() == 0:
return render_template("values.html")
@goals.route('/questions/goals', methods=['GET','POST'])
@questionnaire_reroute
@login_required
def goal():
if request.method == "POST":
goal1, goal2, goal3 = Goal(name=request.form.get(current_user.values[0].value)), Goal(name=request.form.get(current_user.values[1].value)), Goal(name=request.form.get(current_user.values[2].value))
# Connecting the goals to the correct values
connected1, connected2, connected3 = goal1.connect(current_user.values[0].id) , goal2.connect(current_user.values[1].id), goal3.connect(current_user.values[2].id)
if connected1 and connected2 and connected3:
# Updating user's completion stage to 2 for the questionnaire, there are 3 stages in total
current_user.questionnaire+=1
current_user.save()
return redirect(url_for("goals.milestones"))
else:
if current_user.is_complete() == 1:
return render_template("develop_goals.html", value1=current_user.values[0].value, value2=current_user.values[1].value, value3=current_user.values[2].value)
@goals.route('/questions/milestones', methods=['GET','POST'])
@questionnaire_reroute
@login_required
def milestones():
goal1, goal2, goal3 = Goal.query_by_foreignid(current_user.values[0].id).first(), Goal.query_by_foreignid(current_user.values[1].id).first(), Goal.query_by_foreignid(current_user.values[2].id).first()
if request.method == "POST":
goal1_milestones, goal2_milestones, goal3_milestones = request.form.getlist(str(goal1.id)), request.form.getlist(str(goal2.id)), request.form.getlist(str(goal3.id))
# Connecting each milestone to a goal and setting the start and end date for each. Each goal has 3 milestones
Milestone.info_setter(goal1_milestones, goal1)
Milestone.info_setter(goal2_milestones, goal2)
Milestone.info_setter(goal3_milestones, goal3)
# Updating user's completion stage to 3 for the questionnaire, there are 3 stages in total
current_user.questionnaire+=1
current_user.save()
return redirect(url_for("goals.tasks"))
else:
if current_user.is_complete() == 2:
return render_template("milestones.html", goal1=goal1, goal2=goal2, goal3=goal3)
@goals.route('/questions/tasks', methods=['GET','POST'])
@questionnaire_reroute
@login_required
def tasks():
value1, value2, value3 = current_user.values[0], current_user.values[1], current_user.values[2]
if request.method == "POST":
# Below we set the task for each milestone. A loop that cycles 3 times is used because each value has 3 milestones.
for i in range(0, 3):
task_info = request.form.getlist(str(value1.goal.milestone[i].id))
Task.info_setter(value1.goal.milestone[i].id, task_info)
for i in range(0, 3):
task_info = request.form.getlist(str(value2.goal.milestone[i].id))
Task.info_setter(value2.goal.milestone[i].id, task_info)
for i in range(0, 3):
task_info = request.form.getlist(str(value3.goal.milestone[i].id))
Task.info_setter(value3.goal.milestone[i].id, task_info)
# updating user's completion stage to 4 for the questionnaire, user is finished with questionnaire
current_user.questionnaire+=1
current_user.save()
return redirect(url_for("page.home"))
else:
if current_user.is_complete() == 3:
return render_template("tasks.html", value1=value1, value2=value2, value3=value3) | from flask import Blueprint, render_template, url_for, flash, request, redirect
from flask_login import login_required, current_user
from goalgetter.blueprints.goals.models.values import Value
from goalgetter.blueprints.goals.models.goals import Goal
from goalgetter.blueprints.goals.models.milestones import Milestone
from goalgetter.blueprints.goals.models.tasks import Task
from datetime import *
from dateutil.relativedelta import *
from lib.route_logic import questionnaire_reroute
goals = Blueprint('goals', __name__, template_folder='templates')
@goals.route('/questions/values', methods=['GET', 'POST'])
@questionnaire_reroute
@login_required
def values():
if request.method == "POST":
# https://stackoverflow.com/questions/59656684/how-do-i-store-multiple-checkbox-data-in-a-list-of-array
values = request.form.getlist('value')
if len(values) > 3 or len(values) < 0 or (len(values) < 3 and len(values) >= 0):
flash("Number of values chosen have to be 3", "danger")
return redirect(url_for("goals.values"))
value1, value2, value3 = Value(value=values[0]), Value(value=values[1]), Value(value=values[2])
connected1, connected2, connected3 = value1.connect(current_user.id), value2.connect(current_user.id), value3.connect(current_user.id)
if connected1 and connected2 and connected3:
current_user.questionnaire+=1
current_user.save()
return redirect(url_for("goals.goal"))
else:
if current_user.is_complete() == 0:
return render_template("values.html")
@goals.route('/questions/goals', methods=['GET','POST'])
@questionnaire_reroute
@login_required
def goal():
if request.method == "POST":
goal1, goal2, goal3 = Goal(name=request.form.get(current_user.values[0].value)), Goal(name=request.form.get(current_user.values[1].value)), Goal(name=request.form.get(current_user.values[2].value))
# Connecting the goals to the correct values
connected1, connected2, connected3 = goal1.connect(current_user.values[0].id) , goal2.connect(current_user.values[1].id), goal3.connect(current_user.values[2].id)
if connected1 and connected2 and connected3:
# Updating user's completion stage to 2 for the questionnaire, there are 3 stages in total
current_user.questionnaire+=1
current_user.save()
return redirect(url_for("goals.milestones"))
else:
if current_user.is_complete() == 1:
return render_template("develop_goals.html", value1=current_user.values[0].value, value2=current_user.values[1].value, value3=current_user.values[2].value)
@goals.route('/questions/milestones', methods=['GET','POST'])
@questionnaire_reroute
@login_required
def milestones():
goal1, goal2, goal3 = Goal.query_by_foreignid(current_user.values[0].id).first(), Goal.query_by_foreignid(current_user.values[1].id).first(), Goal.query_by_foreignid(current_user.values[2].id).first()
if request.method == "POST":
goal1_milestones, goal2_milestones, goal3_milestones = request.form.getlist(str(goal1.id)), request.form.getlist(str(goal2.id)), request.form.getlist(str(goal3.id))
# Connecting each milestone to a goal and setting the start and end date for each. Each goal has 3 milestones
Milestone.info_setter(goal1_milestones, goal1)
Milestone.info_setter(goal2_milestones, goal2)
Milestone.info_setter(goal3_milestones, goal3)
# Updating user's completion stage to 3 for the questionnaire, there are 3 stages in total
current_user.questionnaire+=1
current_user.save()
return redirect(url_for("goals.tasks"))
else:
if current_user.is_complete() == 2:
return render_template("milestones.html", goal1=goal1, goal2=goal2, goal3=goal3)
@goals.route('/questions/tasks', methods=['GET','POST'])
@questionnaire_reroute
@login_required
def tasks():
value1, value2, value3 = current_user.values[0], current_user.values[1], current_user.values[2]
if request.method == "POST":
# Below we set the task for each milestone. A loop that cycles 3 times is used because each value has 3 milestones.
for i in range(0, 3):
task_info = request.form.getlist(str(value1.goal.milestone[i].id))
Task.info_setter(value1.goal.milestone[i].id, task_info)
for i in range(0, 3):
task_info = request.form.getlist(str(value2.goal.milestone[i].id))
Task.info_setter(value2.goal.milestone[i].id, task_info)
for i in range(0, 3):
task_info = request.form.getlist(str(value3.goal.milestone[i].id))
Task.info_setter(value3.goal.milestone[i].id, task_info)
# updating user's completion stage to 4 for the questionnaire, user is finished with questionnaire
current_user.questionnaire+=1
current_user.save()
return redirect(url_for("page.home"))
else:
if current_user.is_complete() == 3:
return render_template("tasks.html", value1=value1, value2=value2, value3=value3) | en | 0.886349 | # https://stackoverflow.com/questions/59656684/how-do-i-store-multiple-checkbox-data-in-a-list-of-array # Connecting the goals to the correct values # Updating user's completion stage to 2 for the questionnaire, there are 3 stages in total # Connecting each milestone to a goal and setting the start and end date for each. Each goal has 3 milestones # Updating user's completion stage to 3 for the questionnaire, there are 3 stages in total # Below we set the task for each milestone. A loop that cycles 3 times is used because each value has 3 milestones. # updating user's completion stage to 4 for the questionnaire, user is finished with questionnaire | 2.484472 | 2 |
webserver/app/auth.py | lrazovic/advanced_programming | 1 | 6622335 | <reponame>lrazovic/advanced_programming<gh_stars>1-10
from fastapi import FastAPI
from authlib.integrations.starlette_client import OAuthError
from starlette.requests import Request
from starlette.responses import JSONResponse, RedirectResponse, HTMLResponse
from starlette.middleware.sessions import SessionMiddleware
from datetime import datetime
from models import User, Login_form, Pass_change_form
from jwtoken import (
create_token,
valid_email_from_db,
create_refresh_token,
decode_token,
add_user_to_db,
check_user_db,
get_user_data,
change_password,
CREDENTIALS_EXCEPTION,
)
from oauth import oauth
from utils import redirect_uri
auth_app = FastAPI()
auth_app.add_middleware(SessionMiddleware, secret_key="!secret")
@auth_app.route("/login")
async def login(request: Request):
return await oauth.google.authorize_redirect(request, redirect_uri)
@auth_app.route("/token")
async def token(request: Request):
try:
access_token = await oauth.google.authorize_access_token(request)
except OAuthError:
raise CREDENTIALS_EXCEPTION
user_data = await oauth.google.parse_id_token(request, access_token)
access_token = create_token(user_data["email"])
refresh_token = create_refresh_token(user_data["email"])
user_data["access_token"] = access_token
user_data["refresh_token"] = refresh_token
response = await add_user_to_db(user_data)
return JSONResponse(
{
"result": True,
"user_id": response["result"],
"access_token": access_token,
"refresh_token": refresh_token,
}
)
@auth_app.get("/logout", summary="Pop the user session")
async def logout(request: Request):
# request.session.pop("user", None)
return RedirectResponse(url="/")
@auth_app.post("/refresh", summary="Use the refresh token to create a new access token")
async def refresh(request: Request):
try:
form = await request.json()
if form.get("grant_type") == "refresh_token":
token = form.get("refresh_token")
payload = decode_token(token)
# Check if token is not expired
if datetime.utcfromtimestamp(payload.get("exp")) > datetime.utcnow():
email = payload.get("sub")
# Validate email
if valid_email_from_db(email):
# Create and return token
return JSONResponse(
{"result": True, "access_token": create_token(email)}
)
except Exception:
raise CREDENTIALS_EXCEPTION
raise CREDENTIALS_EXCEPTION
##############################################################
@auth_app.post(
"/register",
summary="Add to the db a new user registered with traditional credentials",
)
async def register(user: User):
# Pydantic model to dictionary explicit conversion
user_data = {}
user_data["name"] = user.name
user_data["email"] = user.email
# TODO: Use BCrypt instead of SHA256
# Reference: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html
user_data["password"] = <PASSWORD>
response = await add_user_to_db(user_data)
return JSONResponse(
{
"result": True,
"user_id": response["result"],
"email": user_data["email"],
}
)
@auth_app.post(
"/loginlocal",
summary="Manage the authentication process with the traditional credentials",
)
async def loginlocal(form: Login_form):
response_json = await check_user_db(form.email, form.password)
if "error" in response_json:
return JSONResponse({"authenticationSuccess?": False})
else:
user_id = response_json["result"]["id"]
access_token = create_token(form.email)
refresh_token = create_refresh_token(form.email)
return JSONResponse(
{
"user_id": user_id,
"jwt": access_token,
"refresh": refresh_token,
}
)
@auth_app.post(
"/changepassword",
summary="Change the currently authenticthed user's password in the db",
)
async def changepassword(form: Pass_change_form):
response = await change_password(
form.email,
form.old_password,
form.new_password,
)
# Returns `true` if change success, `Error` if `old_password` didn't match
return JSONResponse({"result": response["result"]})
| from fastapi import FastAPI
from authlib.integrations.starlette_client import OAuthError
from starlette.requests import Request
from starlette.responses import JSONResponse, RedirectResponse, HTMLResponse
from starlette.middleware.sessions import SessionMiddleware
from datetime import datetime
from models import User, Login_form, Pass_change_form
from jwtoken import (
create_token,
valid_email_from_db,
create_refresh_token,
decode_token,
add_user_to_db,
check_user_db,
get_user_data,
change_password,
CREDENTIALS_EXCEPTION,
)
from oauth import oauth
from utils import redirect_uri
auth_app = FastAPI()
auth_app.add_middleware(SessionMiddleware, secret_key="!secret")
@auth_app.route("/login")
async def login(request: Request):
return await oauth.google.authorize_redirect(request, redirect_uri)
@auth_app.route("/token")
async def token(request: Request):
try:
access_token = await oauth.google.authorize_access_token(request)
except OAuthError:
raise CREDENTIALS_EXCEPTION
user_data = await oauth.google.parse_id_token(request, access_token)
access_token = create_token(user_data["email"])
refresh_token = create_refresh_token(user_data["email"])
user_data["access_token"] = access_token
user_data["refresh_token"] = refresh_token
response = await add_user_to_db(user_data)
return JSONResponse(
{
"result": True,
"user_id": response["result"],
"access_token": access_token,
"refresh_token": refresh_token,
}
)
@auth_app.get("/logout", summary="Pop the user session")
async def logout(request: Request):
# request.session.pop("user", None)
return RedirectResponse(url="/")
@auth_app.post("/refresh", summary="Use the refresh token to create a new access token")
async def refresh(request: Request):
try:
form = await request.json()
if form.get("grant_type") == "refresh_token":
token = form.get("refresh_token")
payload = decode_token(token)
# Check if token is not expired
if datetime.utcfromtimestamp(payload.get("exp")) > datetime.utcnow():
email = payload.get("sub")
# Validate email
if valid_email_from_db(email):
# Create and return token
return JSONResponse(
{"result": True, "access_token": create_token(email)}
)
except Exception:
raise CREDENTIALS_EXCEPTION
raise CREDENTIALS_EXCEPTION
##############################################################
@auth_app.post(
"/register",
summary="Add to the db a new user registered with traditional credentials",
)
async def register(user: User):
# Pydantic model to dictionary explicit conversion
user_data = {}
user_data["name"] = user.name
user_data["email"] = user.email
# TODO: Use BCrypt instead of SHA256
# Reference: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html
user_data["password"] = <PASSWORD>
response = await add_user_to_db(user_data)
return JSONResponse(
{
"result": True,
"user_id": response["result"],
"email": user_data["email"],
}
)
@auth_app.post(
"/loginlocal",
summary="Manage the authentication process with the traditional credentials",
)
async def loginlocal(form: Login_form):
response_json = await check_user_db(form.email, form.password)
if "error" in response_json:
return JSONResponse({"authenticationSuccess?": False})
else:
user_id = response_json["result"]["id"]
access_token = create_token(form.email)
refresh_token = create_refresh_token(form.email)
return JSONResponse(
{
"user_id": user_id,
"jwt": access_token,
"refresh": refresh_token,
}
)
@auth_app.post(
"/changepassword",
summary="Change the currently authenticthed user's password in the db",
)
async def changepassword(form: Pass_change_form):
response = await change_password(
form.email,
form.old_password,
form.new_password,
)
# Returns `true` if change success, `Error` if `old_password` didn't match
return JSONResponse({"result": response["result"]}) | en | 0.401603 | # request.session.pop("user", None) # Check if token is not expired # Validate email # Create and return token ############################################################## # Pydantic model to dictionary explicit conversion # TODO: Use BCrypt instead of SHA256 # Reference: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html # Returns `true` if change success, `Error` if `old_password` didn't match | 2.391857 | 2 |
gallery/urls.py | KimLHill/MSP4 | 0 | 6622336 | from django.urls import path
from . import views
# Gallery URLs
urlpatterns = [
path('', views.gallery, name='gallery'),
path('<int:gallery_id>/', views.gallery_detail, name='gallery_detail'),
path('add/', views.add_gallery, name='add_gallery'),
path('edit/<int:gallery_id>/', views.edit_gallery, name='edit_gallery'),
path('delete/<int:gallery_id>/', views.delete_gallery,
name='delete_gallery'),
]
| from django.urls import path
from . import views
# Gallery URLs
urlpatterns = [
path('', views.gallery, name='gallery'),
path('<int:gallery_id>/', views.gallery_detail, name='gallery_detail'),
path('add/', views.add_gallery, name='add_gallery'),
path('edit/<int:gallery_id>/', views.edit_gallery, name='edit_gallery'),
path('delete/<int:gallery_id>/', views.delete_gallery,
name='delete_gallery'),
]
| en | 0.265502 | # Gallery URLs | 1.730906 | 2 |
tool/admin/app/batserver/batbuild.py | mever/qooxdoo | 1 | 6622337 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2007-2009 1&1 Internet AG, Germany, http://www.1und1.de
#
# License:
# MIT: https://opensource.org/licenses/MIT
# See the LICENSE file in the project's top-level directory for details.
#
# Authors:
# * <NAME> (thron7)
# * <NAME> (d_wagner)
#
################################################################################
# NAME
# BAT Build - creating local qooxdoo builds
#
# DESCRIPTION
# This is the "Build" part of qooxdoo's "Build-And-Test" environment.
# It is a small, stand-alone continuous integration server for qooxdoo. It
# monitors changes in an SVN repository, maintains a current local checkout,
# and with every update runs some build targets on it. Messages are written to
# a log file.
import os, sys, platform
import optparse, time, re
# some defaults
buildconf = {
'svn_base_url' : 'https://qooxdoo.svn.sourceforge.net/svnroot/qooxdoo',
'stage_dir' : '/var/www/qx',
'logfile' : 'bat_build.log',
# change the next entry, to e.g. include a release candidate 'tags/release_0_8'
'targets' : ['trunk'],
'download_dir' : '/var/www/downloads',
'doCleanup' : False,
'checkInterval': 10, # 10min - beware of time it takes for a build before re-check
'generate' : False,
'path' : 'application/demobrowser',
'pycmd' : './'
#'disk_space' : '2G',
#'cpu_consume' : '20%',
#'time_limit' : '30m',
}
def get_computed_conf():
parser = optparse.OptionParser()
parser.add_option(
"-w", "--work-dir", dest="stagedir", default=buildconf['stage_dir'], type="string",
help="Directory for checking out and making the target"
)
parser.add_option(
"-t", "--build-target", dest="target", default=buildconf['targets'][0], type="string",
help="Target to build (e.g. \"trunk\")"
)
parser.add_option(
"-r", "--build-release", dest="release", default=None, type="string",
help="Release version (SVN) of target to build (e.g. \"9077\")"
)
parser.add_option(
"-g", "--generate-job", dest="generate", default=buildconf['generate'], type="string",
help="Which generator job to run, e.g. \"release\", \"source\", \"build\""
)
parser.add_option(
"-p", "--generate-path", dest="path", default=buildconf['path'], type="string",
help="Path to run generate.py in, e.g. \"framework\", \"application/demobrowser\""
)
parser.add_option(
"-c", "--clean-up", dest="cleanup", default=buildconf['doCleanup'], action="store_true",
help="Remove all created files in staging dir after building and copying"
)
parser.add_option(
"-l", "--log-file", dest="logfile", default=buildconf['logfile'], type="string",
help="Name of log file"
)
parser.add_option(
"-d", "--demon-mode", dest="demonMode", default=False, action="store_true",
help="Run as demon"
)
parser.add_option(
"-z", "--zap-output", dest="zapOut", default=False, action="store_true",
help="All output to terminal"
)
parser.add_option(
"-s", "--log-size", dest="logSize", type="long", default=None,
help="Log file size (in byte; default: unlimited)"
)
parser.add_option(
"-n", "--no-svn-check", dest="noSvnCheck", default=False, action="store_true",
help="Start generate process even if there were no changes in the repository."
)
parser.add_option(
"-N", "--no-svn-update", dest="noSvnUpdate", default=False, action="store_true",
help="Do not update the repository before starting the generate process."
)
parser.add_option(
"-C", "--clean", dest="distclean", default=False, action="store_true",
help="Run distclean before building"
)
(options, args) = parser.parse_args()
if options.zapOut:
options.logfile = None
return (options, args)
def goto_workdir(workdir):
if not os.path.exists(workdir):
os.mkdir(workdir)
os.chdir(workdir)
def prepare_output(logfile):
# redirect std streams, also for child processes
global sold, eold
if (logfile != None):
sold = sys.stdout
eold = sys.stderr
sys.stdout = open(logfile, 'a')
sys.stderr = sys.stdout
def check_logfile(logfile):
if (logfile != None):
sys.stdout.flush()
if options.logSize != None:
sys.stdout.truncate(options.logSize)
def invoke_external(cmd):
import subprocess
p = subprocess.Popen(cmd, shell=True,
stdout=sys.stdout,
stderr=sys.stderr)
return p.wait()
def invoke_piped(cmd):
import subprocess
p = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
output, errout = p.communicate()
rcode = p.returncode
return (rcode, output, errout)
def svn_check(target,revision):
""" See in svn repos whether target has been changed (in respect to revision).
For this check to work, target has to be checked out into stagedir once
by hand.
'True' means SVN_is_newer.
"""
# %svninfo <rootdir> # yields local 'overall' version
# %svn status --show-updates <rootdir> # compares local tree against repos
#targetdir = options.stagedir+target
targetdir = os.path.join(options.stagedir,target)
ret,out,err = invoke_piped('svn status --show-updates '+targetdir)
if ret or len(err):
raise RuntimeError, "Unable to get svn status of "+targetdir+": "+err
# just check for modified files in repository
#if len(outt) > 2: # you always get 'Status against revision: XXXX\n'
outt = out.split('\n')
if len(filter(lambda s: s[6:9]==' * ', outt)) > 0:
return True
else:
return False
def svn_checkout(target,revision):
rc = invoke_external("svn co %s/%s %s" % (buildconf['svn_base_url'],target,target))
return rc
def make(target):
rc = invoke_external("make -f tool/release/Makefile.release %s" % target)
return rc
def copy_archives(target):
# assert: cwd = ".../frontend"
rc = invoke_external("cp %s* %s" % ('release/qooxdoo-',buildconf['download_dir']))
return rc
def cleanup(target):
# make sure we don't get conflicts
rc = invoke_external("svn --recursive revert %s" % target)
return rc
def date():
" Print a nicely formatted datetime string "
import time
print
print time.ctime()
print
return
#rc = build_packet('tags/release_0_7',0)
#rc = build_packet('trunc',0)
def build_packet(target,revision,generate):
if not options.noSvnUpdate:
cleanup(target)
print("Updating SVN")
svn_checkout(target,revision)
if (generate != None):
if (generate != "release"):
working_dir = os.path.join(options.stagedir, target,options.path)
print("Changing dir to: " + working_dir)
os.chdir(working_dir)
if (options.distclean):
print("Clearing cache")
clRc = invoke_external(buildconf['pycmd'] + "generate.py distclean")
print("Starting generator")
genRc = invoke_external(buildconf['pycmd'] + "generate.py " + generate)
if (genRc != 0):
print ("Generator exited with status " + repr(genRc))
sys.exit(genRc)
else:
goto_workdir(os.path.join(target))
date()
make(generate)
date()
return 0
def build_targets(targList):
rc = 0
for target in targList:
if options.noSvnCheck or svn_check(target,0):
goto_workdir(options.stagedir)
if (options.generate):
print "Target: "+target
rc = build_packet(target,0,options.generate)
else:
rc = build_packet(target,0,None)
if (options.generate == "release"):
copy_archives(target)
if (options.cleanup):
cleanup(target)
return rc
def main():
global options, args
(options,args) = get_computed_conf()
prepare_output(options.logfile)
target = options.target
release = options.release
if (platform.system() == "Windows"):
buildconf['pycmd'] = sys.executable + " "
if (options.demonMode):
while (1):
check_logfile(options.logfile)
rc = build_targets(buildconf['targets'])
time.sleep(buildconf['checkInterval']*60)
else:
check_logfile(options.logfile)
rc = build_targets([target])
return rc
if __name__ == "__main__":
try:
rc = main()
except KeyboardInterrupt:
print
print " * Keyboard Interrupt"
rc = 1
sys.exit(rc)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2007-2009 1&1 Internet AG, Germany, http://www.1und1.de
#
# License:
# MIT: https://opensource.org/licenses/MIT
# See the LICENSE file in the project's top-level directory for details.
#
# Authors:
# * <NAME> (thron7)
# * <NAME> (d_wagner)
#
################################################################################
# NAME
# BAT Build - creating local qooxdoo builds
#
# DESCRIPTION
# This is the "Build" part of qooxdoo's "Build-And-Test" environment.
# It is a small, stand-alone continuous integration server for qooxdoo. It
# monitors changes in an SVN repository, maintains a current local checkout,
# and with every update runs some build targets on it. Messages are written to
# a log file.
import os, sys, platform
import optparse, time, re
# some defaults
buildconf = {
'svn_base_url' : 'https://qooxdoo.svn.sourceforge.net/svnroot/qooxdoo',
'stage_dir' : '/var/www/qx',
'logfile' : 'bat_build.log',
# change the next entry, to e.g. include a release candidate 'tags/release_0_8'
'targets' : ['trunk'],
'download_dir' : '/var/www/downloads',
'doCleanup' : False,
'checkInterval': 10, # 10min - beware of time it takes for a build before re-check
'generate' : False,
'path' : 'application/demobrowser',
'pycmd' : './'
#'disk_space' : '2G',
#'cpu_consume' : '20%',
#'time_limit' : '30m',
}
def get_computed_conf():
parser = optparse.OptionParser()
parser.add_option(
"-w", "--work-dir", dest="stagedir", default=buildconf['stage_dir'], type="string",
help="Directory for checking out and making the target"
)
parser.add_option(
"-t", "--build-target", dest="target", default=buildconf['targets'][0], type="string",
help="Target to build (e.g. \"trunk\")"
)
parser.add_option(
"-r", "--build-release", dest="release", default=None, type="string",
help="Release version (SVN) of target to build (e.g. \"9077\")"
)
parser.add_option(
"-g", "--generate-job", dest="generate", default=buildconf['generate'], type="string",
help="Which generator job to run, e.g. \"release\", \"source\", \"build\""
)
parser.add_option(
"-p", "--generate-path", dest="path", default=buildconf['path'], type="string",
help="Path to run generate.py in, e.g. \"framework\", \"application/demobrowser\""
)
parser.add_option(
"-c", "--clean-up", dest="cleanup", default=buildconf['doCleanup'], action="store_true",
help="Remove all created files in staging dir after building and copying"
)
parser.add_option(
"-l", "--log-file", dest="logfile", default=buildconf['logfile'], type="string",
help="Name of log file"
)
parser.add_option(
"-d", "--demon-mode", dest="demonMode", default=False, action="store_true",
help="Run as demon"
)
parser.add_option(
"-z", "--zap-output", dest="zapOut", default=False, action="store_true",
help="All output to terminal"
)
parser.add_option(
"-s", "--log-size", dest="logSize", type="long", default=None,
help="Log file size (in byte; default: unlimited)"
)
parser.add_option(
"-n", "--no-svn-check", dest="noSvnCheck", default=False, action="store_true",
help="Start generate process even if there were no changes in the repository."
)
parser.add_option(
"-N", "--no-svn-update", dest="noSvnUpdate", default=False, action="store_true",
help="Do not update the repository before starting the generate process."
)
parser.add_option(
"-C", "--clean", dest="distclean", default=False, action="store_true",
help="Run distclean before building"
)
(options, args) = parser.parse_args()
if options.zapOut:
options.logfile = None
return (options, args)
def goto_workdir(workdir):
if not os.path.exists(workdir):
os.mkdir(workdir)
os.chdir(workdir)
def prepare_output(logfile):
# redirect std streams, also for child processes
global sold, eold
if (logfile != None):
sold = sys.stdout
eold = sys.stderr
sys.stdout = open(logfile, 'a')
sys.stderr = sys.stdout
def check_logfile(logfile):
if (logfile != None):
sys.stdout.flush()
if options.logSize != None:
sys.stdout.truncate(options.logSize)
def invoke_external(cmd):
import subprocess
p = subprocess.Popen(cmd, shell=True,
stdout=sys.stdout,
stderr=sys.stderr)
return p.wait()
def invoke_piped(cmd):
import subprocess
p = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
output, errout = p.communicate()
rcode = p.returncode
return (rcode, output, errout)
def svn_check(target,revision):
""" See in svn repos whether target has been changed (in respect to revision).
For this check to work, target has to be checked out into stagedir once
by hand.
'True' means SVN_is_newer.
"""
# %svninfo <rootdir> # yields local 'overall' version
# %svn status --show-updates <rootdir> # compares local tree against repos
#targetdir = options.stagedir+target
targetdir = os.path.join(options.stagedir,target)
ret,out,err = invoke_piped('svn status --show-updates '+targetdir)
if ret or len(err):
raise RuntimeError, "Unable to get svn status of "+targetdir+": "+err
# just check for modified files in repository
#if len(outt) > 2: # you always get 'Status against revision: XXXX\n'
outt = out.split('\n')
if len(filter(lambda s: s[6:9]==' * ', outt)) > 0:
return True
else:
return False
def svn_checkout(target,revision):
rc = invoke_external("svn co %s/%s %s" % (buildconf['svn_base_url'],target,target))
return rc
def make(target):
rc = invoke_external("make -f tool/release/Makefile.release %s" % target)
return rc
def copy_archives(target):
# assert: cwd = ".../frontend"
rc = invoke_external("cp %s* %s" % ('release/qooxdoo-',buildconf['download_dir']))
return rc
def cleanup(target):
# make sure we don't get conflicts
rc = invoke_external("svn --recursive revert %s" % target)
return rc
def date():
" Print a nicely formatted datetime string "
import time
print
print time.ctime()
print
return
#rc = build_packet('tags/release_0_7',0)
#rc = build_packet('trunc',0)
def build_packet(target,revision,generate):
if not options.noSvnUpdate:
cleanup(target)
print("Updating SVN")
svn_checkout(target,revision)
if (generate != None):
if (generate != "release"):
working_dir = os.path.join(options.stagedir, target,options.path)
print("Changing dir to: " + working_dir)
os.chdir(working_dir)
if (options.distclean):
print("Clearing cache")
clRc = invoke_external(buildconf['pycmd'] + "generate.py distclean")
print("Starting generator")
genRc = invoke_external(buildconf['pycmd'] + "generate.py " + generate)
if (genRc != 0):
print ("Generator exited with status " + repr(genRc))
sys.exit(genRc)
else:
goto_workdir(os.path.join(target))
date()
make(generate)
date()
return 0
def build_targets(targList):
rc = 0
for target in targList:
if options.noSvnCheck or svn_check(target,0):
goto_workdir(options.stagedir)
if (options.generate):
print "Target: "+target
rc = build_packet(target,0,options.generate)
else:
rc = build_packet(target,0,None)
if (options.generate == "release"):
copy_archives(target)
if (options.cleanup):
cleanup(target)
return rc
def main():
global options, args
(options,args) = get_computed_conf()
prepare_output(options.logfile)
target = options.target
release = options.release
if (platform.system() == "Windows"):
buildconf['pycmd'] = sys.executable + " "
if (options.demonMode):
while (1):
check_logfile(options.logfile)
rc = build_targets(buildconf['targets'])
time.sleep(buildconf['checkInterval']*60)
else:
check_logfile(options.logfile)
rc = build_targets([target])
return rc
if __name__ == "__main__":
try:
rc = main()
except KeyboardInterrupt:
print
print " * Keyboard Interrupt"
rc = 1
sys.exit(rc)
| en | 0.704919 | #!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # qooxdoo - the new era of web development # # http://qooxdoo.org # # Copyright: # 2007-2009 1&1 Internet AG, Germany, http://www.1und1.de # # License: # MIT: https://opensource.org/licenses/MIT # See the LICENSE file in the project's top-level directory for details. # # Authors: # * <NAME> (thron7) # * <NAME> (d_wagner) # ################################################################################ # NAME # BAT Build - creating local qooxdoo builds # # DESCRIPTION # This is the "Build" part of qooxdoo's "Build-And-Test" environment. # It is a small, stand-alone continuous integration server for qooxdoo. It # monitors changes in an SVN repository, maintains a current local checkout, # and with every update runs some build targets on it. Messages are written to # a log file. # some defaults # change the next entry, to e.g. include a release candidate 'tags/release_0_8' # 10min - beware of time it takes for a build before re-check #'disk_space' : '2G', #'cpu_consume' : '20%', #'time_limit' : '30m', # redirect std streams, also for child processes See in svn repos whether target has been changed (in respect to revision). For this check to work, target has to be checked out into stagedir once by hand. 'True' means SVN_is_newer. # %svninfo <rootdir> # yields local 'overall' version # %svn status --show-updates <rootdir> # compares local tree against repos #targetdir = options.stagedir+target # just check for modified files in repository #if len(outt) > 2: # you always get 'Status against revision: XXXX\n' # assert: cwd = ".../frontend" # make sure we don't get conflicts #rc = build_packet('tags/release_0_7',0) #rc = build_packet('trunc',0) | 1.959656 | 2 |
release_check.py | dwhswenson/autorelease | 3 | 6622338 | <filename>release_check.py
#/usr/bin/env python
from __future__ import print_function
import sys
import argparse
import setup
#import contact_map
from packaging.version import Version
from autorelease import DefaultCheckRunner, conda_recipe_version
from autorelease.version import get_setup_version
repo_path = '.'
SETUP_VERSION = get_setup_version(None, directory='.')
versions = {
#'package': contact_map.version.version,
'setup.py': SETUP_VERSION,
'conda-recipe': conda_recipe_version('devtools/conda-recipe/meta.yaml'),
}
RELEASE_BRANCHES = ['stable']
RELEASE_TAG = "v" + Version(SETUP_VERSION).base_version
if __name__ == "__main__":
checker = DefaultCheckRunner(
versions=versions,
setup=setup,
repo_path='.'
)
checker.release_branches = RELEASE_BRANCHES + [RELEASE_TAG]
tests = checker.select_tests()
skip = []
#skip = [checker.git_repo_checks.reasonable_desired_version]
for test in skip:
skip_test = [t for t in tests if t[0] == test][0]
tests.remove(skip_test)
n_fails = checker.run_as_test(tests)
| <filename>release_check.py
#/usr/bin/env python
from __future__ import print_function
import sys
import argparse
import setup
#import contact_map
from packaging.version import Version
from autorelease import DefaultCheckRunner, conda_recipe_version
from autorelease.version import get_setup_version
repo_path = '.'
SETUP_VERSION = get_setup_version(None, directory='.')
versions = {
#'package': contact_map.version.version,
'setup.py': SETUP_VERSION,
'conda-recipe': conda_recipe_version('devtools/conda-recipe/meta.yaml'),
}
RELEASE_BRANCHES = ['stable']
RELEASE_TAG = "v" + Version(SETUP_VERSION).base_version
if __name__ == "__main__":
checker = DefaultCheckRunner(
versions=versions,
setup=setup,
repo_path='.'
)
checker.release_branches = RELEASE_BRANCHES + [RELEASE_TAG]
tests = checker.select_tests()
skip = []
#skip = [checker.git_repo_checks.reasonable_desired_version]
for test in skip:
skip_test = [t for t in tests if t[0] == test][0]
tests.remove(skip_test)
n_fails = checker.run_as_test(tests)
| en | 0.232306 | #/usr/bin/env python #import contact_map #'package': contact_map.version.version, #skip = [checker.git_repo_checks.reasonable_desired_version] | 1.927331 | 2 |
infrastructure/migrations/0002_auto_20170911_1629.py | comcidis/comcidis-portal | 0 | 6622339 | <reponame>comcidis/comcidis-portal<filename>infrastructure/migrations/0002_auto_20170911_1629.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-11 16:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('infrastructure', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='hardware',
name='unit',
field=models.CharField(choices=[('GB', 'GB'), ('TB', 'TB'), ('CO', 'Cores'), ('BP', 'bps')], default='CO', max_length=2),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-11 16:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('infrastructure', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='hardware',
name='unit',
field=models.CharField(choices=[('GB', 'GB'), ('TB', 'TB'), ('CO', 'Cores'), ('BP', 'bps')], default='CO', max_length=2),
),
] | en | 0.776688 | # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-11 16:29 | 1.801157 | 2 |
botleft.py | judasgutenberg/rover | 1 | 6622340 | <gh_stars>1-10
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.OUT)
GPIO.output(24, GPIO.HIGH)
GPIO.setup(19,GPIO.OUT)
GPIO.setup(26,GPIO.OUT)
GPIO.output(19, GPIO.LOW)
GPIO.output(26, GPIO.HIGH)
for x in range(0,10):
GPIO.output(24, GPIO.HIGH)
time.sleep(0.02)
GPIO.output(24, GPIO.LOW)
time.sleep(0.08)
GPIO.output(24, GPIO.LOW)
GPIO.cleanup()
| import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.OUT)
GPIO.output(24, GPIO.HIGH)
GPIO.setup(19,GPIO.OUT)
GPIO.setup(26,GPIO.OUT)
GPIO.output(19, GPIO.LOW)
GPIO.output(26, GPIO.HIGH)
for x in range(0,10):
GPIO.output(24, GPIO.HIGH)
time.sleep(0.02)
GPIO.output(24, GPIO.LOW)
time.sleep(0.08)
GPIO.output(24, GPIO.LOW)
GPIO.cleanup() | none | 1 | 2.803625 | 3 | |
scripts/format_source.py | vmware/vmaccel | 3 | 6622341 | <reponame>vmware/vmaccel<filename>scripts/format_source.py
#!/usr/bin/python
"""
*******************************************************************************
Copyright (c) 2016-2019 VMware, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
"""
"""
format_source.py
Formats the source per the coding standards and clang-format.
"""
from optparse import OptionParser
from datetime import datetime
import os
import platform
import subprocess
import sys
def FormatSourceTree(treeRoot, clangPath, includeDirs, fileExtensions):
absPath = os.path.abspath(treeRoot)
sourceFiles = os.listdir(absPath)
clangFormatPath = os.path.join(clangPath, "clang-format")
for fileName in sourceFiles:
filePath = os.path.join(absPath, fileName)
if (os.path.isfile(filePath) and
filePath != os.path.abspath(__file__)):
for ext in fileExtensions:
if not filePath.endswith(ext):
continue
print("Formatting: %s" % (filePath))
os.system("%s -i %s" % (clangFormatPath, filePath))
elif (os.path.isdir(filePath) and
fileName != "external" and
fileName != "build"):
FormatSourceTree(filePath, clangPath, includeDirs,
fileExtensions)
if __name__ == "__main__":
startTime = datetime.now()
print("*********************************************************************************")
print("Formatting source tree using clang-format")
print("")
print("os.name = %s" % (os.name))
print("platform.system() = %s" % (platform.system()))
print("sys.platform = %s" % (sys.platform))
print("")
print("Time = %s" % (startTime))
print("********************************************************************************")
#
# Handle command line options for the parser
#
parser = OptionParser()
parser.add_option("-c", "--clangPath", dest="CLANG_PATH",
default=None,
help="Specifies the path for clang.")
parser.add_option("-t", "--sourceTree", dest="SOURCE_TREE",
default=None,
help="Specifies the path for the source tree to be "
"formatted.")
parser.add_option("-i", "--includeDirs", dest="INCLUDE_DIRS",
default=None,
help="Specifies the include directories for the source tree.")
parser.add_option("-x", "--extensions", dest="FILE_EXTENSIONS",
default=".c,.cpp,.h,.hpp,.m,.cc,.java,.js",
help="Specifies a comma delimited list of file extensions.")
(options, args) = parser.parse_args()
#
# Check for the required json argument file
#
clangPath = os.path.abspath(options.CLANG_PATH)
includeDirs = os.path.abspath(options.INCLUDE_DIRS)
if (options.CLANG_PATH is None or options.CLANG_PATH == "" or
not os.path.exists(clangPath)):
print("ERROR: You must supply a directory containing clang-format")
print(" e.g. ../build/external/spirv-llvm/bin")
sys.exit(1)
print("clang path: %s" % (clangPath))
print("Source tree: %s" % (os.path.abspath(options.SOURCE_TREE)))
print("Include directories: %s" % (includeDirs))
print("File extensions: %s" % (options.FILE_EXTENSIONS))
print("")
FormatSourceTree(options.SOURCE_TREE, clangPath, includeDirs,
options.FILE_EXTENSIONS.split(","))
endTime = datetime.now()
print("********************************************************************************")
print("Start Time: %s" % (str(startTime)))
print("End Time : %s" % (str(endTime)))
print("Elapsed : %s" % (str(endTime - startTime)))
print("")
print("Exiting format_source.py...")
print("********************************************************************************")
sys.exit(0)
| #!/usr/bin/python
"""
*******************************************************************************
Copyright (c) 2016-2019 VMware, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
"""
"""
format_source.py
Formats the source per the coding standards and clang-format.
"""
from optparse import OptionParser
from datetime import datetime
import os
import platform
import subprocess
import sys
def FormatSourceTree(treeRoot, clangPath, includeDirs, fileExtensions):
absPath = os.path.abspath(treeRoot)
sourceFiles = os.listdir(absPath)
clangFormatPath = os.path.join(clangPath, "clang-format")
for fileName in sourceFiles:
filePath = os.path.join(absPath, fileName)
if (os.path.isfile(filePath) and
filePath != os.path.abspath(__file__)):
for ext in fileExtensions:
if not filePath.endswith(ext):
continue
print("Formatting: %s" % (filePath))
os.system("%s -i %s" % (clangFormatPath, filePath))
elif (os.path.isdir(filePath) and
fileName != "external" and
fileName != "build"):
FormatSourceTree(filePath, clangPath, includeDirs,
fileExtensions)
if __name__ == "__main__":
startTime = datetime.now()
print("*********************************************************************************")
print("Formatting source tree using clang-format")
print("")
print("os.name = %s" % (os.name))
print("platform.system() = %s" % (platform.system()))
print("sys.platform = %s" % (sys.platform))
print("")
print("Time = %s" % (startTime))
print("********************************************************************************")
#
# Handle command line options for the parser
#
parser = OptionParser()
parser.add_option("-c", "--clangPath", dest="CLANG_PATH",
default=None,
help="Specifies the path for clang.")
parser.add_option("-t", "--sourceTree", dest="SOURCE_TREE",
default=None,
help="Specifies the path for the source tree to be "
"formatted.")
parser.add_option("-i", "--includeDirs", dest="INCLUDE_DIRS",
default=None,
help="Specifies the include directories for the source tree.")
parser.add_option("-x", "--extensions", dest="FILE_EXTENSIONS",
default=".c,.cpp,.h,.hpp,.m,.cc,.java,.js",
help="Specifies a comma delimited list of file extensions.")
(options, args) = parser.parse_args()
#
# Check for the required json argument file
#
clangPath = os.path.abspath(options.CLANG_PATH)
includeDirs = os.path.abspath(options.INCLUDE_DIRS)
if (options.CLANG_PATH is None or options.CLANG_PATH == "" or
not os.path.exists(clangPath)):
print("ERROR: You must supply a directory containing clang-format")
print(" e.g. ../build/external/spirv-llvm/bin")
sys.exit(1)
print("clang path: %s" % (clangPath))
print("Source tree: %s" % (os.path.abspath(options.SOURCE_TREE)))
print("Include directories: %s" % (includeDirs))
print("File extensions: %s" % (options.FILE_EXTENSIONS))
print("")
FormatSourceTree(options.SOURCE_TREE, clangPath, includeDirs,
options.FILE_EXTENSIONS.split(","))
endTime = datetime.now()
print("********************************************************************************")
print("Start Time: %s" % (str(startTime)))
print("End Time : %s" % (str(endTime)))
print("Elapsed : %s" % (str(endTime - startTime)))
print("")
print("Exiting format_source.py...")
print("********************************************************************************")
sys.exit(0) | en | 0.59428 | #!/usr/bin/python ******************************************************************************* Copyright (c) 2016-2019 VMware, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* format_source.py Formats the source per the coding standards and clang-format. # # Handle command line options for the parser # # # Check for the required json argument file # | 1.352246 | 1 |
lib/si4703.py | Liorst4/aramcon-firmware | 8 | 6622342 | <gh_stars>1-10
# SI4703 RDS FM Receiver driver for CircuitPython
# Released under the MIT License
# Note:
# Some of the code was inspired by https://github.com/achilikin/RdSpi, for which the license
# is unclear - some of the source files specify GPLv2+, while others specify BSD.
#
# Copyright (c) 2019, 2020 <NAME> and <NAME>
from time import sleep
from struct import pack, unpack
import adafruit_bus_device.i2c_device as i2c_device
DEBUG = False
SI4703_ADDR = 0x10
SI4703_MAGIC = 0x1242
# POWERCFG (0x2)
POWERCFG_DSMUTE = 1 << 15
POWERCFG_DMUTE = 1 << 14
POWERCFG_MONO = 1 << 13
POWERCFG_RDSM = 1 << 11
POWERCFG_SKMODE = 1 << 10
POWERCFG_SEEKUP = 1 << 9
POWERCFG_SEEK = 1 << 8
POWERCFG_PWR_DISABLE = 1 << 6
POWERCFG_PWR_ENABLE = 1 << 0
# CHANNEL (0x3)
CHANNEL_TUNE = 1 << 15
CHANNEL_CHAN = 0x003FF
# SYSCONF1 (0x4)
SYSCONF1_RDSIEN = 1 << 15
SYSCONF1_STCIEN = 1 << 14
SYSCONF1_RDS = 1 << 12
SYSCONF1_DE = 1 << 11
SYSCONF1_AGCD = 1 << 10
SYSCONF1_BLNDADJ= 0x00C0
SYSCONF1_GPIO3 = 0x0030
SYSCONF1_GPIO2 = 0x000C
SYSCONF1_GPIO1 = 0x0003
# SYSCONF2 (0x05)
SYSCONF2_SEEKTH = 0xFF00
SYSCONF2_BAND = 0x00C0
SYSCONF2_SPACING = 0x0030
SYSCONF2_VOLUME = 0x000F
SYSCONF2_BAND0 = 0x0000 # 87.5 - 107 MHz (Europe, USA)
SYSCONF2_BAND1 = 0x0040 # 76-108 MHz (Japan wide band)
SYSCONF2_BAND2 = 0x0080 # 76-90 MHz (Japan)
SYSCONF2_SPACE50 = 0x0020 # 50 kHz spacing
SYSCONF2_SPACE100 = 0x0010 # 100 kHz (Europe, Japan)
SYSCONF2_SPACE200 = 0x0000 # 200 kHz (USA, Australia)
# SYSCONF3 (0x06)
SYSCONF3_SMUTER = 0xC000
SYSCONF3_SMUTEA = 0x3000
SYSCONF3_RDSPRF = 1 << 9
SYSCONF3_VOLEXT = 1 << 8
SYSCONF3_SKSNR = 0x00F0
SYSCONF3_SKCNT = 0x000F
# TEST1 (0x07)
TEST1_XOSCEN = 1 << 15
TEST1_AHIZEN = 1 << 14
# STATUSRSSI (0x0A)
STATUSRSSI_RDSR = 1 << 15
STATUSRSSI_STC = 1 << 14
STATUSRSSI_SFBL = 1 << 13
STATUSRSSI_AFCRL = 1 << 12
STATUSRSSI_RDSS = 1 << 11
STATUSRSSI_BLERA = 0x0600
STATUSRSSI_STEREO = 1 << 8
STATUSRSSI_RSSI = 0x00FF
# READCHAN (0x0B)
READCHAN_BLERB = 0xC000
READCHAN_BLERC = 0x3000
READCHAN_BLERD = 0x0C00
READCHAN_RCHAN = 0x03FF
SI_BAND = [[8750, 10800], [7600, 10800], [7600, 9000]]
SI_SPACE = [20, 10, 5]
# Registers
REGS = [
'DEVICEID',
'CHIPID',
'POWERCFG',
'CHANNEL',
'SYSCONF1',
'SYSCONF2',
'SYSCONF3',
'TEST1',
'TEST2',
'BOOTCONF',
'STATUSRSSI',
'READCHAN',
'RDSA',
'RDSB',
'RDSC',
'RDSD'
]
def pretty_print_regs(registers, title=None):
if type(registers) is not dict or not DEBUG:
return False
if title:
print("[Si4703] {}:".format(title))
for index, reg_name in enumerate(REGS):
print('\t{:X} 0x{:04X}: {}'.format(index, registers[reg_name], reg_name))
class SI4703:
"""SI4703 RDS FM receiver driver. Parameters:
- i2c: The I2C bus connected to the board.
- reset: A DigitalInOut instance connected to the board's reset line
- address (optional): The I2C address if it has been changed.
- channel (optional): Channel to tune to initially. Set to the desired FM frequency, e.g. 91.8
"""
def __init__(self, i2c, resetpin, address=SI4703_ADDR, channel=95):
self._resetpin = resetpin
self._channel = channel
self._resetpin.switch_to_output(True)
self._device = i2c_device.I2CDevice(i2c, address)
def read_registers(self):
registers = {}
fm_registers_unsorted = bytearray(32)
with self._device as i2c:
i2c.readinto(fm_registers_unsorted)
for i in range(0, 32, 2):
# Each register is a short, and output starts from 0x0A, wraps around at 0x10, don't ask.
register_index = int(0x0A + (i / 2))
if register_index >= 0x10:
register_index -= 0x10
registers[REGS[register_index]] = unpack('>H', fm_registers_unsorted[i:i+2])[0]
return registers
def write_registers(self, registers, count = None):
if type(registers) is not dict:
return False
if not set(REGS).issubset(set(registers.keys())):
return False
# Only these are allowed to be set and at this specific order
registers_batch = pack('>HHHHHH', registers['POWERCFG'],
registers['CHANNEL'],
registers['SYSCONF1'],
registers['SYSCONF2'],
registers['SYSCONF3'],
registers['TEST1'])
if count:
registers_batch = registers_batch[:count * 2]
if DEBUG:
from binascii import hexlify
print('[Si4703] Write: {}'.format(hexlify(registers_batch)))
with self._device as i2c:
i2c.write(registers_batch)
return True
def power_up(self):
registers = self.read_registers()
if registers['DEVICEID'] != SI4703_MAGIC:
raise RuntimeError('Invalid device ID for SI4703: {:%04X}'.format(registers['DEVICEID']))
# set only ENABLE bit, leaving device muted
registers['POWERCFG'] = POWERCFG_PWR_ENABLE
# by default we allow wrap by not setting SKMODE
# registers['POWERCFG'] |= POWERCFG_SKMODE
registers['SYSCONF1'] |= SYSCONF1_RDS # enable RDS
# Set mono/stereo blend adjust to default 0 or 31-49 RSSI
registers['SYSCONF1'] &= ~SYSCONF1_BLNDADJ
# set different BLDADJ if needed
# x00=31-49, x40=37-55, x80=19-37,xC0=25-43 RSSI
# registers['SYSCONF1'] |= 0x0080
# enable RDS High-Performance Mode
registers['SYSCONF3'] |= SYSCONF3_RDSPRF
registers['SYSCONF1'] |= SYSCONF1_DE # set 50us De-Emphasis for Europe, skip for USA
# select general Europe/USA 87.5 - 108 MHz band
registers['SYSCONF2'] = SYSCONF2_BAND0 | SYSCONF2_SPACE100 # 100kHz channel spacing for Europe
# apply recommended seek settings for "most stations"
registers['SYSCONF2'] &= ~SYSCONF2_SEEKTH
registers['SYSCONF2'] |= 0x0C00 # SEEKTH 12
registers['SYSCONF3'] &= 0xFF00
registers['SYSCONF3'] |= 0x004F # SKSNR 4, SKCNT 15
self.write_registers(registers)
# Recommended powerup time
sleep(0.110)
return True
def reset(self):
self._resetpin.value = False
sleep(0.01) # 10ms
self._resetpin.value = True
sleep(0.001) # 1ms
registers = self.read_registers()
pretty_print_regs(registers, "After reset")
registers['TEST1'] |= TEST1_XOSCEN
self.write_registers(registers)
sleep(0.5) # Recommended delay
registers = self.read_registers()
pretty_print_regs(registers, "Oscillator enabled")
# The only way to reliable start the device is to powerdown and powerup
# Just powering up does not work for me after cold start
registers['POWERCFG'] = POWERCFG_PWR_DISABLE | POWERCFG_PWR_ENABLE
self.write_registers(registers, 1)
sleep(0.110)
self.power_up()
registers = self.read_registers()
pretty_print_regs(registers, "Power up")
# default channel
self.channel = self._channel
@property
def channel(self):
return self._channel
@channel.setter
def channel(self, value):
if type(value) not in [int, float]:
return False
freq = round(value * 100)
registers = self.read_registers()
pretty_print_regs(registers, "Before setting a channel")
band = (registers['SYSCONF2'] >> 6) & 0x03
space = (registers['SYSCONF2'] >> 4) & 0x03
if freq < SI_BAND[band][0]:
freq = SI_BAND[band][0]
if freq > SI_BAND[band][1]:
freq = SI_BAND[band][1]
nchan = (freq - SI_BAND[band][0]) // SI_SPACE[space]
registers['CHANNEL'] &= ~CHANNEL_CHAN
registers['CHANNEL'] |= nchan & CHANNEL_CHAN
registers['CHANNEL'] |= CHANNEL_TUNE
self.write_registers(registers)
sleep(0.01)
pretty_print_regs(registers, "After setting a channel")
# Poll to see if STC is set
while (self.read_registers()['STATUSRSSI'] & STATUSRSSI_STC) == 0:
sleep(0.01)
registers = self.read_registers()
registers['CHANNEL'] &= ~CHANNEL_TUNE # Clear the tune after a tune has completed
self.write_registers(registers)
# Wait for the si4703 to clear the STC as well
# Poll to see if STC is set
while (self.read_registers()['STATUSRSSI'] & STATUSRSSI_STC) != 0:
sleep(0.01)
self._channel = value
@property
def volume(self):
registers = self.read_registers()
volume = registers['SYSCONF2'] & 0xF
if registers['SYSCONF3'] & SYSCONF3_VOLEXT:
volume += 15
return volume
@volume.setter
def volume(self, volume):
registers = self.read_registers()
registers['SYSCONF3'] &= ~SYSCONF3_VOLEXT
if volume > 15:
registers['SYSCONF3'] |= SYSCONF3_VOLEXT
volume -= 15
if volume:
registers['POWERCFG'] |= POWERCFG_DSMUTE | POWERCFG_DMUTE # unmute
else:
registers['POWERCFG'] &= ~(POWERCFG_DSMUTE | POWERCFG_DMUTE) # mute
# Clear volume bits
registers['SYSCONF2'] &= 0xFFF0
# Set new volume
registers['SYSCONF2'] |= volume & 0xF
self.write_registers(registers)
| # SI4703 RDS FM Receiver driver for CircuitPython
# Released under the MIT License
# Note:
# Some of the code was inspired by https://github.com/achilikin/RdSpi, for which the license
# is unclear - some of the source files specify GPLv2+, while others specify BSD.
#
# Copyright (c) 2019, 2020 <NAME> and <NAME>
from time import sleep
from struct import pack, unpack
import adafruit_bus_device.i2c_device as i2c_device
DEBUG = False
SI4703_ADDR = 0x10
SI4703_MAGIC = 0x1242
# POWERCFG (0x2)
POWERCFG_DSMUTE = 1 << 15
POWERCFG_DMUTE = 1 << 14
POWERCFG_MONO = 1 << 13
POWERCFG_RDSM = 1 << 11
POWERCFG_SKMODE = 1 << 10
POWERCFG_SEEKUP = 1 << 9
POWERCFG_SEEK = 1 << 8
POWERCFG_PWR_DISABLE = 1 << 6
POWERCFG_PWR_ENABLE = 1 << 0
# CHANNEL (0x3)
CHANNEL_TUNE = 1 << 15
CHANNEL_CHAN = 0x003FF
# SYSCONF1 (0x4)
SYSCONF1_RDSIEN = 1 << 15
SYSCONF1_STCIEN = 1 << 14
SYSCONF1_RDS = 1 << 12
SYSCONF1_DE = 1 << 11
SYSCONF1_AGCD = 1 << 10
SYSCONF1_BLNDADJ= 0x00C0
SYSCONF1_GPIO3 = 0x0030
SYSCONF1_GPIO2 = 0x000C
SYSCONF1_GPIO1 = 0x0003
# SYSCONF2 (0x05)
SYSCONF2_SEEKTH = 0xFF00
SYSCONF2_BAND = 0x00C0
SYSCONF2_SPACING = 0x0030
SYSCONF2_VOLUME = 0x000F
SYSCONF2_BAND0 = 0x0000 # 87.5 - 107 MHz (Europe, USA)
SYSCONF2_BAND1 = 0x0040 # 76-108 MHz (Japan wide band)
SYSCONF2_BAND2 = 0x0080 # 76-90 MHz (Japan)
SYSCONF2_SPACE50 = 0x0020 # 50 kHz spacing
SYSCONF2_SPACE100 = 0x0010 # 100 kHz (Europe, Japan)
SYSCONF2_SPACE200 = 0x0000 # 200 kHz (USA, Australia)
# SYSCONF3 (0x06)
SYSCONF3_SMUTER = 0xC000
SYSCONF3_SMUTEA = 0x3000
SYSCONF3_RDSPRF = 1 << 9
SYSCONF3_VOLEXT = 1 << 8
SYSCONF3_SKSNR = 0x00F0
SYSCONF3_SKCNT = 0x000F
# TEST1 (0x07)
TEST1_XOSCEN = 1 << 15
TEST1_AHIZEN = 1 << 14
# STATUSRSSI (0x0A)
STATUSRSSI_RDSR = 1 << 15
STATUSRSSI_STC = 1 << 14
STATUSRSSI_SFBL = 1 << 13
STATUSRSSI_AFCRL = 1 << 12
STATUSRSSI_RDSS = 1 << 11
STATUSRSSI_BLERA = 0x0600
STATUSRSSI_STEREO = 1 << 8
STATUSRSSI_RSSI = 0x00FF
# READCHAN (0x0B)
READCHAN_BLERB = 0xC000
READCHAN_BLERC = 0x3000
READCHAN_BLERD = 0x0C00
READCHAN_RCHAN = 0x03FF
SI_BAND = [[8750, 10800], [7600, 10800], [7600, 9000]]
SI_SPACE = [20, 10, 5]
# Registers
REGS = [
'DEVICEID',
'CHIPID',
'POWERCFG',
'CHANNEL',
'SYSCONF1',
'SYSCONF2',
'SYSCONF3',
'TEST1',
'TEST2',
'BOOTCONF',
'STATUSRSSI',
'READCHAN',
'RDSA',
'RDSB',
'RDSC',
'RDSD'
]
def pretty_print_regs(registers, title=None):
if type(registers) is not dict or not DEBUG:
return False
if title:
print("[Si4703] {}:".format(title))
for index, reg_name in enumerate(REGS):
print('\t{:X} 0x{:04X}: {}'.format(index, registers[reg_name], reg_name))
class SI4703:
"""SI4703 RDS FM receiver driver. Parameters:
- i2c: The I2C bus connected to the board.
- reset: A DigitalInOut instance connected to the board's reset line
- address (optional): The I2C address if it has been changed.
- channel (optional): Channel to tune to initially. Set to the desired FM frequency, e.g. 91.8
"""
def __init__(self, i2c, resetpin, address=SI4703_ADDR, channel=95):
self._resetpin = resetpin
self._channel = channel
self._resetpin.switch_to_output(True)
self._device = i2c_device.I2CDevice(i2c, address)
def read_registers(self):
registers = {}
fm_registers_unsorted = bytearray(32)
with self._device as i2c:
i2c.readinto(fm_registers_unsorted)
for i in range(0, 32, 2):
# Each register is a short, and output starts from 0x0A, wraps around at 0x10, don't ask.
register_index = int(0x0A + (i / 2))
if register_index >= 0x10:
register_index -= 0x10
registers[REGS[register_index]] = unpack('>H', fm_registers_unsorted[i:i+2])[0]
return registers
def write_registers(self, registers, count = None):
if type(registers) is not dict:
return False
if not set(REGS).issubset(set(registers.keys())):
return False
# Only these are allowed to be set and at this specific order
registers_batch = pack('>HHHHHH', registers['POWERCFG'],
registers['CHANNEL'],
registers['SYSCONF1'],
registers['SYSCONF2'],
registers['SYSCONF3'],
registers['TEST1'])
if count:
registers_batch = registers_batch[:count * 2]
if DEBUG:
from binascii import hexlify
print('[Si4703] Write: {}'.format(hexlify(registers_batch)))
with self._device as i2c:
i2c.write(registers_batch)
return True
def power_up(self):
registers = self.read_registers()
if registers['DEVICEID'] != SI4703_MAGIC:
raise RuntimeError('Invalid device ID for SI4703: {:%04X}'.format(registers['DEVICEID']))
# set only ENABLE bit, leaving device muted
registers['POWERCFG'] = POWERCFG_PWR_ENABLE
# by default we allow wrap by not setting SKMODE
# registers['POWERCFG'] |= POWERCFG_SKMODE
registers['SYSCONF1'] |= SYSCONF1_RDS # enable RDS
# Set mono/stereo blend adjust to default 0 or 31-49 RSSI
registers['SYSCONF1'] &= ~SYSCONF1_BLNDADJ
# set different BLDADJ if needed
# x00=31-49, x40=37-55, x80=19-37,xC0=25-43 RSSI
# registers['SYSCONF1'] |= 0x0080
# enable RDS High-Performance Mode
registers['SYSCONF3'] |= SYSCONF3_RDSPRF
registers['SYSCONF1'] |= SYSCONF1_DE # set 50us De-Emphasis for Europe, skip for USA
# select general Europe/USA 87.5 - 108 MHz band
registers['SYSCONF2'] = SYSCONF2_BAND0 | SYSCONF2_SPACE100 # 100kHz channel spacing for Europe
# apply recommended seek settings for "most stations"
registers['SYSCONF2'] &= ~SYSCONF2_SEEKTH
registers['SYSCONF2'] |= 0x0C00 # SEEKTH 12
registers['SYSCONF3'] &= 0xFF00
registers['SYSCONF3'] |= 0x004F # SKSNR 4, SKCNT 15
self.write_registers(registers)
# Recommended powerup time
sleep(0.110)
return True
def reset(self):
self._resetpin.value = False
sleep(0.01) # 10ms
self._resetpin.value = True
sleep(0.001) # 1ms
registers = self.read_registers()
pretty_print_regs(registers, "After reset")
registers['TEST1'] |= TEST1_XOSCEN
self.write_registers(registers)
sleep(0.5) # Recommended delay
registers = self.read_registers()
pretty_print_regs(registers, "Oscillator enabled")
# The only way to reliable start the device is to powerdown and powerup
# Just powering up does not work for me after cold start
registers['POWERCFG'] = POWERCFG_PWR_DISABLE | POWERCFG_PWR_ENABLE
self.write_registers(registers, 1)
sleep(0.110)
self.power_up()
registers = self.read_registers()
pretty_print_regs(registers, "Power up")
# default channel
self.channel = self._channel
@property
def channel(self):
return self._channel
@channel.setter
def channel(self, value):
if type(value) not in [int, float]:
return False
freq = round(value * 100)
registers = self.read_registers()
pretty_print_regs(registers, "Before setting a channel")
band = (registers['SYSCONF2'] >> 6) & 0x03
space = (registers['SYSCONF2'] >> 4) & 0x03
if freq < SI_BAND[band][0]:
freq = SI_BAND[band][0]
if freq > SI_BAND[band][1]:
freq = SI_BAND[band][1]
nchan = (freq - SI_BAND[band][0]) // SI_SPACE[space]
registers['CHANNEL'] &= ~CHANNEL_CHAN
registers['CHANNEL'] |= nchan & CHANNEL_CHAN
registers['CHANNEL'] |= CHANNEL_TUNE
self.write_registers(registers)
sleep(0.01)
pretty_print_regs(registers, "After setting a channel")
# Poll to see if STC is set
while (self.read_registers()['STATUSRSSI'] & STATUSRSSI_STC) == 0:
sleep(0.01)
registers = self.read_registers()
registers['CHANNEL'] &= ~CHANNEL_TUNE # Clear the tune after a tune has completed
self.write_registers(registers)
# Wait for the si4703 to clear the STC as well
# Poll to see if STC is set
while (self.read_registers()['STATUSRSSI'] & STATUSRSSI_STC) != 0:
sleep(0.01)
self._channel = value
@property
def volume(self):
registers = self.read_registers()
volume = registers['SYSCONF2'] & 0xF
if registers['SYSCONF3'] & SYSCONF3_VOLEXT:
volume += 15
return volume
@volume.setter
def volume(self, volume):
registers = self.read_registers()
registers['SYSCONF3'] &= ~SYSCONF3_VOLEXT
if volume > 15:
registers['SYSCONF3'] |= SYSCONF3_VOLEXT
volume -= 15
if volume:
registers['POWERCFG'] |= POWERCFG_DSMUTE | POWERCFG_DMUTE # unmute
else:
registers['POWERCFG'] &= ~(POWERCFG_DSMUTE | POWERCFG_DMUTE) # mute
# Clear volume bits
registers['SYSCONF2'] &= 0xFFF0
# Set new volume
registers['SYSCONF2'] |= volume & 0xF
self.write_registers(registers) | en | 0.813656 | # SI4703 RDS FM Receiver driver for CircuitPython # Released under the MIT License # Note: # Some of the code was inspired by https://github.com/achilikin/RdSpi, for which the license # is unclear - some of the source files specify GPLv2+, while others specify BSD. # # Copyright (c) 2019, 2020 <NAME> and <NAME> # POWERCFG (0x2) # CHANNEL (0x3) # SYSCONF1 (0x4) # SYSCONF2 (0x05) # 87.5 - 107 MHz (Europe, USA) # 76-108 MHz (Japan wide band) # 76-90 MHz (Japan) # 50 kHz spacing # 100 kHz (Europe, Japan) # 200 kHz (USA, Australia) # SYSCONF3 (0x06) # TEST1 (0x07) # STATUSRSSI (0x0A) # READCHAN (0x0B) # Registers SI4703 RDS FM receiver driver. Parameters: - i2c: The I2C bus connected to the board. - reset: A DigitalInOut instance connected to the board's reset line - address (optional): The I2C address if it has been changed. - channel (optional): Channel to tune to initially. Set to the desired FM frequency, e.g. 91.8 # Each register is a short, and output starts from 0x0A, wraps around at 0x10, don't ask. # Only these are allowed to be set and at this specific order # set only ENABLE bit, leaving device muted # by default we allow wrap by not setting SKMODE # registers['POWERCFG'] |= POWERCFG_SKMODE # enable RDS # Set mono/stereo blend adjust to default 0 or 31-49 RSSI # set different BLDADJ if needed # x00=31-49, x40=37-55, x80=19-37,xC0=25-43 RSSI # registers['SYSCONF1'] |= 0x0080 # enable RDS High-Performance Mode # set 50us De-Emphasis for Europe, skip for USA # select general Europe/USA 87.5 - 108 MHz band # 100kHz channel spacing for Europe # apply recommended seek settings for "most stations" # SEEKTH 12 # SKSNR 4, SKCNT 15 # Recommended powerup time # 10ms # 1ms # Recommended delay # The only way to reliable start the device is to powerdown and powerup # Just powering up does not work for me after cold start # default channel # Poll to see if STC is set # Clear the tune after a tune has completed # Wait for the si4703 to clear the STC as well # Poll to see if STC is set # unmute # mute # Clear volume bits # Set new volume | 2.114577 | 2 |
tools/spm_to_vocab.py | Waino/OpenNMT-py | 6 | 6622343 | # converts a SentencePiece vocabulary to the format expected by dynamicdata
# (essentially converts float expected counts to "fixed precision" int pseudocounts,
# and inverts the order)
import sys
import math
OMIT = ('<unk>', '<s>', '</s>')
def convert(lines):
for line in lines:
w, c = line.rstrip('\n').split(None, 1)
if w in OMIT:
continue
c = math.exp(float(c)) * 1000000
c = int(c) + 1
yield c, w
if __name__ == '__main__':
for c, w in convert(sys.stdin):
print('{}\t{}'.format(c, w))
| # converts a SentencePiece vocabulary to the format expected by dynamicdata
# (essentially converts float expected counts to "fixed precision" int pseudocounts,
# and inverts the order)
import sys
import math
OMIT = ('<unk>', '<s>', '</s>')
def convert(lines):
for line in lines:
w, c = line.rstrip('\n').split(None, 1)
if w in OMIT:
continue
c = math.exp(float(c)) * 1000000
c = int(c) + 1
yield c, w
if __name__ == '__main__':
for c, w in convert(sys.stdin):
print('{}\t{}'.format(c, w))
| en | 0.77877 | # converts a SentencePiece vocabulary to the format expected by dynamicdata # (essentially converts float expected counts to "fixed precision" int pseudocounts, # and inverts the order) | 3.090866 | 3 |
tests/test_get_data/test_imf_data.py | jm-rivera/pydeflate | 0 | 6622344 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 12:18:13 2021
@author: jorge
"""
import pytest
from pydeflate.get_data import imf_data
from pydeflate import config
import sys
import io
import os
def test__update_weo():
"""Capture print statements which are only printed if download successful"""
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
imf_data._update_weo(2020, 1)
output = new_stdout.getvalue()
sys.stdout = old_stdout
print(output)
assert output[-21:] == "2020-Apr WEO dataset\n"
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
imf_data._update_weo(2020, 1)
output = new_stdout.getvalue()
sys.stdout = old_stdout
print(output)
assert output[0:7] == "Already"
# cleaning
file = config.paths.data + r"/weo2020_1.csv"
if os.path.exists(file):
os.remove(file)
def test_get_implied_ppp_rate():
result = imf_data.get_implied_ppp_rate()
result = result.loc[
(result.iso_code == "GTM") & (result.year.dt.year == 1991), "value"
]
assert round(result.sum(), 1) == 1.4
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 12:18:13 2021
@author: jorge
"""
import pytest
from pydeflate.get_data import imf_data
from pydeflate import config
import sys
import io
import os
def test__update_weo():
"""Capture print statements which are only printed if download successful"""
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
imf_data._update_weo(2020, 1)
output = new_stdout.getvalue()
sys.stdout = old_stdout
print(output)
assert output[-21:] == "2020-Apr WEO dataset\n"
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
imf_data._update_weo(2020, 1)
output = new_stdout.getvalue()
sys.stdout = old_stdout
print(output)
assert output[0:7] == "Already"
# cleaning
file = config.paths.data + r"/weo2020_1.csv"
if os.path.exists(file):
os.remove(file)
def test_get_implied_ppp_rate():
result = imf_data.get_implied_ppp_rate()
result = result.loc[
(result.iso_code == "GTM") & (result.year.dt.year == 1991), "value"
]
assert round(result.sum(), 1) == 1.4
| en | 0.775212 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Sat Nov 20 12:18:13 2021 @author: jorge Capture print statements which are only printed if download successful # cleaning | 2.149872 | 2 |
django/core/admin.py | reallinfo/lifelog | 0 | 6622345 | <filename>django/core/admin.py
from django.contrib import admin
from core.models import Action, Record
admin.site.register(Action)
admin.site.register(Record)
| <filename>django/core/admin.py
from django.contrib import admin
from core.models import Action, Record
admin.site.register(Action)
admin.site.register(Record)
| none | 1 | 1.428022 | 1 | |
Django 3 By Example-Book/Bookmark App/account/urls.py | ibnshayed/Python-Programming | 0 | 6622346 | <reponame>ibnshayed/Python-Programming
from django.urls import path, include
from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView, PasswordChangeDoneView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView
from .views import user_login, dashboard, register, edit
urlpatterns = [
# path('login/', user_login, name='login')
# path('login/', LoginView.as_view(), name='login'),
# path('logout/', LogoutView.as_view(), name='logout'),
# change password urls
# path('password_change/',PasswordChangeView.as_view(),name='password_change'),
# path('password_change/done/',PasswordChangeDoneView.as_view(),name='password_change_done'),
# reset password urls
# path('password_reset/',PasswordResetView.as_view(),name='password_reset'),
# path('password_reset/done/',PasswordResetDoneView.as_view(),name='password_reset_done'),
# path('reset/<uidb64>/<token>/',PasswordResetConfirmView.as_view(),name='password_reset_confirm'),
# path('reset/done/',PasswordResetCompleteView.as_view(),name='password_reset_complete'),
# above all path or url include it by default
path('', include('django.contrib.auth.urls')),
path('register/', register, name='register'),
path('edit/', edit, name='edit'),
path('', dashboard, name='dashboard'),
]
| from django.urls import path, include
from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView, PasswordChangeDoneView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView
from .views import user_login, dashboard, register, edit
urlpatterns = [
# path('login/', user_login, name='login')
# path('login/', LoginView.as_view(), name='login'),
# path('logout/', LogoutView.as_view(), name='logout'),
# change password urls
# path('password_change/',PasswordChangeView.as_view(),name='password_change'),
# path('password_change/done/',PasswordChangeDoneView.as_view(),name='password_change_done'),
# reset password urls
# path('password_reset/',PasswordResetView.as_view(),name='password_reset'),
# path('password_reset/done/',PasswordResetDoneView.as_view(),name='password_reset_done'),
# path('reset/<uidb64>/<token>/',PasswordResetConfirmView.as_view(),name='password_reset_confirm'),
# path('reset/done/',PasswordResetCompleteView.as_view(),name='password_reset_complete'),
# above all path or url include it by default
path('', include('django.contrib.auth.urls')),
path('register/', register, name='register'),
path('edit/', edit, name='edit'),
path('', dashboard, name='dashboard'),
] | en | 0.184897 | # path('login/', user_login, name='login') # path('login/', LoginView.as_view(), name='login'), # path('logout/', LogoutView.as_view(), name='logout'), # change password urls # path('password_change/',PasswordChangeView.as_view(),name='password_change'), # path('password_change/done/',PasswordChangeDoneView.as_view(),name='password_change_done'), # reset password urls # path('password_reset/',PasswordResetView.as_view(),name='password_reset'), # path('password_reset/done/',PasswordResetDoneView.as_view(),name='password_reset_done'), # path('reset/<uidb64>/<token>/',PasswordResetConfirmView.as_view(),name='password_reset_confirm'), # path('reset/done/',PasswordResetCompleteView.as_view(),name='password_reset_complete'), # above all path or url include it by default | 2.006099 | 2 |
extensions/ml_recommender/python/tests/test_user_to_items.py | woon5118/totara_ub | 0 | 6622347 | """
This file is part of Totara Enterprise Extensions.
Copyright (C) 2020 onwards Totara Learning Solutions LTD
Totara Enterprise Extensions is provided only to Totara
Learning Solutions LTD's customers and partners, pursuant to
the terms and conditions of a separate agreement with Totara
Learning Solutions LTD or its affiliate.
If you do not have an agreement with Totara Learning Solutions
LTD, you may not access, use, modify, or distribute this software.
Please contact [<EMAIL>] for more information.
@author <NAME> <<EMAIL>>
@package ml_recommender
"""
import unittest
from unittest.mock import patch, Mock
import numpy as np
from pandas import DataFrame
from tests.generate_data import GenerateData
from subroutines.data_loader import DataLoader
from subroutines.user_to_items import UserToItems
class TestUserToItems(unittest.TestCase):
"""
This class is set up to test units of the `UserToItems` class
"""
def setUp(self):
"""
Hook method for setting up the fixture before exercising it
"""
data_generator = GenerateData()
data_loader = DataLoader()
processed_data = data_loader.load_data(
interactions_df=data_generator.get_interactions(),
users_data=data_generator.get_users(),
items_data=data_generator.get_items()
)
self.model = Mock()
self.mock_predictions = np.random.rand(10)
self.model.predict.return_value = self.mock_predictions
self.user_to_items = UserToItems(
u_mapping=processed_data['mapping'][0],
i_mapping=processed_data['mapping'][2],
item_type_map=processed_data['item_type_map'],
item_features=processed_data['item_features'],
positive_inter_map=processed_data['positive_inter_map'],
model=self.model
)
@patch('subroutines.user_to_items.np.fromiter')
def test_fromiter_called_in_get_items(self, mock_fromiter):
"""
This method tests if the `__get_items` method of the `UserToItems` class calls the
`np.fromiter` function exactly once with the correct arguments
"""
test_uid = 5
__ = self.user_to_items._UserToItems__get_items(internal_uid=test_uid)
mock_fromiter.assert_called_once()
self.assertEqual(list(self.user_to_items.i_mapping.values()), list(mock_fromiter.call_args[0][0]))
self.assertDictEqual({'dtype': np.int32}, mock_fromiter.call_args[1])
def test_predict_called_in_get_items(self):
"""
This method tests if the `__get_items` method of the `UserToItems` class calls the `predict` method
on the LightFM model object exactly once with the correct arguments
"""
test_uid = 5
__ = self.user_to_items._UserToItems__get_items(internal_uid=test_uid)
self.model.predict.assert_called_once()
self.assertEqual(self.model.predict.call_args[1]['user_ids'], test_uid)
np.testing.assert_equal(
self.model.predict.call_args[1]['item_ids'],
np.fromiter(self.user_to_items.i_mapping.values(), dtype=np.int32)
)
self.assertEqual(self.model.predict.call_args[1]['item_features'], None)
self.assertEqual(self.model.predict.call_args[1]['num_threads'], self.user_to_items.num_threads)
def test_get_items_overall(self):
"""
This method tests if the `__get_items` method of the `UserToItems` class returns a list of items
as expected, i.e., after excluding the already seen items and ordered as per their ranking/score
for the given user
"""
test_uid = 5
computed_recommended_items = self.user_to_items._UserToItems__get_items(
internal_uid=test_uid,
reduction_percentage=0.3
)
sorted_ids = self.mock_predictions.argsort()[::-1]
sorted_items = [
(
self.user_to_items.i_mapping_rev[x],
self.mock_predictions[x],
self.user_to_items.item_type_map[self.user_to_items.i_mapping_rev[x]]
)
for x in sorted_ids
]
best_with_score = self.user_to_items._UserToItems__top_x_by_cat(sorted_items)
self.assertEqual(computed_recommended_items, best_with_score)
def test_all_items(self):
"""
This method tests if the `all_items` method of the `UserToItems` class returns a pandas` DataFrame object
with the correct shape
"""
computed_user_items = self.user_to_items.all_items()
self.assertIsInstance(computed_user_items, DataFrame)
self.assertEqual(computed_user_items.shape[1], 3)
| """
This file is part of Totara Enterprise Extensions.
Copyright (C) 2020 onwards Totara Learning Solutions LTD
Totara Enterprise Extensions is provided only to Totara
Learning Solutions LTD's customers and partners, pursuant to
the terms and conditions of a separate agreement with Totara
Learning Solutions LTD or its affiliate.
If you do not have an agreement with Totara Learning Solutions
LTD, you may not access, use, modify, or distribute this software.
Please contact [<EMAIL>] for more information.
@author <NAME> <<EMAIL>>
@package ml_recommender
"""
import unittest
from unittest.mock import patch, Mock
import numpy as np
from pandas import DataFrame
from tests.generate_data import GenerateData
from subroutines.data_loader import DataLoader
from subroutines.user_to_items import UserToItems
class TestUserToItems(unittest.TestCase):
"""
This class is set up to test units of the `UserToItems` class
"""
def setUp(self):
"""
Hook method for setting up the fixture before exercising it
"""
data_generator = GenerateData()
data_loader = DataLoader()
processed_data = data_loader.load_data(
interactions_df=data_generator.get_interactions(),
users_data=data_generator.get_users(),
items_data=data_generator.get_items()
)
self.model = Mock()
self.mock_predictions = np.random.rand(10)
self.model.predict.return_value = self.mock_predictions
self.user_to_items = UserToItems(
u_mapping=processed_data['mapping'][0],
i_mapping=processed_data['mapping'][2],
item_type_map=processed_data['item_type_map'],
item_features=processed_data['item_features'],
positive_inter_map=processed_data['positive_inter_map'],
model=self.model
)
@patch('subroutines.user_to_items.np.fromiter')
def test_fromiter_called_in_get_items(self, mock_fromiter):
"""
This method tests if the `__get_items` method of the `UserToItems` class calls the
`np.fromiter` function exactly once with the correct arguments
"""
test_uid = 5
__ = self.user_to_items._UserToItems__get_items(internal_uid=test_uid)
mock_fromiter.assert_called_once()
self.assertEqual(list(self.user_to_items.i_mapping.values()), list(mock_fromiter.call_args[0][0]))
self.assertDictEqual({'dtype': np.int32}, mock_fromiter.call_args[1])
def test_predict_called_in_get_items(self):
"""
This method tests if the `__get_items` method of the `UserToItems` class calls the `predict` method
on the LightFM model object exactly once with the correct arguments
"""
test_uid = 5
__ = self.user_to_items._UserToItems__get_items(internal_uid=test_uid)
self.model.predict.assert_called_once()
self.assertEqual(self.model.predict.call_args[1]['user_ids'], test_uid)
np.testing.assert_equal(
self.model.predict.call_args[1]['item_ids'],
np.fromiter(self.user_to_items.i_mapping.values(), dtype=np.int32)
)
self.assertEqual(self.model.predict.call_args[1]['item_features'], None)
self.assertEqual(self.model.predict.call_args[1]['num_threads'], self.user_to_items.num_threads)
def test_get_items_overall(self):
"""
This method tests if the `__get_items` method of the `UserToItems` class returns a list of items
as expected, i.e., after excluding the already seen items and ordered as per their ranking/score
for the given user
"""
test_uid = 5
computed_recommended_items = self.user_to_items._UserToItems__get_items(
internal_uid=test_uid,
reduction_percentage=0.3
)
sorted_ids = self.mock_predictions.argsort()[::-1]
sorted_items = [
(
self.user_to_items.i_mapping_rev[x],
self.mock_predictions[x],
self.user_to_items.item_type_map[self.user_to_items.i_mapping_rev[x]]
)
for x in sorted_ids
]
best_with_score = self.user_to_items._UserToItems__top_x_by_cat(sorted_items)
self.assertEqual(computed_recommended_items, best_with_score)
def test_all_items(self):
"""
This method tests if the `all_items` method of the `UserToItems` class returns a pandas` DataFrame object
with the correct shape
"""
computed_user_items = self.user_to_items.all_items()
self.assertIsInstance(computed_user_items, DataFrame)
self.assertEqual(computed_user_items.shape[1], 3)
| en | 0.805776 | This file is part of Totara Enterprise Extensions. Copyright (C) 2020 onwards Totara Learning Solutions LTD Totara Enterprise Extensions is provided only to Totara Learning Solutions LTD's customers and partners, pursuant to the terms and conditions of a separate agreement with Totara Learning Solutions LTD or its affiliate. If you do not have an agreement with Totara Learning Solutions LTD, you may not access, use, modify, or distribute this software. Please contact [<EMAIL>] for more information. @author <NAME> <<EMAIL>> @package ml_recommender This class is set up to test units of the `UserToItems` class Hook method for setting up the fixture before exercising it This method tests if the `__get_items` method of the `UserToItems` class calls the `np.fromiter` function exactly once with the correct arguments This method tests if the `__get_items` method of the `UserToItems` class calls the `predict` method on the LightFM model object exactly once with the correct arguments This method tests if the `__get_items` method of the `UserToItems` class returns a list of items as expected, i.e., after excluding the already seen items and ordered as per their ranking/score for the given user This method tests if the `all_items` method of the `UserToItems` class returns a pandas` DataFrame object with the correct shape | 2.026225 | 2 |
crawler/GithubDemoCrawler/GithubDemoCrawler/spiders/GithubDemoSpider.py | kingking888/SearchEngine | 6 | 6622348 | import scrapy
import json
import os
from scrapy import signals
from scrapy.http import Request
from scrapy.xlib.pydispatch import dispatcher
from CrawlerUtils.Catalog import DocCatalog
from ..driver import github_driver
from ..items import GithubdemocrawlerItem
from lxml import etree
class GithubDemoSpider(scrapy.Spider):
name = 'github-spider'
start_url = 'https://github.com/search?p=%d&q=%s&type=Repositories'
host = 'https://github.com'
keywords_map = {}
def __init__(self):
super(GithubDemoSpider, self).__init__()
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config.json')
with open(config_path, 'r') as cursor:
self.CONFIG = json.load(cursor)
for keyword in self.CONFIG['keywords']:
self.keywords_map[keyword] = False
dispatcher.connect(self.SpiderStopped, signals.engine_stopped)
def SpiderStopped(self):
for driver in github_driver.driver_pools:
driver.close()
def start_requests(self):
for keyword in self.CONFIG['keywords']:
url = self.start_url % (1, keyword)
yield Request(url=url, callback=self.parse_page, meta={
'key' : 'page',
'keyword' : keyword
})
def parse_page(self, response):
content = response.text
selector = etree.HTML(content)
repo_list_tags = selector.xpath('//li[contains(@class, "repo-list-item")]/div[1]')
for repo in repo_list_tags:
a_tag = repo.find('./h3/a[1]')
link = self.host + a_tag.get('href')
yield Request(url=link, callback=self.parse_content, meta={
'key' : 'content',
'keyword' : response.meta['keyword'],
})
# crawl pages
if self.keywords_map[response.meta['keyword']] == False:
# last_page = selector.xpath('//em[@class="current"]')
# total_page = int(last_page[0].get('data-total-pages'))
for page in range(2, 20):
yield Request(url=self.start_url % (page, response.meta['keyword']), callback=self.parse_page, meta={
'key' : 'page',
'keyword' : response.meta['keyword']
})
self.keywords_map[response.meta['keyword']] = True
def parse_content(self, response):
content = response.text
selector = etree.HTML(content)
try:
summary_tag = selector.xpath('//span[@class="text-gray-dark mr-2"]')[0]
summary = ' '.join(summary_tag.text.strip('\n').split())
date_tag = selector.xpath('//relative-time')[0]
date = date_tag.text
url = response.url
url_text = url.split('/')
author = url_text[-2]
title = url_text[-1]
document = GithubdemocrawlerItem()
document['title'] = title
document['summary'] = summary
document['url'] = url
document['tags'] = [response.meta['keyword']]
document['catalog'] = DocCatalog.CATALOG_DEMO
document['content'] = summary
document['source'] = self.CONFIG['source'],
document['author'] = author
document['date'] = date
yield document
except Exception as e:
pass
| import scrapy
import json
import os
from scrapy import signals
from scrapy.http import Request
from scrapy.xlib.pydispatch import dispatcher
from CrawlerUtils.Catalog import DocCatalog
from ..driver import github_driver
from ..items import GithubdemocrawlerItem
from lxml import etree
class GithubDemoSpider(scrapy.Spider):
name = 'github-spider'
start_url = 'https://github.com/search?p=%d&q=%s&type=Repositories'
host = 'https://github.com'
keywords_map = {}
def __init__(self):
super(GithubDemoSpider, self).__init__()
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config.json')
with open(config_path, 'r') as cursor:
self.CONFIG = json.load(cursor)
for keyword in self.CONFIG['keywords']:
self.keywords_map[keyword] = False
dispatcher.connect(self.SpiderStopped, signals.engine_stopped)
def SpiderStopped(self):
for driver in github_driver.driver_pools:
driver.close()
def start_requests(self):
for keyword in self.CONFIG['keywords']:
url = self.start_url % (1, keyword)
yield Request(url=url, callback=self.parse_page, meta={
'key' : 'page',
'keyword' : keyword
})
def parse_page(self, response):
content = response.text
selector = etree.HTML(content)
repo_list_tags = selector.xpath('//li[contains(@class, "repo-list-item")]/div[1]')
for repo in repo_list_tags:
a_tag = repo.find('./h3/a[1]')
link = self.host + a_tag.get('href')
yield Request(url=link, callback=self.parse_content, meta={
'key' : 'content',
'keyword' : response.meta['keyword'],
})
# crawl pages
if self.keywords_map[response.meta['keyword']] == False:
# last_page = selector.xpath('//em[@class="current"]')
# total_page = int(last_page[0].get('data-total-pages'))
for page in range(2, 20):
yield Request(url=self.start_url % (page, response.meta['keyword']), callback=self.parse_page, meta={
'key' : 'page',
'keyword' : response.meta['keyword']
})
self.keywords_map[response.meta['keyword']] = True
def parse_content(self, response):
content = response.text
selector = etree.HTML(content)
try:
summary_tag = selector.xpath('//span[@class="text-gray-dark mr-2"]')[0]
summary = ' '.join(summary_tag.text.strip('\n').split())
date_tag = selector.xpath('//relative-time')[0]
date = date_tag.text
url = response.url
url_text = url.split('/')
author = url_text[-2]
title = url_text[-1]
document = GithubdemocrawlerItem()
document['title'] = title
document['summary'] = summary
document['url'] = url
document['tags'] = [response.meta['keyword']]
document['catalog'] = DocCatalog.CATALOG_DEMO
document['content'] = summary
document['source'] = self.CONFIG['source'],
document['author'] = author
document['date'] = date
yield document
except Exception as e:
pass
| en | 0.426701 | # crawl pages # last_page = selector.xpath('//em[@class="current"]') # total_page = int(last_page[0].get('data-total-pages')) | 2.427946 | 2 |
ServerApp.py | MattBcool/NLPTalk | 1 | 6622349 | <reponame>MattBcool/NLPTalk
import time
from models.GPT3 import GPT3
from server.ServerSocket import ServerSocket
from utils import DataCleanser as dc
def ServerApp():
while True:
try:
ss = ServerSocket(4824)
ss.listen()
except Exception as e:
print('\nWaiting 30 seconds for port to open...\n')
time.sleep(30)
# Press the green button to run the script
if __name__ == '__main__':
ServerApp()
| import time
from models.GPT3 import GPT3
from server.ServerSocket import ServerSocket
from utils import DataCleanser as dc
def ServerApp():
while True:
try:
ss = ServerSocket(4824)
ss.listen()
except Exception as e:
print('\nWaiting 30 seconds for port to open...\n')
time.sleep(30)
# Press the green button to run the script
if __name__ == '__main__':
ServerApp() | en | 0.664301 | # Press the green button to run the script | 2.461442 | 2 |
tackle/providers/pyinquirer/hooks/rawlist.py | geometry-labs/tackle-box | 1 | 6622350 | <reponame>geometry-labs/tackle-box
"""Raw list hook."""
from PyInquirer import prompt
from pydantic import Field
from typing import Any
from tackle.models import BaseHook
from tackle.utils.dicts import get_readable_key_path
class InquirerRawListHook(BaseHook):
"""
Hook for PyInquirer 'rawlist' type prompts.
Example: https://github.com/CITGuru/PyInquirer/blob/master/examples/rawlist.py
:param message: String message to show when prompting.
:param choices: A list of strings or list of k/v pairs per above description
:param name: A key to insert the output value to. If not provided defaults to
inserting into parent key
:return: String for the answer
"""
hook_type: str = 'rawlist'
default: Any = Field(None, description="Default choice.")
message: str = Field(None, description="String message to show when prompting.")
name: str = Field('tmp', description="Extra key to embed into. Artifact of API.")
_args: list = ['message', 'default']
def __init__(self, **data: Any):
super().__init__(**data)
if self.message is None:
self.message = get_readable_key_path(self.key_path_) + ' >>>'
def execute(self):
if not self.no_input:
question = {
'type': self.type,
'name': self.name,
'message': self.message,
'choices': self.choices,
}
if self.default:
question.update({'default': self.default})
response = prompt([question])
if self.name != 'tmp':
return response
else:
return response['tmp']
elif self.default:
return self.default
else:
# When no_input then return empty list
return []
| """Raw list hook."""
from PyInquirer import prompt
from pydantic import Field
from typing import Any
from tackle.models import BaseHook
from tackle.utils.dicts import get_readable_key_path
class InquirerRawListHook(BaseHook):
"""
Hook for PyInquirer 'rawlist' type prompts.
Example: https://github.com/CITGuru/PyInquirer/blob/master/examples/rawlist.py
:param message: String message to show when prompting.
:param choices: A list of strings or list of k/v pairs per above description
:param name: A key to insert the output value to. If not provided defaults to
inserting into parent key
:return: String for the answer
"""
hook_type: str = 'rawlist'
default: Any = Field(None, description="Default choice.")
message: str = Field(None, description="String message to show when prompting.")
name: str = Field('tmp', description="Extra key to embed into. Artifact of API.")
_args: list = ['message', 'default']
def __init__(self, **data: Any):
super().__init__(**data)
if self.message is None:
self.message = get_readable_key_path(self.key_path_) + ' >>>'
def execute(self):
if not self.no_input:
question = {
'type': self.type,
'name': self.name,
'message': self.message,
'choices': self.choices,
}
if self.default:
question.update({'default': self.default})
response = prompt([question])
if self.name != 'tmp':
return response
else:
return response['tmp']
elif self.default:
return self.default
else:
# When no_input then return empty list
return [] | en | 0.455563 | Raw list hook. Hook for PyInquirer 'rawlist' type prompts. Example: https://github.com/CITGuru/PyInquirer/blob/master/examples/rawlist.py :param message: String message to show when prompting. :param choices: A list of strings or list of k/v pairs per above description :param name: A key to insert the output value to. If not provided defaults to inserting into parent key :return: String for the answer # When no_input then return empty list | 2.726957 | 3 |