def test_file_by_name(self): fh = _get_format(self.FMT) obj = dict(answer=42) filename1 = 'tmp.' + fh.extension dump(obj, filename1) try: obj1 = load(filename1) self.assertEqual(obj, obj1) finally: os.remove(filename1) filename2 = 'tmp.' + fh.extension + '.bla' dump(obj, filename2, fmt=self.FMT) try: obj2 = load(filename2, fmt=self.FMT) self.assertEqual(obj, obj2) finally: os.remove(filename2) filename3 = Path("tmp." + fh.extension) dump(obj, filename3) try: obj1 = load(filename3) self.assertEqual(obj, obj1) finally: filename3.unlink()
def load(inf, spacing = None, optics = None): """ Load data or results Parameters ---------- inf : single or list of basestring or files File to load. If the file is a yaml file, all other arguments are ignored. If inf is a list of image files or filenames they are all loaded as a a timeseries hologram optics : :class:`holopy.optics.Optics` object or string (optional) Optical train parameters. If string, specifies the filename of an optics yaml bg : string (optional) name of background file bg_type : string (optional) set to 'subtract' or 'divide' to specify how background is removed channel : int (optional) number of channel to load for a color image (in general 0=red, 1=green, 2=blue) time_scale : float or list (optional) time between frames or, if list, time at each frame Returns ------- obj : The object loaded, :class:`holopy.core.marray.Image`, or as loaded from yaml """ if isinstance(optics, (basestring, file)): optics = serialize.load(optics) # In the past We allowed optics yamls to be written without an !Optics # tag, so for that backwards compatability, we attempt to turn an # anonymous dict into an Optics if isinstance(optics, dict): optics = Optics(**optics) loaded_yaml = False try: loaded = serialize.load(inf) loaded_yaml = True except serialize.ReaderError: pass if not loaded_yaml: loaded = load_image(inf, spacing=spacing, optics=optics) elif optics is not None and spacing is not None: loaded = arr_like(loaded, spacing = spacing, optics = optics) warn("Overriding spacing and optics of loaded yaml") elif optics is not None: loaded = arr_like(loaded, optics = optics) warn("WARNING: overriding optics of loaded yaml without overriding " "spacing, this is probably incorrect.") elif spacing is not None: loaded = arr_like(loaded, spacing = spacing) warn("WARNING: overriding spacing of loaded yaml without overriding " "optics, this is probably incorrect.") return loaded
def menu(self): while True: point = self.view if point == 1: self._calculate() elif point == 2: serialize.load() elif point == 3: data = self.view.change_serialization_file() serialize.change_config(data[0], data[1]) elif point == 4: break
def test_json(self): """ test for serialization with json """ output = srz.save(self.data, self.output, 'json') output = unicode(output) self.output = StringIO(output) extr_data = srz.load(self.output, 'json') self.assertEqual(self.data, extr_data)
def convert_image_yaml(yaml): h = serialize.load(yaml) d = Image(h, spacing=h.spacing, medium_index=h.optics.index, illum_wavelen=h.optics.wavelen, illum_polarization=h.optics.polarization) name, ext = os.path.splitext(yaml) save(name, d)
def load(self): load_config = read_last_configs() specifier = "rb" if load_config == "pickle" else "r" try: with open(self.filename, specifier) as source: self._db = serialize.load(source, load_config) except OSError: self._db = []
def test_file_by_name(self): fh = _get_format(self.FMT) obj = dict(answer=42) filename1 = "tmp." + fh.extension dump(obj, filename1) try: obj1 = load(filename1) self.assertEqual(obj, obj1) finally: os.remove(filename1) filename2 = "tmp." + fh.extension + ".bla" dump(obj, filename2, fmt=self.FMT) try: obj2 = load(filename2, fmt=self.FMT) self.assertEqual(obj, obj2) finally: os.remove(filename2)
def load(self, path): """Load parameters from yaml file to CorrectorArmy. Parameters ---------- path : path path to file where army is to be saved """ # TODO: Not implemented data = load(path) self.bkg_params.loads(data['bkg']) self.bleach_params.loads(data['bleach']) self.bleed_mean, self.bleed_error = data['bleed']
def load(self): a=QMessageBox() path = "." fname = QFileDialog.getOpenFileName(self,"Open mindmap",path,"Mindmaps(*.mindqt)") if fname.isEmpty(): return self.filename=fname self.new() if not serialize.load(self.filename,self.view): a.setText("Document couldn't be loaded") a.exec_() else: a.setText("Document succesfully loaded") a.exec_()
def people_group_api(request): if request.method == "GET": groups = PeopleGroup.find_all() return JSONResponse(jsonfy(groups)) elif request.method == "POST": group_name = request.POST.get('group_name') people_list = load(request.POST.get("people_list")) print people_list group = PeopleGroup.find_one(group_name=group_name) if group is None: group = PeopleGroup(group_name=group_name, people_list=people_list) group.save() else: group.update(people_list=people_list) return JSONResponse(jsonfy(group))
def _test_round_trip(self, obj): dumped = dumps(obj, self.FMT) # dumps / loads self.assertEqual(obj, loads(dumped, self.FMT)) buf = io.BytesIO() dump(obj, buf, self.FMT) # dump / dumps self.assertEqual(dumped, buf.getvalue()) buf.seek(0) # dump / load self.assertEqual(obj, load(buf, self.FMT))
def from_yaml(cls, filename): with open(filename, mode='w', encoding='utf-8') as fi: source = serialize.load(fi) f = Flock() f._source_dict = source for name, info in source['drivers']: driver_cls = helpers.import_from_entrypoint(info['cls']) driver = driver_cls(name=info['name'], *info.get('args', ()), **info.get('kwargs', {})) driver.logger_name = info.get('logger_name', None) f.add(driver, *info.get('dependencies', ())) f._checkpoint[info['name']] = info.get('state', {}) return f
def init(self): self.name = self.name_base + ' Leg' self.segments = serialize.load(self.model) assert len(self.segments) == 3 initial_direction = self.segments[0].direction_center if self.orientation == 'counterclockwise': self.segments[0].axis *= -1 self.segments[1].axis *= -1 self.segments[1].default_rotation *= -1 self.segments[2].axis *= -1 self.segments[2].default_rotation *= -1 axis = initial_direction.cross(self.leg_direction) angle = initial_direction.interior_angle(self.leg_direction) for i in range(len(self.segments)): segment = self.segments[i] self.init_segment(segment, i, axis, angle) self.segments[0].parent = self
def from_filenames( cls, filenames: Iterable[Union[str, pathlib.Path]], fmt=None, *, raise_on_error=True, err_on_unexpected=True, err_on_missing=True, ): """Load the content of a multiple filenames into this datastructure This leverages the serialize library. Parameters ---------- filenames : List[str] Multiple filenames. The first has precedence over the last. raise_on_error : bool If true, an exception will be raised. If false, the exception will be recorded. err_on_unexpected : bool If true, an unexpected value will produce an error. If false, only a warning is issued. err_on_missing : bool If true, a missing value will produce an error. If false, only a warning is issued. Returns ------- DataStruct """ dct = merge( tuple(serialize.load(filename, fmt) for filename in filenames)) return cls.from_dict( dct, raise_on_error=raise_on_error, err_on_unexpected=err_on_unexpected, err_on_missing=err_on_missing, )
def from_filename( cls, filename: str, fmt=None, *, raise_on_error=True, err_on_unexpected=True, err_on_missing=True, ): """Load the content of a filename into this datastructure This leverages the serialize library. Parameters ---------- filename : str fmt : str or None File format. Use None (default) to infer from the extension) raise_on_error : bool If true, an exception will be raised. If false, the exception will be recorded. err_on_unexpected : bool If true, an unexpected value will produce an error. If false, only a warning is issued. err_on_missing : bool If true, a missing value will produce an error. If false, only a warning is issued. Returns ------- DataStruct """ return cls.from_dict( serialize.load(filename, fmt), raise_on_error=raise_on_error, err_on_unexpected=err_on_unexpected, err_on_missing=err_on_missing, )
def run(self): if not self.connected: return self.running = True while self.running: inready, outready, exready = select.select([self.sock], [], [], 5) if inready: response = self.sock.recv(5) # Check for a closed connection if response == '': return if response != 'move\n': continue response = self.sock.recv(10000) board = serialize.load(response) move = self.decide_move(board) self.send_move(move[0], move[1])
def start(config, file_name): """function for run project""" file_obj = open (config, "r") tp = pickle.load(file_obj); file_obj.close() file_obj = open (file_name, "r "); calendar = serialize.load(file_obj, tp) file_obj.close() calendar = Control.menu(calendar) new_tp = save_result() file_obj = open (file_name, "w"); if new_tp == "": serialize.save(calendar, file_obj, tp) else: fl = open(config, "w") pickle.dump(new_tp, fl) fl.close() serialize.save(calendar, file_obj, new_tp) file_obj.close()
def load_memory(self): return load(str(self.path.joinpath('memory.json')))
def _load_table(table_name): yaml_table = load((os.path.join(__location__, table_name))) result = {} for D, sub_table in yaml_table.items(): result.update({D: {k: v * ureg.inch for k, v in sub_table.items()}}) return result
def test_pickle(self): """ test for serialization with pickle """ output = srz.save(self.data, self.output, 'pickle') self.output = BytesIO(output) extr_data = srz.load(self.output, "pickle") self.assertEqual(self.data, extr_data)
def from_yaml(cls, filename): source = serialize.load(filename) f = Flock() f._source_dict = source return cls.parse(f, source)
def load(inf, spacing=None, optics=None, channel=None): """ Load data or results Parameters ---------- inf : single or list of basestring or files File to load. If the file is a yaml file, all other arguments are ignored. If inf is a list of image files or filenames they are all loaded as a a timeseries hologram optics : :class:`holopy.optics.Optics` object or string (optional) Optical train parameters. If string, specifies the filename of an optics yaml bg : string (optional) name of background file bg_type : string (optional) set to 'subtract' or 'divide' to specify how background is removed channel : int (optional) number of channel to load for a color image (in general 0=red, 1=green, 2=blue) time_scale : float or list (optional) time between frames or, if list, time at each frame Returns ------- obj : The object loaded, :class:`holopy.core.marray.Image`, or as loaded from yaml """ if isinstance(optics, (basestring, file)): optics = serialize.load(optics) # In the past We allowed optics yamls to be written without an !Optics # tag, so for that backwards compatability, we attempt to turn an # anonymous dict into an Optics if isinstance(optics, dict): optics = Optics(**optics) # attempt to load a holopy yaml file try: loaded = serialize.load(inf) if optics is not None and spacing is not None: loaded = arr_like(loaded, spacing=spacing, optics=optics) warn("Overriding spacing and optics of loaded yaml") elif optics is not None: loaded = arr_like(loaded, optics=optics) warn( "WARNING: overriding optics of loaded yaml without overriding " "spacing, this is probably incorrect.") elif spacing is not None: loaded = arr_like(loaded, spacing=spacing) warn( "WARNING: overriding spacing of loaded yaml without overriding " "optics, this is probably incorrect.") return loaded except (serialize.ReaderError, AttributeError): pass # If that fails, we go on an read images loaded_files = [] for inf in _ensure_array(inf): if not loaded_yaml: loaded = load_image(inf, spacing=spacing, optics=optics, channel=channel) loaded_files.append(loaded) return Image(np.dstack(loaded_files).squeeze(), optics=optics, spacing=spacing)
return JSONResponse(jsonfy({"errmsg": errmsg + u"\n指标无法从APP接口获取"})) except MissingValueError, e: errmsg = u"""以下指标数据缺失:\n""" for missing_norm in e.norm: errmsg += missing_norm.name + "," return JSONResponse(jsonfy({"errmsg": errmsg})) except OverThresholdError, e: errmsg = u"""以下指标超过阈值:\n""" for missing_norm in e.norm: errmsg += missing_norm.name + "," return JSONResponse(jsonfy({"errmsg": errmsg})) # 数据合格,给领导发送 fail_list = [] success_list = [] people_list = Message.find_one(_id=message_id).people_list for name, phone in load(people_list).iteritems(): result = load( send_message(phone=phone, msg=message_str, user_num=global_config.get("staffId"))) if result["errmsg"] != u"请求成功": fail_list.append(name) else: success_list.append(name) error_msg = u"成功发送给:\n" for one in success_list: error_msg += one + " " if len(fail_list) != 0: error_msg += u"\n以下发送失败:\n" for one in fail_list: error_msg += one + " "
#!/usr/bin/env python # -*- coding: utf-8 -*- import serialize as s lrs = s.load(open('data/lecturers.yml')) globals().update(lrs)
def load_ip_dict(self): if self.path.exists(): return load(str(self.path)) else: return {}
import code import robot import position import insect import display import arduino import serialize import controller # Connect to Arduino print(">>> arduino.connect()") arduino_board = arduino.connect() # Load Robot Data serialize.package = sys.modules[__name__] r = serialize.load("model.txt") # Draw Window window = display.Display() # Define Cleanup Method def exit(): if arduino_board: arduino_board.close() sys.exit() # Build Controller controller.robot = r controller.arduino_board = arduino_board controller.window = window