code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def _get_object_as_soft(self): soft = ["^%s = %s" % (self.geotype, self.name), self._get_metadata_as_string(), self._get_columns_as_string(), self._get_table_as_string()] return "\n".join(soft)
Get the object as SOFT formated string.
def _sort_column(self, column, reverse): if tk.DISABLED in self.state(): return l = [(self.set(child, column), child) for child in self.get_children('')] l.sort(reverse=reverse, key=lambda x: self._column_types[column](x[0])) for index, (val, child) in enumerate(l): ...
Sort a column by its values
def read_hdf5_timeseries(h5f, path=None, start=None, end=None, **kwargs): kwargs.setdefault('array_type', TimeSeries) series = read_hdf5_array(h5f, path=path, **kwargs) if start is not None or end is not None: return series.crop(start, end) return series
Read a `TimeSeries` from HDF5
def _fetchAllChildren(self): bands = self._bands if len(bands) != self._array.shape[-1]: logger.warn("No bands added, bands != last_dim_lenght ({} !: {})" .format(len(bands), self._array.shape[-1])) return [] childItems = [] for bandNr, ban...
Adds the bands as separate fields so they can be inspected easily.
def check_git_unchanged(filename, yes=False): if check_staged(filename): s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename) if yes or input(s) in ('y', 'yes'): return else: raise RuntimeError('There are staged changes in ' ...
Check git to avoid overwriting user changes.
def to_string(self, hdr, other): result = "%s[%s,%s" % ( hdr, self.get_type(self.type), self.get_clazz(self.clazz)) if self.unique: result += "-unique," else: result += "," result += self.name if other is not None: result += ",%...
String representation with additional information
def scroll_down (self): s = self.scroll_row_start - 1 e = self.scroll_row_end - 1 self.w[s+1:e+1] = copy.deepcopy(self.w[s:e])
Scroll display down one line.
def _assert_keys_match(keys1, keys2): if set(keys1) != set(keys2): raise ValueError('{} {}'.format(list(keys1), list(keys2)))
Ensure the two list of keys matches.
def new(self, filename=None): path = (self.exec_path,) if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE): p = find_executable("python") path = (p, 'python') + path else: path += (self.exec_path,) if filename: path += ...
start a session an independent process
def _add_properties(self, **kwargs): for k,v in kwargs.items(): if k=='parallax': self.obs.add_parallax(v) elif k in ['Teff', 'logg', 'feh', 'density']: par = {k:v} self.obs.add_spectroscopy(**par) elif re.search('_', k): ...
Adds non-photometry properties to ObservationTree
def add_target_and_index(self, name, sig, signode): targetname = '%s-%s' % (self.objtype, name) if targetname not in self.state.document.ids: signode['names'].append(targetname) signode['ids'].append(targetname) signode['first'] = (not self.names) self.sta...
Add a target and index for this thing.
def validate_vars(env): if 'PCH' in env and env['PCH']: if 'PCHSTOP' not in env: raise SCons.Errors.UserError("The PCHSTOP construction must be defined if PCH is defined.") if not SCons.Util.is_String(env['PCHSTOP']): raise SCons.Errors.UserError("The PCHSTOP construction var...
Validate the PCH and PCHSTOP construction variables.
def _make_qheader(self, job_name, qout_path, qerr_path): subs_dict = self.get_subs_dict() subs_dict['job_name'] = job_name.replace('/', '_') subs_dict['_qout_path'] = qout_path subs_dict['_qerr_path'] = qerr_path qtemplate = QScriptTemplate(self.QTEMPLATE) unclean_templat...
Return a string with the options that are passed to the resource manager.
def power_up(self): for m in self.motors: m.compliant = False m.moving_speed = 0 m.torque_limit = 100.0
Changes all settings to guarantee the motors will be used at their maximum power.
def _uint2objs(ftype, num, length=None): if num == 0: objs = [ftype.box(0)] else: _num = num objs = list() while _num != 0: objs.append(ftype.box(_num & 1)) _num >>= 1 if length: if length < len(objs): fstr = "overflow: num = {} req...
Convert an unsigned integer to a list of constant expressions.
def _client_connection(self, conn, addr): log.debug('Established connection with %s:%d', addr[0], addr[1]) conn.settimeout(self.socket_timeout) try: while self.__up: msg = conn.recv(self.buffer_size) if not msg: continue ...
Handle the connecition with one client.
def format_coord(self, x, y): p, b = stereonet_math.geographic2plunge_bearing(x, y) s, d = stereonet_math.geographic2pole(x, y) pb = u'P/B={:0.0f}\u00b0/{:03.0f}\u00b0'.format(p[0], b[0]) sd = u'S/D={:03.0f}\u00b0/{:0.0f}\u00b0'.format(s[0], d[0]) return u'{}, {}'.format(pb, sd)
Format displayed coordinates during mouseover of axes.
def _get_bus_array_construct(self): bus_no = integer.setResultsName("bus_no") v_base = real.setResultsName("v_base") v_magnitude = Optional(real).setResultsName("v_magnitude") v_angle = Optional(real).setResultsName("v_angle") area = Optional(integer).setResultsName("area") ...
Returns a construct for an array of bus data.
def _connect_lxd(spec): return { 'method': 'lxd', 'kwargs': { 'container': spec.remote_addr(), 'python_path': spec.python_path(), 'lxc_path': spec.mitogen_lxc_path(), 'connect_timeout': spec.ansible_ssh_timeout() or spec.timeout(), 'remote_...
Return ContextService arguments for an LXD container connection.
async def send_webmention(self, entry, url): if (entry.url, url) in self._processed_mentions: LOGGER.debug( "Skipping already processed mention %s -> %s", entry.url, url) self._processed_mentions.add((entry.url, url)) LOGGER.debug("++WAIT: webmentions.get_target %s", ...
send a webmention from an entry to a URL
def parse_option(self, option, block_name, message): if option == 'show': option = 'start_' + option key = option.split('_', 1)[0] self.messages[key] = message
Parse show, end_show, and timer_show options.
def run_work(self): if os.path.exists(LOCAL_EVAL_ROOT_DIR): sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR) self.run_attacks() self.run_defenses()
Run attacks and defenses
def unindent(self): _logger().debug('unindent') cursor = self.editor.textCursor() _logger().debug('cursor has selection %r', cursor.hasSelection()) if cursor.hasSelection(): cursor.beginEditBlock() self.unindent_selection(cursor) cursor.endEditBlock() ...
Un-indents text at cursor position.
def _should_defer(input_layer, args, kwargs): for arg in itertools.chain([input_layer], args, six.itervalues(kwargs)): if isinstance(arg, (_DeferredLayer, UnboundVariable)): return True elif (isinstance(arg, collections.Sequence) and not isinstance(arg, six.string_types)): if _should_def...
Checks to see if any of the args are templates.
def _handle_tag_enabledebugger2(self): obj = _make_object("EnableDebugger2") obj.Reserved = unpack_ui16(self._src) obj.Password = self._get_struct_string() return obj
Handle the EnableDebugger2 tag.
def audio_load_time(self): load_times = self.get_load_times('audio') return round(mean(load_times), self.decimal_precision)
Returns aggregate audio load time for all pages.
def create_modelo(self): return Modelo( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of modelo services facade.
def _fill_out_err(result, testcase): if result.get("stdout"): system_out = etree.SubElement(testcase, "system-out") system_out.text = utils.get_unicode_str(result["stdout"]) if result.get("stderr"): system_err = etree.SubElement(testcase, "system-err") sys...
Adds stdout and stderr if present.
def packstr(instr, textwidth=160, breakchars=' ', break_words=True, newline_prefix='', indentation='', nlprefix=None, wordsep=' ', remove_newlines=True): if not isinstance(instr, six.string_types): instr = repr(instr) if nlprefix is not None: newline_prefix = nlprefix ...
alias for pack_into. has more up to date kwargs
def validate(self): _validate_operator_name(self.operator, BinaryComposition.SUPPORTED_OPERATORS) if not isinstance(self.left, Expression): raise TypeError(u'Expected Expression left, got: {} {} {}'.format( type(self.left).__name__, self.left, self)) if not isinstance...
Validate that the BinaryComposition is correctly representable.
def mute_parse_args(self, text): error = AzCliCommandParser.error _check_value = AzCliCommandParser._check_value AzCliCommandParser.error = error_pass AzCliCommandParser._check_value = _check_value_muted try: parse_args = self.argsfinder.get_parsed_args(parse_quotes(t...
mutes the parser error when parsing, then puts it back
def all_floating_ips(self): if self.api_version == 2: json = self.request('/floating_ips') return json['floating_ips'] else: raise DoError(v2_api_required_str)
Lists all of the Floating IPs available on the account.
def _get_argument_list_from_toolkit_function_name(fn): unity = _get_unity() fnprops = unity.describe_toolkit_function(fn) argnames = fnprops['arguments'] return argnames
Given a toolkit function name, return the argument list
def android_example(): env = holodeck.make("AndroidPlayground") command = np.ones(94) * 10 for i in range(10): env.reset() for j in range(1000): if j % 50 == 0: command *= -1 state, reward, terminal, _ = env.step(command) pixels = state[Sen...
A basic example of how to use the android agent.
def _build_body_schema(serializer, body_parameters): description = "" if isinstance(body_parameters, Param): schema = serializer.to_json_schema(body_parameters.arginfo.type) description = body_parameters.description required = True else: if len(body_parameters) == 0: ...
body is built differently, since it's a single argument no matter what.
def tileXYZToQuadKey(self, x, y, z): quadKey = '' for i in range(z, 0, -1): digit = 0 mask = 1 << (i - 1) if (x & mask) != 0: digit += 1 if (y & mask) != 0: digit += 2 quadKey += str(digit) return quadKey
Computes quadKey value based on tile x, y and z values.
def parse_url(request, url): try: validate = URLValidator() validate(url) except ValidationError: if url.startswith('/'): host = request.get_host() scheme = 'https' if request.is_secure() else 'http' url = '{scheme}://{host}{uri}'.format(scheme=scheme,...
Parse url URL parameter.
def scores_to_probs(scores, proba, eps=0.01): if np.any(~proba): probs = copy.deepcopy(scores) n_class = len(proba) for m in range(n_class): if not proba[m]: max_extreme_score = max(np.abs(np.min(scores[:,m])),\ np.abs(np.max(sc...
Transforms scores to probabilities by applying the logistic function
def _on_client_latency_changed(self, data): self._clients.get(data.get('id')).update_latency(data)
Handle client latency changed.
def GetSOAPPart(self): head, part = self.parts[0] return StringIO.StringIO(part.getvalue())
Get the SOAP body part.
def load_user_envs(self): installed_packages = self._list_packages() gym_package = 'gym ({})'.format(installed_packages['gym']) if 'gym' in installed_packages else 'gym' core_specs = registry.all() for spec in core_specs: spec.source = 'OpenAI Gym Core Package' sp...
Loads downloaded user envs from filesystem cache on `import gym`
def optimize_no(self): self.optimization = 0 self.relax = False self.gc_sections = False self.ffunction_sections = False self.fdata_sections = False self.fno_inline_small_functions = False
all options set to default
def apool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): return self._pool("apool", pooling_layers.average_pooling2d, k_height, k_wi...
Construct an average pooling layer.
def Y_tighter(self): self.parent.value('y_distance', self.parent.value('y_distance') / 1.4) self.parent.traces.display()
Decrease the distance of the lines.
def clear_cache_delete_selected(modeladmin, request, queryset): result = delete_selected(modeladmin, request, queryset) if not result and hasattr(modeladmin, 'invalidate_cache'): modeladmin.invalidate_cache(queryset=queryset) return result
A delete action that will invalidate cache after being called.
def config_scale(self, cnf={}, **kwargs): self._scale.config(cnf, **kwargs) self._variable.configure(high=self._scale['to'], low=self._scale['from']) if 'orient' in cnf or 'orient' in kwargs: self._grid_widgets()
Configure resources of the Scale widget.
def __addNode(self, name, cls): if name in self.nodes: raise Exception("A node by the name {} already exists. Can't add a duplicate.".format(name)) self.__nxgraph.add_node(name) self.__nxgraph.node[name]['label'] = name self.__nxgraph.node[name]['nodeobj'] = cls() se...
Add a node to the topology
def dispatch(self, *args, **kwargs): return super(QuickEntry, self).dispatch(*args, **kwargs)
Decorate the view dispatcher with permission_required.
def properties_changed(self, properties, changed_properties, invalidated_properties): value = changed_properties.get('Value') if value is not None: self.service.device.characteristic_value_updated(characteristic=self, value=bytes(value))
Called when a Characteristic property has changed.
def process_build_metrics(context, build_processors): build_metrics = OrderedDict() for p in build_processors: p.reset() for p in build_processors: build_metrics.update(p.build_metrics) return build_metrics
use processors to collect build metrics.
def response(self, msgtype, msgid, error, result): self._proxy.response(msgid, error, result)
Handle an incoming response.
def index(): kwdb = current_app.kwdb libraries = get_collections(kwdb, libtype="library") resource_files = get_collections(kwdb, libtype="resource") return flask.render_template("libraryNames.html", data={"libraries": libraries, "ve...
Show a list of available libraries, and resource files
def write_summary_cnts_all(self): cnts = self.get_cnts_levels_depths_recs(set(self.obo.values())) self._write_summary_cnts(cnts)
Write summary of level and depth counts for all active GO Terms.
def _convert_to_identifier_json(self, address_data): if isinstance(address_data, str): return {"slug": address_data} if isinstance(address_data, tuple) and len(address_data) > 0: address_json = {"address": address_data[0]} if len(address_data) > 1: add...
Convert input address data into json format
def check_enum(enum, name=None, valid=None): name = name or 'enum' res = None if isinstance(enum, int): if hasattr(enum, 'name') and enum.name.startswith('GL_'): res = enum.name[3:].lower() elif isinstance(enum, string_types): res = enum.lower() if res is None: ra...
Get lowercase string representation of enum.
def callback_result(self): if self._state == self._PENDING: self._loop.run_until_complete(self) if self._callbacks: result = self._callback_result else: result = self.result() return result
Blocking until the task finish and return the callback_result.until
def execute(self): self._collect_garbage() upstream_channels = {} for node in nx.topological_sort(self.logical_topo): operator = self.operators[node] downstream_channels = self._generate_channels(operator) handles = self.__generate_actors(operator, upstream_ch...
Deploys and executes the physical dataflow.
def template_to_base_path(template, google_songs): if template == os.getcwd() or template == '%suggested%': base_path = os.getcwd() else: template = os.path.abspath(template) song_paths = [template_to_filepath(template, song) for song in google_songs] base_path = os.path.dirname(os.path.commonprefix(song_path...
Get base output path for a list of songs for download.
def fingerprint_from_var(var): vsn = gpg_version() cmd = flatten([gnupg_bin(), gnupg_home()]) if vsn[0] >= 2 and vsn[1] < 1: cmd.append("--with-fingerprint") output = polite_string(stderr_with_input(cmd, var)).split('\n') if not output[0].startswith('pub'): raise CryptoritoError('pro...
Extract a fingerprint from a GPG public key
def humanize_hours(total_hours, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}', negative_frmt=None): seconds = int(float(total_hours) * 3600) return humanize_seconds(seconds, frmt, negative_frmt)
Given time in hours, return a string representing the time.
def _update_axes(ax, xincrease, yincrease, xscale=None, yscale=None, xticks=None, yticks=None, xlim=None, ylim=None): if xincrease is None: pass elif xincrease and ax.xaxis_inverted(): ax.invert_xaxis() elif not xincrease and not ax.xaxis_in...
Update axes with provided parameters
def editor_js_initialization(selector, **extra_settings): init_template = loader.get_template( settings.MARKDOWN_EDITOR_INIT_TEMPLATE) options = dict( previewParserPath=reverse('django_markdown_preview'), **settings.MARKDOWN_EDITOR_SETTINGS) options.update(extra_settings) ctx = d...
Return script tag with initialization code.
def serialize_checks(check_set): check_set_list = [] for check in check_set.all()[:25]: check_set_list.append( { 'datetime': check.checked_datetime.isoformat(), 'value': check.response_time, 'success': 1 if check.success else 0 } ...
Serialize a check_set for raphael
def list(self): service = self._service lxc_names = service.list_names() lxc_list = [] for name in lxc_names: lxc = self.get(name) lxc_list.append(lxc) return lxc_list
Get's all of the LXC's and creates objects for them
def monitor(self): while self.monitor_running.is_set(): if time.time() - self.last_flush > self.batch_time: if not self.queue.empty(): logger.info("Queue Flush: time without flush exceeded") self.flush_queue() time.sleep(self.batch_...
Flushes the queue periodically.
def close(self): if VERBOSE: _print_out('\nDummy_serial: Closing port\n') if not self._isOpen: raise IOError('Dummy_serial: The port is already closed') self._isOpen = False self.port = None
Close a port on dummy_serial.
def _post_build(self, module, encoding): module.file_encoding = encoding self._manager.cache_module(module) for from_node in module._import_from_nodes: if from_node.modname == "__future__": for symbol, _ in from_node.names: module.future_imports.ad...
Handles encoding and delayed nodes after a module has been built
def _get_data_from_list_of_lists(source, fields='*', first_row=0, count=-1, schema=None): if schema is None: schema = google.datalab.bigquery.Schema.from_data(source) fields = get_field_list(fields, schema) gen = source[first_row:first_row + count] if count >= 0 else source cols = [schema.find(name) for nam...
Helper function for _get_data that handles lists of lists.
def _match_magic(self, full_path): for magic in self.magics: if magic.matches(full_path): return magic
Return the first magic that matches this path or None.
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True): graph = tf.get_default_graph() assert graph.unique_name(scope, False) == scope, ( 'Scope "%s" already exists. Provide explicit scope names when ' 'importing multiple instances of the model.') % scope t_input, t_prep_...
Import model GraphDef into the current graph.
def _is_reference(arg): return isinstance(arg, dict) and len(arg) == 1 and isinstance(next(six.itervalues(arg)), six.string_types)
Return True, if arg is a reference to a previously defined statement.
def action(arguments): source_format = (arguments.source_format or fileformat.from_handle(arguments.source_file)) output_format = (arguments.output_format or fileformat.from_handle(arguments.output_file)) with arguments.source_file: sequences = SeqIO.parse( ...
Trim the alignment as specified
def parse_buffer_to_jpeg(data): return [ Image.open(BytesIO(image_data + b'\xff\xd9')) for image_data in data.split(b'\xff\xd9')[:-1] ]
Parse JPEG file bytes to Pillow Image
def load_vstr(buf, pos): slen, pos = load_vint(buf, pos) return load_bytes(buf, slen, pos)
Load bytes prefixed by vint length
def check_config(config): url = config.get("Server", "url") try: urlopen(url) except Exception as e: logger.error( "The configured OpenSubmit server URL ({0}) seems to be invalid: {1}".format(url, e)) return False targetdir = config.get("Execution", "directory") i...
Check the executor config file for consistency.
def remove_droppable(self, droppable_id): updated_droppables = [] for droppable in self.my_osid_object_form._my_map['droppables']: if droppable['id'] != droppable_id: updated_droppables.append(droppable) self.my_osid_object_form._my_map['droppables'] = updated_droppab...
remove a droppable, given the id
def cmd_devid(self, args): for p in self.mav_param.keys(): if p.startswith('COMPASS_DEV_ID'): mp_util.decode_devid(self.mav_param[p], p) if p.startswith('INS_') and p.endswith('_ID'): mp_util.decode_devid(self.mav_param[p], p)
decode device IDs from parameters
def webob_to_django_response(webob_response): from django.http import HttpResponse django_response = HttpResponse( webob_response.app_iter, content_type=webob_response.content_type, status=webob_response.status_code, ) for name, value in webob_response.headerlist: django_...
Returns a django response to the `webob_response`
def correct(self, image, keepSize=False, borderValue=0): image = imread(image) (h, w) = image.shape[:2] mapx, mapy = self.getUndistortRectifyMap(w, h) self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, ...
remove lens distortion from given image
def update(self): if self.input_method == 'local': if self._thread is None: thread_is_running = False else: thread_is_running = self._thread.isAlive() if self.timer_ports.finished() and not thread_is_running: self._thread = Thre...
Update the ports list.
def create_variable(descriptor): if descriptor['type'] == 'continuous': return ContinuousVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1)) elif descriptor['type'] == 'bandit': return BanditVariable(descriptor['name'], descriptor['domain'], descriptor.get('di...
Creates a variable from a dictionary descriptor
def strip_uri(repo): splits = repo.split() for idx in range(len(splits)): if any(splits[idx].startswith(x) for x in ('http://', 'https://', 'ftp://')): splits[idx] = splits[idx].rstrip('/') return ' '.join(splits)
Remove the trailing slash from the URI in a repo definition
def build_ebound_table(self): cols = [ Column(name="E_MIN", dtype=float, data=self._emin, unit='MeV'), Column(name="E_MAX", dtype=float, data=self._emax, unit='MeV'), Column(name="E_REF", dtype=float, data=self._eref, unit='MeV'), Column(name="REF_DNDE", dtype=flo...
Build and return an EBOUNDS table with the encapsulated data.
def connections(self): conn = lambda x: str(x).replace('connection:', '') return [conn(name) for name in self.sections()]
Returns all of the loaded connections names as a list
def _CreateSingleValueCondition(self, value, operator): if isinstance(value, str) or isinstance(value, unicode): value = '"%s"' % value return '%s %s %s' % (self._field, operator, value)
Creates a single-value condition with the provided value and operator.
def column(m, linkpart): assert linkpart in (0, 1, 2, 3) seen = set() for link in m.match(): val = link[linkpart] if val not in seen: seen.add(val) yield val
Generate all parts of links according to the parameter
def _query(self, cmd, *datas): cmd = Command(query=cmd) return cmd.query(self._transport, self._protocol, *datas)
Helper function to allow method queries.
def clean_aliases(ctx, force_yes): inactive_aliases = [] for (alias, mapping) in six.iteritems(aliases_database): if mapping.mapping is None: continue project = ctx.obj['projects_db'].get(mapping.mapping[0], mapping.backend) if (pr...
Removes aliases from your config file that point to inactive projects.
def show(cls, msg=None): if msg: cls.add(msg) cls.overlay.show() cls.overlay.el.bind("click", lambda x: cls.hide()) cls.el.style.display = "block" cls.bind()
Show the log interface on the page.
def from_name_re(cls, path:PathOrStr, fnames:FilePathList, pat:str, valid_pct:float=0.2, **kwargs): "Create from list of `fnames` in `path` with re expression `pat`." pat = re.compile(pat) def _get_label(fn): if isinstance(fn, Path): fn = fn.as_posix() res = pat.search(st...
Create from list of `fnames` in `path` with re expression `pat`.
def audit_ghosts(self): print_header = True for app_name in self._get_ghosts(): if print_header: print_header = False print ( "Found the following in the state database but not " "available as a configured job:" ...
compare the list of configured jobs with the jobs in the state
def which(fname): if "PATH" not in os.environ or not os.environ["PATH"]: path = os.defpath else: path = os.environ["PATH"] for p in [fname] + [os.path.join(x, fname) for x in path.split(os.pathsep)]: p = os.path.abspath(p) if os.access(p, os.X_OK) and not os.path.isdir(p): ...
Find location of executable.
def _get(operation: Operation, url=URL, **params): prepped_request = _prep_get(operation, url=url, **params) return cgi.send(prepped_request)
HTTP GET of the FlashAir command.cgi entrypoint
def _estimate_strains(self): for l in self._profile: l.reset() l.strain = self._motion.pgv / l.initial_shear_vel
Compute an estimate of the strains.
def from_analysis_period(cls, analysis_period, tau_b, tau_d, daylight_savings_indicator='No'): _check_analysis_period(analysis_period) return cls(analysis_period.st_month, analysis_period.st_day, tau_b, tau_d, daylight_savings_indicator)
Initialize a RevisedClearSkyCondition from an analysis_period
def export_data(self): data_tuples = ((key, self._serialize(key, value)) for key, value in six.iteritems(self._data)) data_tuples = filter(lambda t: t[1] is not '', data_tuples) data = dict(data_tuples) return json.dumps(data, separators=(',', ':'))
Exports current data contained in the Task as JSON
def next(self): if self._stopped_iteration: raise StopIteration() while True: try: chunk = self.process._pipe_queue.get(True, 0.001) except Empty: if self.call_args["iter_noblock"]: return errno.EWOULDBLOCK ...
allow us to iterate over the output of our command
def _if(cls, verb): pred = verb.predicate data = verb.data groups = set(_get_groups(verb)) if isinstance(pred, str): if not pred.endswith('_dtype'): pred = '{}_dtype'.format(pred) pred = getattr(pdtypes, pred) elif pdtypes.is_bool_dtype(np....
A verb with a predicate function
def create_dialog(self): self.bbox = QDialogButtonBox(QDialogButtonBox.Close) self.idx_close = self.bbox.button(QDialogButtonBox.Close) self.idx_close.pressed.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addStretch(1) btnlayout.addWidget(self.bbox) lay...
Create the basic dialog.
def freeze(self, number=None): if number is None: number = self.head_layers for idx, child in enumerate(self.model.children()): if idx < number: mu.freeze_layer(child)
Freeze given number of layers in the model