code
stringlengths
1
18.2k
def _compute_one_step(self, t, fields, pars): """ Compute one step of the simulation, then update the timers. """ fields, pars = self._hook(t, fields, pars) self.dt = (self.tmax - t if self.tmax and (t + self.dt >= self.tmax) else self.dt) before_compute = time.process_time() t, fields = self._scheme(t, fields, self.dt...
def compute(self): """Generator which yield the actual state of the system every dt. Yields ------ tuple : t, fields Actual time and updated fields container. """ fields = self.fields t = self.t pars = self.parameters self._started_timestamp = pendulum.now() self.stream.emit(self) try: while True: t, fields, pars = sel...
def run(self, progress=True, verbose=False): """Compute all steps of the simulation. Be careful: if tmax is not set, this function will result in an infinit loop. Returns ------- (t, fields): last time and result fields. """ total_iter = int((self.tmax // self.user_dt) if self.tmax else None) log = logging.info if verb...
def attach_container(self, path=None, save="all", mode="w", nbuffer=50, force=False): """add a Container to the simulation which allows some persistance to the simulation. Parameters ---------- path : str or None (default: None) path for the container. If None (the default), the data lives only in memory (and are avail...
(path, self.id) if path else None, save=save, mode=mode, metadata=self.parameters, force=force, nbuffer=nbuffer) self._container.connect(self.stream) return self._container
def add_post_process(self, name, post_process, description=""): """add a post-process Parameters ---------- name : str name of the post-traitment post_process : callback (function of a class with a __call__ method or a streamz.Stream). this callback have to accept the simulation state as parameter and return the modifi...
def remove_post_process(self, name): """remove a post-process Parameters ---------- name : str name of the post-process to remove. """ self._pprocesses = [post_process for post_process in self._pprocesses if post_process.name != name]
def task_done(self, **kws): """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been...
def put(self, item, block=True, **kws): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was availab...
def cache_file(package, mode): """ Yields a file-like object for the purpose of writing to or reading from the cache. The code: with cache_file(...) as f: # do stuff with f is guaranteed to convert any exceptions to warnings (*), both in the cache_file(...) call and the 'do stuff with f' block. The file is automaticall...
exceptions coming from the with block. with exception_to_warning('use cache while checking for outdated package', OutdatedCacheFailedWarning): try: cache_path = os.path.join(tempfile.gettempdir(), get_cache_filename(package)) if mode == 'w' or os.path.exists(cache_path): f = open(cache_path, mode) finally: # Putting th...
def exception_to_warning(description, category, always_raise=False): """ Catches any exceptions that happen in the corresponding with block and instead emits a warning of the given category, unless always_raise is True or the environment variable OUTDATED_RAISE_EXCEPTION is set to 1, in which caise the exception will n...
def transmit_length(self, val=3): """Sets transmit length.""" if self.instrument == "Vectrino" and type(val) is float: if val == 0.3: self.pdx.TransmitLength = 0 elif val == 0.6: self.pdx.TransmitLength = 1 elif val == 1.2: self.pdx.TransmitLength = 2 elif val == 1.8: self.pdx.TransmitLength = 3 elif val == 2.4: self.p...
def sampling_volume(self, val): """Sets sampling volume.""" if self.instrument == "Vectrino" and type(val) is float: if val == 2.5: self.pdx.SamplingVolume = 0 elif val == 4.0: self.pdx.SamplingVolume = 1 elif val == 5.5: self.pdx.SamplingVolume = 2 elif val == 7.0: self.pdx.SamplingVolume = 3 elif val == 8.5: self.pdx...
def sound_speed_mode(self, mode): """Sets sound speed mode; 0 or "measured" for measured; 1 or "fixed" for fixed.""" if mode == "measured": mode = 0 if mode == "fixed": mode = 1 self.pdx.SoundSpeedMode = mode
def sound_speed(self, value): """Sets the sound speed in m/s. Default is 1525.0. If this function is called, `sound_speed_mode` will be set to fixed.""" if not self.sound_speed_mode: self.sound_speed_mode = 1 self.pdx.SoundSpeed = float(value)
def power_level(self, val): """Sets the power level according to the index or string. 0 = High 1 = HighLow 2 = LowHigh 3 = Low""" if val in [0, 1, 2, 3]: self.pdx.PowerLevel = val elif type(val) is str: if val.lower() == "high": self.pdx.PowerLevel = 0 elif val.lower() == "highlow": self.pdx.PowerLevel = 1 elif val.low...
def coordinate_system(self, coordsys): """Sets instrument coordinate system. Accepts an int or string.""" if coordsys.upper() == "ENU": ncs = 0 elif coordsys.upper() == "XYZ": ncs = 1 elif coordsys.upper() == "BEAM": ncs = 2 elif coordsys in [0, 1, 2]: ncs = coordsys else: raise ValueError("Invalid coordinate system se...
def start_disk_recording(self, filename, autoname=False): """Starts data recording to disk. Specify the filename without extension. If autoname = True a new file will be opened for data recording each time the specified time interval has elapsed. The current date and time is then automatically added to the filename."""...
def sampling_volume_value(self): """Returns the device samping volume value in m.""" svi = self.pdx.SamplingVolume tli = self.pdx.TransmitLength return self._sampling_volume_value(svi, tli)
def _launch_forever_coro(coro, args, kwargs, loop): ''' This helper function launches an async main function that was tagged with forever=True. There are two possibilities: - The function is a normal function, which handles initializing the event loop, which is then run forever - The function is a coroutine, which need...
ensure that any exceptions raised in the tasks are collected ASAP. ''' # Personal note: I consider this an antipattern, as it relies on the use of # unowned resources. The setup function dumps some stuff into the event # loop where it just whirls in the ether without a well defined owner or # lifetime. For this reason,...
def autoasync(coro=None, *, loop=None, forever=False, pass_loop=False): ''' Convert an asyncio coroutine into a function which, when called, is evaluted in an event loop, and the return value returned. This is intented to make it easy to write entry points into asyncio coroutines, which otherwise need to be explictly e...
with asyncio.start_server and the like. If `pass_loop` is True, the event loop object is passed into the coroutine as the `loop` kwarg when the wrapper function is called. In this case, the wrapper function's __signature__ is updated to remove this parameter, so that autoparse can still be used on it without generating...
parameter in 100% of cases, even if it's a positional parameter. # NOTE: A future release will probably require the loop parameter to be # a kwonly parameter. if pass_loop: old_sig = signature(coro) new_sig = old_sig.replace(parameters=( param for name, param in old_sig.parameters.items() if name != "loop")) @wraps(cor...
local_loop.run_forever() else: return local_loop.run_until_complete(coro(*args, **kwargs)) # Attach the updated signature. This allows 'pass_loop' to be used with # autoparse if pass_loop: autoasync_wrapper.__signature__ = new_sig return autoasync_wrapper
def automain(module, *, args=(), kwargs=None): ''' This decorator automatically invokes a function if the module is being run as the "__main__" module. Optionally, provide args or kwargs with which to call the function. If `module` is "__main__", the function is called, and the program is `sys.exit`ed with the return v...
kwargs is None: kwargs = {} # Use a function definition instead of a lambda for a neater traceback def automain_decorator(main): sys.exit(main(*args, **kwargs)) return automain_decorator else: return lambda main: main
async def report_winner(self, winner: Participant, scores_csv: str): """ report scores and give a winner |methcoro| Args: winner: :class:Participant instance scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2") Raises: ValueError: scores_csv has a wrong format APIException """ awai...
async def reopen(self): """ Reopens a match that was marked completed, automatically resetting matches that follow it |methcoro| Raises: APIException """ res = await self.connection('POST', 'tournaments/{}/matches/{}/reopen'.format(self._tournament_id, self._id)) self._refresh_from_json(res)
async def change_votes(self, player1_votes: int = None, player2_votes: int = None, add: bool = False): """ change the votes for either player |methcoro| The votes will be overriden by default, If `add` is set to True, another API request call will be made to ensure the local is up to date with the Challonge server. The...
Raises: ValueError: one of the votes arguments must not be None APIException """ assert_or_raise(player1_votes is not None or player2_votes is not None, ValueError, 'One of the votes must not be None') if add: # order a fresh update of this match res = await self.connection('GET', 'tournaments/{}/matches/{}'.format(sel...
async def attach_file(self, file_path: str, description: str = None) -> Attachment: """ add a file as an attachment |methcoro| Warning: |unstable| Args: file_path: path to the file you want to add description: *optional* description for your attachment Returns: Attachment: Raises: ValueError: file_path must not be None...
async def attach_url(self, url: str, description: str = None) -> Attachment: """ add an url as an attachment |methcoro| Args: url: url you want to add description: *optional* description for your attachment Returns: Attachment: Raises: ValueError: url must not be None APIException """ return await self._attach(url=url,...
async def destroy_attachment(self, a: Attachment): """ destroy a match attachment |methcoro| Args: a: the attachment you want to destroy Raises: APIException """ await self.connection('DELETE', 'tournaments/{}/matches/{}/attachments/{}'.format(self._tournament_id, self._id, a._id)) if a in self.attachments: self.attach...
def class_subobjects( class_: Type) -> Generator[Tuple[str, Type, bool], None, None]: """Find the aggregated subobjects of an object. These are the public attributes. Args: class_: The class whose subobjects to return. Yields: Tuples (name, type, required) describing subobjects. """ argspec = inspect.getfullargspec(cla...
def read_tarball(path, shortkey=False, classes=Editor): """ Read a (possibly compressed) tarball archive and return a dictionary of editors. .. code-block:: python eds = read_tarball(path, classes=MyEditor) # All files read as type MyEditor # Only read the special file as type MyEditor (default to Editor) eds = read_ta...
= classes.get(name, Editor) elif callable(classes): cls = classes(name) else: raise TypeError("Wrong type for classes argument (with type {})".format(type(classes))) editors[name] = cls(f, name=name) return editors
def format_frameinfo(fi): """ Takes a frameinfo object (from the inspect module) returns a properly formated string """ s1 = "{0}:{1}".format(fi.filename, fi.lineno) s2 = "function:{0}, code_context:".format(fi.function) if fi.code_context: s3 = fi.code_context[0] else: s3 = "<no code context available>" return "\n".jo...
def get_frame_list(): """ Create the list of frames """ # TODO: use this function in IPS below (less code duplication) frame_info_list = [] frame_list = [] frame = inspect.currentframe() while frame is not None: frame_list.append(frame) info = inspect.getframeinfo(frame) frame_info_list.append(info) frame = frame.f_bac...
def IPS(copy_namespaces=True, overwrite_globals=False): """Starts IPython embedded shell. This is similar to IPython.embed() but with some additional features: 1. Print a list of the calling frames before entering the prompt 2. (optionally) copy local name space to global one to prevent certain IPython bug. 3. while do...
"{0}{1}{2}".format(custom_header1, frame_info_str, custom_header2) # prevent IPython shell to be launched in IP-Notebook test_str = str(frame_info_list[0]) + str(frame_info_list[1]) if 'IPython' in test_str and 'zmq' in test_str: print("\n- Not entering IPython embedded shell -\n") return # copied (and modified) from I...
reversed above f1 = frame_list[-2] lns = f1.f_locals gns = f1.f_globals l_keys = set(lns) g_keys = set(gns) u_keys = shell.user_ns.keys() # those keys which are in local ns but not in global safe_keys = l_keys - g_keys unsafe_keys = l_keys.intersection(g_keys) assert safe_keys.union(unsafe_keys) == l_keys gns.update({k...
= gns else: # unexpected few frames or no copying desired: lns = None dummy_module = None # now execute the shell shell(header=custom_header, stack_depth=2, local_ns=lns, module=dummy_module) custom_excepthook = getattr(sys, 'custom_excepthook', None) if custom_excepthook is not None: assert callable(custom_excepthook)...
def ip_shell_after_exception(frame): """ Launches an IPython embedded shell in the namespace where an exception occurred. :param frame: :return: """ # let the user know, where this shell is 'waking up' # construct frame list # this will be printed in the header frame_info_list = [] frame_list = [] original_frame = fram...
= str(frame_info_list[0]) + str(frame_info_list[1]) if 'IPython' in test_str and 'zmq' in test_str: print("\n- Not entering IPython embedded shell -\n") return # copied (and modified) from IPython/terminal/embed.py config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell # these two...
def ips_excepthook(excType, excValue, traceback, frame_upcount=0): """ This function is launched after an exception. It launches IPS in suitable frame. Also note that if `__mu` is an integer in the local_ns of the closed IPS-Session then another Session is launched in the corresponding frame: "__mu" means = "move up" a...
is the critical frame where the exception occured index = 0 diff_index = frame_upcount while diff_index is not None: index += diff_index tb_printer.print(end_offset=index) current_frame = tb_frame_list[index] diff_index = ip_shell_after_exception(frame=current_frame)
def color_exepthook(pdb=0, mode=2): """ Make tracebacks after exceptions colored, verbose, and/or call pdb (python cmd line debugger) at the place where the exception occurs """ modus = ['Plain', 'Context', 'Verbose'][mode] # select the mode sys.excepthook = ultratb.FormattedTB(mode=modus, color_scheme='Linux', call_pd...
def ip_extra_syshook(fnc, pdb=0, filename=None): """ Extended system hook for exceptions. supports logging of tracebacks to a file lets fnc() be executed imediately before the IPython Verbose Traceback is started this can be used to pop up a QTMessageBox: "An exception occured" """ assert isinstance(fnc, collections.Ca...
def save_current_nb_as_html(info=False): """ Save the current notebook as html file in the same directory """ assert in_ipynb() full_path = get_notebook_name() path, filename = os.path.split(full_path) wd_save = os.getcwd() os.chdir(path) cmd = 'jupyter nbconvert --to html "{}"'.format(filename) os.system(cmd) os.chdir...
def dirsearch(word, obj, only_keys = True, deep = 0): """ search a string in dir(<some object>) if object is a dict, then search in keys optional arg only_keys: if False, returns also a str-version of the attribute (or dict-value) instead only the key this function is not case sensitive """ word = word.lower() if isins...
search also in value (if it is of type basestring) if not isinstance(value, str): value = "" # only local change return (word in key.lower()) or (word in value.lower()) res = [(k, maxlen(str(v), 20)) for k,v in items if match(word, k, v)] # res is a list of (key,value)-pairs if deep > 0: def interesting(obj): module = ...
keys return res
def get_whole_assignment_expression(line, varname, seq_type): """ Example: line = "x = Container(cargs=(a, b, c))" varname = cargs delimiter pair = "()" return "a, b, c" :return: """ tokens = list(tk.generate_tokens(io.StringIO(line).readline)) if issubclass(seq_type, tuple): L, R = "()" elif issubclass(seq_type, list)...
if search_mode < 1 or not t.type == tk.OP: continue if t.string == L: DOL += 1 search_mode = 2 if t.string == R: DOL -= 1 if search_mode == 2 and DOL == 0: i_end = i break else: # no break raise ValueError(errmsg) substr = line[tokens[i_start].start[1]: tokens[i_end].end[1]] try: assert substr.count(L) == 1 assert subs...
def _get_attrs(self, names): """ Convenience function to extract multiple attributes at once :param names: string of names separated by comma or space :return: """ assert isinstance(names, str) names = names.replace(",", " ").split(" ") res = [] for n in names: if n == "": continue if n not in self.__dict__: raise KeyE...
def fetch_locals(self, upcount=1): """ Magic function which fetches all variables from the callers namespace :param upcount int, how many stack levels we go up :return: """ frame = inspect.currentframe() i = upcount while True: if frame.f_back is None: break frame = frame.f_back i -= 1 if i == 0: break for k, v in fram...
def publish_attrs(self, upcount=1): """ Magic function which inject all attrs into the callers namespace :param upcount int, how many stack levels we go up :return: """ frame = inspect.currentframe() i = upcount while True: if frame.f_back is None: break frame = frame.f_back i -= 1 if i == 0: break for k, v in self.__d...
def parsemsg(s): # stolen from twisted.words """Breaks a message from an IRC server into its prefix, command, and arguments. """ prefix = '' trailing = [] if not s: raise Exception("Empty line.") if s[0] == ':': prefix, s = s[1:].split(' ', 1) if s.find(' :') != -1: s, trailing = s.split(' :', 1) args = s.split() args....
def pull(self): """This coroutine handles the server connection, does a basic parse on the received messages and put them in a queue named events. The controllers pull method will take the messages from that queue. """ self.sock = sockets.Socket() self.sock.settimeout(self.sock_timo) yield events.AddCoro(self.monitor) ...
def push(self, id): "Sends a message to the specified connection (id)" conn = session['connections'].get(id, None) if conn: msgs = simplejson.loads(request.body) for msg in msgs: try: cmd = msg.pop(0).upper() assert ' ' not in cmd, "Bad message" if cmd in ('USER', ): sufix = " :"+msg.pop() else: sufix = '' assert not [...
def connect(self, server): "Connects to a server and return a connection id." if 'connections' not in session: session['connections'] = {} session.save() conns = session['connections'] id = str(len(conns)) conn = Connection(server) conns[id] = conn yield request.environ['cogen.core'].events.AddCoro(conn.pull) yield id
def pull(self, id): """Take the messages from the queue and if there are none wait 30 seconds till returning an empty message. Also, cogen's wsgi async extensions are in the environ and prefixed with 'cogen.' """ conn = session['connections'].get(id, None) conn.last_update = time.time() if conn: ev_list = [] while 1: #...
elif isinstance(event, Exception): ev_list.append(('', 'ERROR', str(event))) break else: ev_list.append(event) if ev_list: print 'PULL:', ev_list yield simplejson.dumps(ev_list) else: # if we don't have any updates atm, we'll wait 30 secs for one yield request.environ['cogen.call'](conn.events.get)(timeout=30) event = ...
def main(input_filename, songname, format, counter): """ Calculate the fingerprint hashses of the referenced audio file and save to disk as a pickle file """ # open the file & convert to wav song_data = AudioSegment.from_file(input_filename, format=format) song_data = song_data.set_channels(1) # convert to mono wav_tmp...
def make_frame(self, frame, birthframe, startframe, stopframe, deathframe, noiseframe=None): """ :param frame: current frame :param birthframe: frame where this animation starts returning something other than None :param startframe: frame where animation starts to evolve :param stopframe: frame where animation is compl...
def decode(cls, root_element): """ Decode the object to the object :param root_element: the parsed xml Element :type root_element: xml.etree.ElementTree.Element :return: the decoded Element as object :rtype: object """ new_object = cls() field_names_to_attributes = new_object._get_field_names_to_attributes() for child_...
def calendar(format, *args, **kwargs): """ Creates a formatted ``HTMLCalendar``. Argument ``format`` can be one of ``month``, ``year``, or ``yearpage`` Keyword arguments are collected and passed into ``HTMLCalendar.formatmonth``, ``HTMLCalendar.formatyear``, and ``HTMLCalendar.formatyearpage`` Syntax:: {% calendar mont...
def verify_address(self, addr1="", addr2="", city="", fname="", lname="", phone="", province="", postal="", country="", email="", recordID="", freeform= ""): """verify_address Builds a JSON request to send to Melissa data. Takes in all needed address info. Args: addr1 (str):Contains info for Melissa data addr2 (str):Co...
"Records": [{ "RecordID": recordID, "CompanyName": "", "FullName": fname + " " + lname, "AddressLine1": addr1, "AddressLine2": addr2, "Suite": "", "City": city, "State": province, "PostalCode": postal, "Country": country, "PhoneNumber": phone, "EmailAddress": email, "FreeForm": freeform, }] } self.country = country dat...
def parse_results(self, data): """parse_results Parses the MelissaData response. Args: data (dict): Contains MelissaData response Returns: results, either contains a dict with corrected address info or -1 for an invalid address. """ results = [] if len(data["Records"]) < 1: return -1 codes = data["Records"][0]["Results...
def add(self, coro, args=(), kwargs={}, first=True): """Add a coroutine in the scheduler. You can add arguments (_args_, _kwargs_) to init the coroutine with.""" assert callable(coro), "'%s' not a callable object" % coro coro = coro(*args, **kwargs) if first: self.active.append( (None, coro) ) else: self.active.appendl...
def next_timer_delta(self): "Returns a timevalue that the proactor will wait on." if self.timeouts and not self.active: now = getnow() timo = self.timeouts[0].timeout if now >= timo: #looks like we've exceded the time return 0 else: return (timo - now) else: if self.active: return 0 else: return None
def handle_timeouts(self): """Handle timeouts. Raise timeouted operations with a OperationTimeout in the associated coroutine (if they are still alive and the operation hasn't actualy sucessfuly completed) or, if the operation has a weak_timeout flag, update the timeout point and add it back in the heapq. weak_timeout ...
to check if the op has completed since finalized is set when the operation gets back in the coro - and it might still be in the Scheduler.active queue when we get to this timeout - well, this is certainly a problem magnet: TODO: fix_finalized) """ now = getnow() #~ print '>to:', self.timeouts, self.timeouts and self.ti...
def process_op(self, op, coro): "Process a (op, coro) pair and return another pair. Handles exceptions." if op is None: if self.active: self.active.append((op, coro)) else: return op, coro else: try: result = op.process(self, coro) or (None, None) except: op.state = events.ERRORED result = CoroutineException(*sys.exc_i...
def iter_run(self): """ The actual processing for the main loop is here. Running the main loop as a generator (where a iteration is a full sched, proactor and timers/timeouts run) is usefull for interleaving the main loop with other applications that have a blocking main loop and require cogen to run in the same thread...
if self.timeouts: self.handle_timeouts() yield # this could had beed a ordinary function and have the run() call #this repeatedly but the _urgent_ operation this is usefull (as it #saves us needlessly hammering the active coroutines queue with #append and pop calls on the same thing self.cleanup()
def cleanup(self): """Used internally. Cleans up the sched references in the proactor. If you use this don't use it while the :class:`Scheduler` (:func:`run`) is still running. """ if hasattr(self, 'proactor'): if hasattr(self.proactor, 'scheduler'): del self.proactor.scheduler if hasattr(self.proactor, 'close'): self....
def add_note(self, body): """ Create a Note to current object :param body: the body of the note :type body: str :return: newly created Note :rtype: Tag """ from highton.models.note import Note created_id = self._post_request( endpoint=self.ENDPOINT + '/' + str(self.id) + '/' + Note.ENDPOINT, data=self.element_to_string...
def hms2frame(hms, fps): """ :param hms: a string, e.g. "01:23:15" for one hour, 23 minutes 15 seconds :param fps: framerate :return: frame number """ import time t = time.strptime(hms, "%H:%M:%S") return (t.tm_hour * 60 * 60 + t.tm_min * 60 + t.tm_sec) * fps
def list_emails(self, page=0, since=None): """ Get the emails of current object :param page: the page starting at 0 :type since: int :param since: get all notes since a datetime :type since: datetime.datetime :return: the emails :rtype: list """ from highton.models.email import Email params = {'n': int(page) * self.EMA...
def tween(self, t): """ t is number between 0 and 1 to indicate how far the tween has progressed """ if t is None: return None if self.method in self.method_to_tween: return self.method_to_tween[self.method](t) elif self.method in self.method_1param: return self.method_1param[self.method](t, self.param1) elif self.meth...
def tween2(self, val, frm, to): """ linearly maps val between frm and to to a number between 0 and 1 """ return self.tween(Mapping.linlin(val, frm, to, 0, 1))
def _encode_str(self, obj, escape_quotes=True): """Return an ASCII-only JSON representation of a Python string""" def replace(match): s = match.group(0) try: if escape_quotes: return ESCAPE_DCT[s] else: return BASE_ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: return '\\u{0:04x}'.format(n) else: # surrogate...
def _encode_numbers(self, obj): """Returns a JSON representation of a Python number (int, float or Decimal)""" # strict checks first - for speed if obj.__class__ is int: if abs(obj) > JAVASCRIPT_MAXINT: raise ValueError('Number out of range: {!r}'.format(obj)) return str(obj) if obj.__class__ is float: if isnan(obj): r...
def _encode_list(self, obj):# do """Returns a JSON representation of a Python list""" self._increment_nested_level() buffer = [] for element in obj: buffer.append(self._encode(element)) self._decrement_nested_level() return '['+ ','.join(buffer) + ']'
def _encode_dict(self, obj): """Returns a JSON representation of a Python dict""" self._increment_nested_level() buffer = [] for key in obj: buffer.append(self._encode_key(key) + ':' + self._encode(obj[key])) self._decrement_nested_level() return '{'+ ','.join(buffer) + '}'
def _encode_key(self, obj): """Encodes a dictionary key - a key can only be a string in std JSON""" if obj.__class__ is str: return self._encode_str(obj) if obj.__class__ is UUID: return '"' + str(obj) + '"' # __mm_serialize__ is called before any isinstance checks (but after exact type checks) try: sx_encoder = obj.__...
def _encode(self, obj): """Returns a JSON representation of a Python object - see dumps. Accepts objects of any type, calls the appropriate type-specific encoder. """ if self._use_hook: obj = self.encode_hook(obj) # first try simple strict checks _objtype = obj.__class__ if _objtype is str: return self._encode_str(obj)...
sx_json_data = obj.__mm_json__ except AttributeError: pass else: try: data = sx_json_data() except NotImplementedError: pass else: if isinstance(data, bytes): return data.decode('utf-8') else: return self._encode_str(data, escape_quotes=False) try: sx_encoder = obj.__mm_serialize__ except AttributeError: pass else: try...
def dumps(self, obj, *, max_nested_level=100): """Returns a string representing a JSON-encoding of ``obj``. The second optional ``max_nested_level`` argument controls the maximum allowed recursion/nesting level. See class description for details. """ self._max_nested_level = max_nested_level return self._encode(obj)
def dumpb(self, obj, *, max_nested_level=100): """Similar to ``dumps()``, but returns ``bytes`` instead of a ``string``""" self._max_nested_level = max_nested_level return self._encode(obj).encode('utf-8')
def download_file(url, filename=None, show_progress=draw_pbar): ''' Download a file and show progress url: the URL of the file to download filename: the filename to download it to (if not given, uses the url's filename part) show_progress: callback function to update a progress bar the show_progress function shall take...
def main(): ''' entry point of the application. Parses the CLI commands and runs the actions. ''' args = CLI.parse_args(__doc__) if args['--verbose']: requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) logging.basicConfig(level=logging.DEBUG) if not args['-k']: print("No ...
def part_search(self, part_query): ''' handles the part lookup/search for the given part query part_query: part string to search as product name outputs result on stdout ''' limit = 100 results = self._e.parts_search(q=part_query, limit=limit) start = 0 hits = results[0]['hits'] if hits == 0: print("No result") return ...
def part_specs(self, part): ''' returns the specifications of the given part. If multiple parts are matched, only the first one will be output. part: the productname or sku prints the results on stdout ''' result = self._e.parts_match( queries=[{'mpn_or_sku': part}], exact_only=True, show_mpn=True, show_manufacturer=Tr...
max_value): print(" → {:20}: {}{}".format(name, value, unit)) elif value and min_value and max_value: print(" → {:20}: {}{} (min: {}, max: {})".format(name, value, unit, min_value, max_value)) elif not value and min_value and max_value: print(" → {:20}:{} min: {}, max: {}".format(name, unit, min_value, max_value)) elif...
Updated: {}".format(datasheet['metadata']['last_updated'])) print(" → Nb Pages: {}".format(datasheet['metadata']['num_pages'])) if len(result['reference_designs']) > 0: print(" → Reference designs: ") if len(result['cad_models']) > 0: print(" → CAD Models: ") return ReturnValues.OK