def set_detector_rz_collection(self, list_of_detids): # Create detector patches self.patches_rz = [] n_failed = 0 for detid in list_of_detids: module = Module(detid) partner_detid = Module(detid).partnerDetId() if partner_detid not in self.det_geom.getData().keys(): # print("{} not found from {} (isLower = {}, isInverted = {})".format(partner_detid, detid, module.isLower(), module.isInverted())) n_failed += 1 continue else: # print("{} found from {} (isLower = {}, isInverted = {})".format(partner_detid, detid, module.isLower(), module.isInverted())) pass six_faces = self.get_six_faces( self.det_geom.getData()[detid], self.det_geom.getData()[partner_detid]) for face in six_faces: points = [[x[0], math.sqrt(x[1]**2 + x[2]**2)] for x in face] polygon = Polygon(np.array(points), True) self.patches_rz.append(polygon)
def LmodModuleList(paths): import string moduleList = [] output = pexpect.run(MODULE_COMMAND + ' ' + string.join(paths, ':')) import json output_js = json.loads(output) if "jsonSoftwarePage" in MODULE_COMMAND: for elem in output_js: for v in elem["versions"]: name = v["full"] help = "-" prereq = "-" if v.has_key("help"): help = v["help"] if v.has_key("parent"): prereq = string.join(v["parent"], " or ").replace( "default:", "").replace("default", "").replace(":", " and ") newModule = Module(name, help, "-", prereq) if newModule.version[0] != ".": moduleList.append(newModule) elif "spider-json" in MODULE_COMMAND: # print(str(output_js)) for module_name in output_js: data = output_js[module_name] for path in data: module_data = data[path] # print(str(module_data)) if module_data.has_key("fullName"): name = module_data["fullName"] help = "-" prereq = "-" if module_data.has_key("Description"): help = module_data["Description"] if module_data.has_key("parentAA"): prereq = string.join(module_data["parentAA"][0], " and ") newModule = Module(name, help, "-", prereq) if newModule.version[0] != ".": found = False for n, m in enumerate(moduleList): if m.name == newModule.name: newModule = Module(name, help, "-", m.prereq + " or " + prereq) moduleList[n] = newModule found = True break if not found: moduleList.append(newModule) return moduleList
def main(): ## create patient schedule patientList = [] personA = Person('A', 0) patientList.append(personA) personB = Person('B', 4) patientList.append(personB) personC = Person('C', 10) patientList.append(personC) ## module schedule (from a file) moduleList = [] module1 = Module(0, 2) moduleList.append(module1) module2 = Module(1, 3) moduleList.append(module2) moduleCount = len(moduleList) ## need a nursing scheduler as nurses could be different than modules. ## intialize simulation parameters counter = 0 completed = 0 ## simulation loop while completed < len(patientList): print('Time Step: {0}'.format(counter)) for mod in moduleList: for pat in patientList: if pat.location == mod.location and pat.serviceTime > 0: mod.serve(pat) break if pat.location == mod.location and pat.serviceTime == -1: # This should be a method in the module class. print('Location {0} now serving Patient {1}'.format( mod.location, pat.name)) pat.serviceTime = mod.completionTime break completed = 0 # condition to check if all patients have completed the clinic (Can we close?) for pat in patientList: if pat.location == moduleCount: completed += 1 counter += 1
def get_modules(session): print("Getting modules...\n") modules = [] resp = session_get('{0}/courses/{1}/modules'.format(CANVAS_URL, COURSE_ID), session) tree = html.fromstring(resp.content) moduleNodes = tree.xpath( "//div[contains(@class, 'context_module') and contains(@class, 'item-group-condensed')]" ) # Last element is a blank module moduleNodes.pop() for moduleNode in moduleNodes: module = Module() module.name = moduleNode.attrib['aria-label'] print("Found Module ", module.name) module.items = get_items(moduleNode) modules.append(module) print("") return modules
def set_detector_etaphi_collection(self, list_of_detids): # Create detector patches self.patches_etaphi = [] n_failed = 0 for detid in list_of_detids: module = Module(detid) bound_points = self.det_geom.getData()[detid] points = [] for bp in bound_points: x = bp[1] y = bp[2] z = bp[ 0] # The index is weird because that's how it is saved in det_geom phi = math.atan2(y, x) print(x, y, phi) # print(x, y, z) eta = math.copysign( -math.log( math.tan( math.atan(math.sqrt(y**2 + x**2) / abs(z)) / 2.)), z) points.append([eta, phi]) polygon = Polygon(np.array(points), True) self.patches_etaphi.append(polygon)
def git_init(repo): os.mkdir(repo) tmp = Module(repo, True) os.chdir(tmp.url) os.system('git init') os.chdir(work_path) return tmp
def __init__(self): rooms = [["GD923", 60], ["GD924", 60], ["GD926", 60], ["GD929", 60], ["GD933", 60]] meeting_times = [["1. Block", "08:00 – 09:50"], ["2. Block", "10:00 – 11:50"], ["3. Block", "13:00 – 14:50"], ["4. Block", "15:00 – 16:50"]] dosens = [ ["HTS", "Humasak Simanjuntak"], ["SGS", "Samuel Situmeang"], ["JUN", "Junita Amalia"], ["MSS", "Mario Simaremare"], ["THS", "Tennov Simanjuntak"], ["DWS", "Devis Wawan Saputra"], ["BLT", "Bonar Lumban Tobing"], ["IUS", "Iustisia Simbolon"], ["PAT", "Parmonangan Togatorop"], ] self._rooms = [] self._meeting_times = [] self._dosens = [] self.fill_objects(rooms, meeting_times, dosens) module1 = Module("BASDATLAN", "Advanced Database", [self.get_dosen("HTS")]) module2 = Module("CERTAN", "Artificial Intelligence", [self.get_dosen("SGS")]) module3 = Module("PROBSTAT", "Probability and Statistics", [self.get_dosen("JUN"), self.get_dosen("THS")]) module4 = Module("PPW", "Web Application Programming and Testing", [self.get_dosen("MSS")]) module5 = Module("ALSTRUDAT", "Algorithms and Data Structures", [ self.get_dosen("THS"), self.get_dosen("HTS"), self.get_dosen("PAT"), self.get_dosen("SGS") ]) module6 = Module("TEKNO", "Technopreneurship", [self.get_dosen("DWS")]) module7 = Module("ATI", "Religion and Ethics", [self.get_dosen("BLT")]) module8 = Module("RPL", "Software Engineering", [self.get_dosen("IUS")]) module9 = Module("MPSI", "Information System Project Management", [self.get_dosen("PAT")]) self._modules = [module1, module2, module3, module4, module5, module6] course1 = Course("11SI", [module1, module3, module4, module7], 59) course2 = Course("12SI", [module2, module4, module5, module8], 50) course3 = Course("13SI", [module4, module5, module6, module9], 56) course4 = Course("14SI", [module5, module3, module1, module9], 48) self._courses = [course1, course2, course3, course4]
def get_module_objects(self): module_objs = [ Module(module, self.configs, self.verbosity) for module in self.module_path_list ] if len(module_objs) > 1 and self.verbosity > 1: print("[" + str(len(module_objs)) + "]") return module_objs
def exec(self, args, **kwargs): parse_args = Command.Command.PARSER.parse_args(args) module = Module(parse_args.command, parse_args.interval, parse_args.signal, parse_args.align, parse_args.order) modules.append(module) module.exec(shell) epoll.register(module) return b'Ok'
def printPixelMap_v1(): import os dirpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) det_geom = DetectorGeometry( "/data2/segmentlinking/phase2_2020_0428.txt".format(dirpath)) super_bins = {} neta = 40. nphi = 72. isuper_bin = 0 pt_bounds = [0.9, 2.0, 4.0, 10., 50.] # pt_bounds = [0.9, 2.0] for ipt in xrange(len(pt_bounds) - 1): pt_lo = pt_bounds[ipt] pt_hi = pt_bounds[ipt + 1] for ieta in xrange(int(neta)): eta_lo = -2.6 + (5.2 / neta) * ieta eta_hi = -2.6 + (5.2 / neta) * (ieta + 1) for iphi in xrange(int(nphi)): phi_lo = -math.pi + (2 * math.pi / nphi) * iphi phi_hi = -math.pi + (2 * math.pi / nphi) * (iphi + 1) super_bins[isuper_bin] = (pt_lo, pt_hi, eta_lo, eta_hi, phi_lo, phi_hi) isuper_bin += 1 print(len(super_bins)) maps = {} for layer in [1, 2, 3, 4, 5, 6]: for subdet in [4, 5]: for isuper_bin in super_bins.keys(): bounds = super_bins[isuper_bin] maps[isuper_bin] = [] for detid in det_geom.getDetIds(): if Module(detid).layer() == layer and Module( detid).isLower() == 1 and Module(detid).moduleType( ) == 0 and Module(detid).subdet() == subdet: if det_geom.isConnected(detid, bounds[2], bounds[3], bounds[4], bounds[5], bounds[0], bounds[1], -30, 30): maps[isuper_bin].append(detid) print(isuper_bin, layer, subdet, bounds[2], bounds[3], bounds[4], bounds[5], maps[isuper_bin])
def getModules(self, elements, libraryDict, converter): for element in elements: elementPackage = element.get("package") elementLib = element.get("library") libNode = libraryDict.get(elementLib).get(elementPackage) modContacts = self.contacts.get(element.get("name")) module = Module(libNode, converter, element, modContacts) self.elements.append(module)
def addModule(self, inputData, register, output): """Add a module to the module list Parameters: input - (DataContainer) input variables and results from preparatory modules register - (DataContainer) registry data of this module output - (DataContainer) with output requirements for this module """ module = Module(inputData, register, output) self.moduleList.append(module, ) return
def refreshCallback(self, data): remote_modules = data['modules'] self._repo_state = data['repostate'] modulenames = [m.getModuleName() for m in self.children] for module in remote_modules: if module['name'] not in modulenames: self.addChild(Module(self, module)) else: self.getModuleByName(module['name']).refresh(module) result_modulenames = [m['name'] for m in remote_modules] for module in self.children: if module.getModuleName() not in result_modulenames: self.removeChild(module) self.updated() self.getApplication().getObjectStore().updated()
def pass_up(self, data: NetworkDataPoint): print("Received data from %d:" % data.address, data.value) new_mod = False if data.address not in self.modules: print("New module! address =", data.address) self.modules[data.address] = Module(self, data.address) new_mod = True idd = data.value[0] val = data.value[1:] self.modules[data.address].pass_up(DataPoint(idd, val)) if new_mod: self.modules[data.address].subscribe()
def __init__(self, object_filename): self.modules = dict() self.courses = dict() with open(object_filename, 'rt') as fp: cDin = csv.DictReader(fp) objs = [row for row in cDin] for obj in objs: new_m = Module(obj) if not obj['course_id'] in self.courses: self.courses[obj['course_id']] = Course(obj['course_id']) self.modules[obj['module_id']] = new_m self.courses[obj['course_id']].addModule(new_m) for module in self.modules.values(): module.BuildChildrenRef(self.modules)
def __loadModules(self, con, cur): """Get modules list from database.""" # Fetches modules (list of tuples) with con: cur.execute(""" SELECT modID, macAddr, ipAddr, posX, posY, nFans, nLayers, pwm, rpm, isConnected, isFlashing, isPowered, lifePoints, isRebooting, isSendingRPM FROM modules """) modules = cur.fetchall() # Stores modules for module in modules: modID = module[0] self.__modules[modID] = Module(module)
def buildByLayer(self): self.barrel_lower_det_ids = [] print("Building barrel detIds") for i in tqdm(range(1, 7)): self.barrel_lower_det_ids.append( self.getDetIds(lambda x: Module(x[0]).subdet() == 5 and Module( x[0]).layer() == i and Module(x[0]).isLower() == 1)) self.endcap_lower_det_ids = [] print("Building endcap detIds") for i in tqdm(range(1, 6)): self.endcap_lower_det_ids.append( self.getDetIds(lambda x: Module(x[0]).subdet() == 4 and Module( x[0]).layer() == i and Module(x[0]).isLower() == 1))
def __init__(self, oldFolder: str): # Установка параметров обфускации self.params: ObfuscationParams = ObfuscationParams() # Старая и новые папки проекта self.oldFolder: str = oldFolder path, filename = list(os.path.split(oldFolder)) self.newFolder: str = os.path.join(path, self.prefix + filename) # Сохранение в self.files путей к файлам, которые надо обфусцировать # Остальные копируются в новую папку проекта self.files: List[str] = self.find_and_copy_files() self.module_queue: List[Module] = [Module(file) for file in self.files] # Создание словаря обфусцированных имён self.name_generator: NameGenerator = NameGenerator() # Инициализация графа замисимостей импортов. Ключ - модуль, значение - список импортированных модулей self.dependency_graph: Dict[Module, List[Module]] = dict()
def run(path: str, binds: Dict[int, str]): if path == 'FULL': for key in binds: command = binds[key] if command != 'FULL': run(command, binds) return if os.path.isfile(path): module = Module(path) module.collect_data() module.obfuscate() # print(module.tree) module.save() else: project = Project(path) project.simple_obfuscation()
def extract(fileName, modules, nodes): f = open(fileName, "r") for i in f: input_nodes = [] lower_case = i.lower() if "inv" in lower_case or "and" in lower_case or "or" in lower_case: t, name, inputs, output = parser(i) if output not in nodes: nodes[output] = Node(output) for i in inputs: if i not in nodes: nodes[i] = Node(i) input_nodes.append(nodes[i]) output_node = nodes[output] modules.append(Module(t, name, input_nodes, output_node))
def ModuleList(paths): moduleList = [] for path in paths: os.putenv('MODULEPATH', path) output = pexpect.run(MODULE_COMMAND + ' avail') splittedOutput = re.split('-* ' + path + ' -*', output) if len(splittedOutput) != 2: continue modules = splittedOutput[1].split() for module in modules: show = pexpect.run(MODULE_COMMAND + ' show ' + module.replace("(default)", "")) help = pexpect.run(MODULE_COMMAND + ' help ' + module.replace("(default)", "")) newModule = Module(module, help, show) moduleList.append(newModule) return moduleList
def __init__(self): super(mywindow, self).__init__() self.setupUi(self) # Start the server-handler thread. Connect a pyqtSignal to # the send_command slot self._server_handler = ServerIO(ui_config['host'], ui_config['input_port'], ui_config['output_port'], ui_config['header_length'], commands) self._server_handler.start() self.send_command.connect(self._server_handler.send_command) # Start a timer, provided to controls objects so they # can check for stale values self.timer_1000 = QtCore.QTimer() self.timer_1000.start(1000) self.Module1 = Module(5, 5, 100, self.pushButton, self.checkbox, self.graphicsView, self.graphicsView_2, self.graphicsView_3) # Tell the server to start sending updates self.send_command.emit('connect_devices') self.send_command.emit('set_alerts') self.send_command.emit('set_monitoring') self.fan = FanControls(self.pushButton_2, self.pushButton_3, self.lineEdit_3, self.lineEdit_4, self.fanAlertLineEdit, self._server_handler.on_update, self.timer_1000.timeout, self.send_command) self.power = PowerControls(self.pushButton_4, self.pushButton_5, self.lineEdit_5, self.lineEdit_6, self._server_handler.on_update, self.send_command)
def __init__(self): rooms = [["2.56CR", 40], ["2.18", 40], ["2.20", 55]] meeting_times = [["1. Block", "09:50 – 11:20"], ["2. Block", "11:30 – 13:00"], ["3. Block", "13:45 – 15:15"], ["4. Block", "15:30 – 17:00"]] docents = [["HOZ", "Holzheuer, Heiko"], ["EWE", "Ewering, Christian"], ["NUW", "Nüßer, Wilhelm"], ["JAA", "Jäsche, Andreas"], ["JAP", "Janacik, Peter"], ["PAD", "Padberg, Carsten"]] self._rooms = [] self._meeting_times = [] self._docents = [] self.fill_objects(rooms, meeting_times, docents) module1 = Module("ISM", "IT-Strategie und -management", [self.get_docent("HOZ")]) module2 = Module("OR", "Operations Research - Methoden und Anwendungen", [self.get_docent("EWE")]) module3 = Module("TT", "Technologie-Trends", [self.get_docent("NUW"), self.get_docent("HOZ")]) module4 = Module("SIC", "Strategieimplementierung und Changemanagement", [self.get_docent("JAA")]) module5 = Module("CM", "Complexity Management", [self.get_docent("JAP")]) module6 = Module("MIC", "Methoden und Instrumente des Controlling", [self.get_docent("PAD")]) self._modules = [module1, module2, module3, module4, module5, module6] course1 = Course("PFMI419A", [module1, module3, module4], 20) course2 = Course("PFMV419A", [module2, module4, module5], 20) course3 = Course("PFMF419A", [module4, module5, module6], 50) self._courses = [course1, course2, course3]
from Module import Module import codecs import base64 import string import random modules = [] def to_rot_13(flag): return codecs.encode(flag, "rot_13") modules.append(Module("Encode Flag using ROT-13", to_rot_13, [])) def from_rot_13(flag): return codecs.decode(flag, "rot_13") modules.append(Module("Decode Flag using ROT-13", from_rot_13, [])) def to_base64(flag): return base64.b64encode(flag.encode()) def from_base64(flag): return base64.b64decode(flag.encode())
def add_password(zip, passwd): zipfile = ZipFile(zip, "a") zipfile.setpassword(passwd) zipfile.close() return zip def add_password_flag(flag, zip): return add_password(zip[0], flag) def add_password_gen(zip, text): return add_password(zip, text[0]) modules.append(Module("Add Generated File to new Zip Archive", zip_files, [])) modules.append( Module("Add Generated File to existing Zip Archive", zip_files_existing, [ "Absolute Path to Zip Archive (Required)", "Password (leave blank if none)" ])) modules.append( Module("Add flag as comment to existing zip archive", add_comment_flag, ["Absolute Path to Zip Archive (Required)"])) modules.append( Module("Add comment to generated zip archive", add_comment_generated, ["Comment (cannot excede 65535 bytes, required)"])) modules.append( Module("Add flag as password to existing zip archive", add_password_gen, ["Absolute Path to Zip Archive (Required)"])) modules.append(
except Exception as e: print(e) exit(1) return image def hide_text_in_exif(image, options): text = options[0] im = get_image(image) path = tempfile.mkstemp()[1] + ".jpg" im.save(path, exif=piexif.dump( {"0th": { piexif.ImageIFD.Make: text.encode('utf-8') }})) im.close() return path def hide_in_exif(flag, options): image = options[0] return hide_text_in_exif(image, flag) modules.append( Module("Hide Flag in Image EXIF data", hide_in_exif, ["Absolute Path to Image (Required)"])) modules.append( Module("Hide Text in Already Generated Image EXIF data", hide_text_in_exif, ["Text (Required)"]))
import glob import shutil import datetime import time from Dir import Dir from Module import Module from filecmp import dircmp from shell import remove from shell import move_file from sv_protect import sv_protect work_path = os.getcwd() names = locals() for i in glob.module_list: names[i] = Module(i) glob.module_wkspc.append(names[i]) #after merge where to checkout the dirs and files def checkout(dir, l): for i in dir.files.values(): if len(i.editor) == 0: l.get('root').append(i.path) elif len(i.editor) == 1: l.get(list(i.editor)[0]).append(i.path) for i in dir.subdirs.values(): if len(i.editor) == 0: l.get('root').append(i.path) elif len(i.editor) == 1: l.get(list(i.editor)[0]).append(i.path) else:
from FeatureVectorGen import PrintMetrics from sklearn.linear_model import LogisticRegression from sklearn import metrics from Module import Module objectsFile = '../data/object/object.csv' date_file = '../data/object/date.csv' print "Reading obects from "+ objectsFile with open(objectsFile) as openfileobject: openfileobject.next() objects = [Module(line) for line in openfileobject] object_map = dict([(obj.module_id, obj) for obj in objects]) detached_objects = 0 for obj in objects: valid_children = [] for child in obj.children: if (child in object_map): child_node = object_map[child] child_node.parent = obj obj.children_nodes.append(child_node) valid_children.append(child) else: detached_objects += 1
def string_to_hex(flag): return str(binascii.b2a_hex(flag.encode()).decode()) def binary_to_ascii(flag): return str(binascii.b2a_uu(flag.encode()).decode()) def hexbin4_binary_to_ascii(flag): return str(binascii.b2a_hqx(flag.encode()).decode()) def string_to_decimal(flag): return str(int.from_bytes(flag.encode(), 'big')) def string_to_binary(flag): return str(bin(int.from_bytes(flag.encode(), 'big'))).replace('b', '') modules.append(Module("Convert Flag to Binary", string_to_binary, [])) modules.append(Module("Convert Flag to Decimal", string_to_decimal, [])) modules.append(Module("Convert Flag to Hex", string_to_hex, [])) modules.append( Module("Treat Flag as Binary and Convert to Ascii", binary_to_ascii, [])) modules.append( Module( "Treat Flag as Binary and Perform hexbin4 binary-to-ascii translation", hexbin4_binary_to_ascii, []))
def test_total_fuel1(module, expected): assert (Module(module).fuel() == expected)