code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def add_case(): ind_ids = request.form.getlist('ind_id') case_id = request.form['case_id'] source = request.form['source'] variant_type = request.form['type'] if len(ind_ids) == 0: return abort(400, "must add at least one member of case") new_case = Case(case_id=case_id, name=case_id, va...
Make a new case out of a list of individuals.
def _update_defaults(self, defaults, old_version, verbose=False): old_defaults = self._load_old_defaults(old_version) for section, options in defaults: for option in options: new_value = options[ option ] try: old_value = old_defaults...
Update defaults after a change in version
def tfds_dir(): return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
Path to tensorflow_datasets directory.
def sys_toolbox_dir(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'esri', 'toolboxes')
Returns this site-package esri toolbox directory.
def command_exit(self, details): log = self._params.get('log', self._discard) pid = self._key status = details why = statusfmt(status) if status: log.warning("pid %d for %s(%s) %s", pid, self._name, self._handler_arg, why) else: log.info("pid %d fo...
Handle the event when a utility command exits.
def inject_environment_variables(self, d): if not d: return d if isinstance(d, six.string_types): return os.path.expandvars(d) for k, v in d.items(): if isinstance(v, six.string_types): d[k] = os.path.expandvars(v) elif isinstance(v...
Recursively injects environment variables into TOML values
def _add_plain_namespace(self, namespace): src_name = namespace.source_name target_name = namespace.dest_name src_names = self._reverse_plain.setdefault(target_name, set()) src_names.add(src_name) if len(src_names) > 1: existing_src = (src_names - set([src_name])).pop...
Add an included and possibly renamed non-wildcard Namespace.
def text2vocab(text, output_file, text2wfreq_kwargs={}, wfreq2vocab_kwargs={}): with tempfile.NamedTemporaryFile(suffix='.wfreq', delete=False) as f: wfreq_file = f.name try: text2wfreq(text, wfreq_file, **text2wfreq_kwargs) wfreq2vocab(wfreq_file, output_file, **wfreq2vocab_kwargs) ...
Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text.
def _help_add_edge(self, u: BaseEntity, v: BaseEntity, attr: Mapping) -> str: self.add_node_from_data(u) self.add_node_from_data(v) return self._help_add_edge_helper(u, v, attr)
Help add a pre-built edge.
def stats_printer(stats_queue): proc_stats = [ProcessStats(i) for i in range(FLAGS.parallel)] print_time = start_time = time.time() width = 107 running = True while running: print_time += 10 while time.time() < print_time: try: s = stats_queue.get(True, print_time - time.time()) ...
A thread that consumes stats_queue and prints them every 10 seconds.
def _connect(self): if self._connParams: self._conn = psycopg2.connect(**self._connParams) else: self._conn = psycopg2.connect('') try: ver_str = self._conn.get_parameter_status('server_version') except AttributeError: ver_str = self.getPar...
Establish connection to PostgreSQL Database.
def write_local_file(self, outputfile, path): self.logger.info("Writing file to %s", path) outputfile.seek(0) with open(path, 'wb') as fd: copyfileobj(outputfile, fd)
Write file to the desired path.
def _propagate_options(self, change): "Set the values and labels, and select the first option if we aren't initializing" options = self._options_full self.set_trait('_options_labels', tuple(i[0] for i in options)) self._options_values = tuple(i[1] for i in options) if self._initi...
Set the values and labels, and select the first option if we aren't initializing
def generate(self, output_dir, catalogue, results, label): data = results.get_raw_data() labels = catalogue.ordered_labels ngrams = self._generate_results(output_dir, labels, data) ngram_table = self._generate_ngram_table(output_dir, labels, data) corpus_table = self._generate_co...
Generates the report, writing it to `output_dir`.
def abort(self, reason): if _debug: ClientSSM._debug("abort %r", reason) self.set_state(ABORTED) abort_pdu = AbortPDU(False, self.invokeID, reason) return abort_pdu
This function is called when the transaction should be aborted.
def search(self, filterstr, attrlist): return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr, attrlist=attrlist, page_size=self.settings.PAGE_SIZE)
Query the configured LDAP server.
def special_mode(v): mode1 = { 0: 'Normal', 1: 'Unknown', 2: 'Fast', 3: 'Panorama', } mode2 = { 0: 'Non-panoramic', 1: 'Left to right', 2: 'Right to left', 3: 'Bottom to top', 4: 'Top to bottom', } if not v or (v[0] not in mode1...
decode Olympus SpecialMode tag in MakerNote
def stop_workers_async(self): self._started = False for worker in self._workers: worker.signal_stop()
Signal that all workers should stop without waiting.
def validate_payment_form(self): warn_untested() form = self.payment_form_cls(self.request.POST) if form.is_valid(): success = form.process(self.request, self.item) if success: return HttpResponseRedirect(self.success_url) else: ...
Try to validate and then process the DirectPayment form.
def stop_process(self): self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
Stops the child process.
def _set_aspect(self, axes, aspect): if ((isinstance(aspect, util.basestring) and aspect != 'square') or self.data_aspect): data_ratio = self.data_aspect or aspect else: (x0, x1), (y0, y1) = axes.get_xlim(), axes.get_ylim() xsize = np.log(x1) - np.log(x0) ...
Set the aspect on the axes based on the aspect setting.
def make(parser): s = parser.add_subparsers( title='commands', metavar='COMMAND', help='description', ) def install_f(args): install(args) install_parser = install_subparser(s) install_parser.set_defaults(func=install_f)
provison Manila Share with HA
def advise(self, item, stop=False): hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE) hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_ADVSTOP if stop else XTYP_ADVSTART, TIMEOUT_ASYNC, LPDWORD()) DDE.FreeStringHandle(self._idInst, hszItem) ...
Request updates when DDE data changes.
def to_jd(year, month, day): return (day + ceil(29.5 * (month - 1)) + (year - 1) * 354 + trunc((3 + (11 * year)) / 30) + EPOCH) - 1
Determine Julian day count from Islamic date
def _add_title(hist: HistogramBase, vega: dict, kwargs: dict): title = kwargs.pop("title", hist.title) if title: vega["title"] = { "text": title }
Display plot title if available.
def _to_query_json(self): json = { 'compression': 'GZIP' if self._compressed else 'NONE', 'ignoreUnknownValues': self._ignore_unknown_values, 'maxBadRecords': self._max_bad_records, 'sourceFormat': self._bq_source_format, 'sourceUris': self._source, } if self._source_format == ...
Return the table as a dictionary to be used as JSON in a query job.
def parse_buffer_to_png(data): images = [] c1 = 0 c2 = 0 data_len = len(data) while c1 < data_len: if data[c2:c2 + 4] == b'IEND' and (c2 + 8 == data_len or data[c2+9:c2+12] == b'PNG'): images.append(Image.open(BytesIO(data[c1:c2 + 8]))) c1 = c2 + 8 c2 = c1...
Parse PNG file bytes to Pillow Image
def jpegtran(ext_args): args = copy.copy(_JPEGTRAN_ARGS) if Settings.destroy_metadata: args += ["-copy", "none"] else: args += ["-copy", "all"] if Settings.jpegtran_prog: args += ["-progressive"] args += ['-outfile'] args += [ext_args.new_filename, ext_args.old_filename] ...
Create argument list for jpegtran.
def validate_image(image, number_tiles): TILE_LIMIT = 99 * 99 try: number_tiles = int(number_tiles) except: raise ValueError('number_tiles could not be cast to integer.') if number_tiles > TILE_LIMIT or number_tiles < 2: raise ValueError('Number of tiles must be between 2 and {} ...
Basic sanity checks prior to performing a split.
def observe(self, algorithm): if self.__observing: raise RuntimeError('This error observer is already observing an algorithm.') if hasattr(algorithm, 'GetExecutive') and algorithm.GetExecutive() is not None: algorithm.GetExecutive().AddObserver(self.event_type, self) algo...
Make this an observer of an algorithm
def bsseval(inargs=None): parser = argparse.ArgumentParser() parser.add_argument( 'reference_dir', type=str ) parser.add_argument( 'estimates_dir', type=str ) parser.add_argument('-o', help='output_dir') parser.add_argument( '--win', type=float, help='...
Generic cli app for bsseval results. Expects two folder with
def setup_method_options(method, tuning_options): kwargs = {} maxiter = numpy.prod([len(v) for v in tuning_options.tune_params.values()]) kwargs['maxiter'] = maxiter if method in ["Nelder-Mead", "Powell"]: kwargs['maxfev'] = maxiter elif method == "L-BFGS-B": kwargs['maxfun'] = maxit...
prepare method specific options
def _encode_dict(self, obj): 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) + '}'
Returns a JSON representation of a Python dict
def _cut_selection(self, *event): if react_to_event(self.view, self.view.editor, event): logger.debug("cut selection") global_clipboard.cut(self.model.selection) return True
Cuts the current selection and copys it to the clipboard.
def assert_no_leftovers(self): leftovers = [] for name in self._members.keys(): if name in self._members and name not in self._documented: leftovers.append(name) if leftovers: raise RuntimeError("%s: undocumented members: %s" % (self._title, ", ".join(leftovers))...
Generate an error if there are leftover members.
def available(self) -> bool: is_available = self.api.online and \ next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'online') == "True" return is_available
Return if device is online or not.
def chain_getattr(obj, attr, value=None): try: return _resolve_value(safe_chain_getattr(obj, attr)) except AttributeError: return value
Get chain attribute for an object.
def _concat_bgzip_fastq(finputs, out_dir, read, ldetail): out_file = os.path.join(out_dir, "%s_%s.fastq.gz" % (ldetail["name"], read)) if not utils.file_exists(out_file): with file_transaction(out_file) as tx_out_file: subprocess.check_call("zcat %s | bgzip -c > %s" % (" ".join(finputs), tx_...
Concatenate multiple input fastq files, preparing a bgzipped output file.
def _expr2bddnode(expr): if expr.is_zero(): return BDDNODEZERO elif expr.is_one(): return BDDNODEONE else: top = expr.top _ = bddvar(top.names, top.indices) root = top.uniqid lo = _expr2bddnode(expr.restrict({top: 0})) hi = _expr2bddnode(expr.restrict(...
Convert an expression into a BDD node.
def format_BLB(): rc("figure", facecolor="white") rc('font', family = 'serif', size=10) rc('xtick', labelsize=10) rc('ytick', labelsize=10) rc('axes', linewidth=1) rc('xtick.major', size=4, width=1) rc('xtick.minor', size=2, width=1) rc('ytick.major', size=4, width=1) rc('yti...
Sets some formatting options in Matplotlib.
def _interp(self): if np.all(self.hrow_indices == self.row_indices): return self._interp1d() xpoints, ypoints = np.meshgrid(self.hrow_indices, self.hcol_indices) for num, data in enumerate(self.tie_data): spl = RectBivariateSpline(se...
Interpolate the cartesian coordinates.
async def get(self, request): form = await self.get_form(request) ctx = dict(active=self, form=form, request=request) if self.resource: return self.app.ps.jinja2.render(self.template_item, **ctx) return self.app.ps.jinja2.render(self.template_list, **ctx)
Get collection of resources.
def show(self): bytecode._Print("MAP_LIST SIZE", self.size) for i in self.map_item: if i.item != self: i.show()
Print with a pretty display the MapList object
def page_count(self): postcount = self.post_set.count() max_pages = (postcount / get_paginate_by()) if postcount % get_paginate_by() != 0: max_pages += 1 return max_pages
Get count of total pages
def print_status(self): tweets = self.received now = time.time() diff = now - self.since self.since = now self.received = 0 if diff > 0: logger.info("Receiving tweets at %s tps", tweets / diff)
Print out the current tweet rate and reset the counter
def main_loop(self): while True: for e in pygame.event.get(): self.handle_event(e) self.step() pygame.time.wait(5)
Runs the main game loop.
def patch(self): original = self.__dict__['__original__'] return jsonpatch.make_patch(original, dict(self)).to_string()
Return a jsonpatch object representing the delta
def update(self): stats = self.get_init_value() if self.input_method == 'local': stats = self.glancesgrabhddtemp.get() else: pass self.stats = stats return self.stats
Update HDD stats using the input method.
def matrix_str(p, decimal_places=2, print_zero=True, label_columns=False): return '[{0}]'.format("\n ".join([(str(i) if label_columns else '') + vector_str(a, decimal_places, print_zero) for i, a in enumerate(p)]))
Pretty-print the matrix.
def _compute_bgid(self, bg=None): if bg is None: bg = self._bgdata if isinstance(bg, qpimage.QPImage): if "identifier" in bg: return bg["identifier"] else: data = [bg.amp, bg.pha] for key in sorted(list(bg.meta.keys())):...
Return a unique identifier for the background data
def cfg_from_file(self, yaml_filename, config_dict): import yaml from easydict import EasyDict as edict with open(yaml_filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) return self._merge_a_into_b(yaml_cfg, config_dict)
Load a config file and merge it into the default options.
def response_builder(self, response): try: r = response.json() result = r['query']['results'] response = { 'num_result': r['query']['count'] , 'result': result } except (Exception,) as e: print(e) ret...
Try to return a pretty formatted response object
def _start_reader(self): while True: message = yield From(self.pipe.read_message()) self._process(message)
Read messages from the Win32 pipe server and handle them.
def instance_query_movie_ids(self) -> List[str]: completions_with_desc = [] for movie_id in utils.natural_sort(self.MOVIE_DATABASE_IDS): if movie_id in self.MOVIE_DATABASE: movie_entry = self.MOVIE_DATABASE[movie_id] completions_with_desc.append(argparse_compl...
Demonstrates showing tabular hinting of tab completion information
def makeLambdaPicklable(lambda_function): if isinstance(lambda_function, type(lambda: None)) and lambda_function.__name__ == '<lambda>': def __reduce_ex__(proto): return unpickleLambda, (marshal.dumps(lambda_function.__code__), ) lambda_function.__reduce_ex__ = __reduce...
Take input lambda function l and makes it picklable.
def error(bot, update, error): logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"})
Log Errors caused by Updates.
def duration_minutes(duration): if isinstance(duration, list): res = dt.timedelta() for entry in duration: res += entry return duration_minutes(res) elif isinstance(duration, dt.timedelta): return duration.total_seconds() / 60 else: return duration
returns minutes from duration, otherwise we keep bashing in same math
def perform_flag(request, comment): flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.SUGGEST_REMOVAL ) signals.comment_was_flagged.send( sender = comment.__class__, com...
Actually perform the flagging of a comment from a request.
def bt_addr_to_string(addr): addr_str = array.array('B', addr) addr_str.reverse() hex_str = hexlify(addr_str.tostring()).decode('ascii') return ':'.join(a+b for a, b in zip(hex_str[::2], hex_str[1::2]))
Convert a binary string to the hex representation.
def read_messages(fobj, magic_table): messages = [] while True: magic = read_magic(fobj) if not magic: break func = magic_table.get(magic) if func is not None: messages.append(func(fobj)) else: log.error('Unknown magic: ' + str(' '.join...
Read messages from a file-like object until stream is exhausted.
def update(self): params = {} return self.send( url=self._base_url + 'update', method='POST', json=params )
Sync up changes to reminders.
def dispatch_failed(self, context): traceback.print_exception( context.exc_type, context.exc_value, context.traceback) raise SystemExit(1)
Print the unhandled exception and exit the application.
def js_to_url_function(converter): if hasattr(converter, 'js_to_url_function'): data = converter.js_to_url_function() else: for cls in getmro(type(converter)): if cls in js_to_url_functions: data = js_to_url_functions[cls](converter) break else...
Get the JavaScript converter function from a rule.
def _add_job_from_spec(self, job_json, use_job_id=True): job_id = (job_json['job_id'] if use_job_id else self.backend.get_new_job_id()) self.add_job(str(job_json['name']), job_id) job = self.get_job(job_json['name']) if job_json.get('cron_schedule', No...
Add a single job to the Dagobah from a spec.
def check_snmp(self): from glances.snmp import GlancesSNMPClient clientsnmp = GlancesSNMPClient(host=self.args.client, port=self.args.snmp_port, version=self.args.snmp_version, community=...
Chek if SNMP is available on the server.
def _process_items(cls, vals): "Processes list of items assigning unique paths to each." if type(vals) is cls: return vals.data elif not isinstance(vals, (list, tuple)): vals = [vals] items = [] counts = defaultdict(lambda: 1) cls._unpack_paths(val...
Processes list of items assigning unique paths to each.
def colorize(string, stack): codes = optimize(stack) if len(codes): prefix = SEQ % ';'.join(map(str, codes)) suffix = SEQ % STYLE.reset return prefix + string + suffix else: return string
Apply optimal ANSI escape sequences to the string.
def dt2decyear(dt): year = dt.year startOfThisYear = datetime(year=year, month=1, day=1) startOfNextYear = datetime(year=year+1, month=1, day=1) yearElapsed = sinceEpoch(dt) - sinceEpoch(startOfThisYear) yearDuration = sinceEpoch(startOfNextYear) - sinceEpoch(startOfThisYear) fraction = yearElap...
Convert datetime to decimal year
def add_signal_handler(): import signal def handler(sig, frame): if sig == signal.SIGINT: librtmp.RTMP_UserInterrupt() raise KeyboardInterrupt signal.signal(signal.SIGINT, handler)
Adds a signal handler to handle KeyboardInterrupt.
def adjustHeadingPointer(self): self.headingText.set_text(str(self.heading)) self.headingText.set_size(self.fontSize)
Adjust the value of the heading pointer.
def clear(actor=()): if not settings.plotter_instance: return settings.plotter_instance.clear(actor) return settings.plotter_instance
Clear specific actor or list of actors from the current rendering window.
def rsl_push_many_readings(self, value, count, stream_id): for i in range(1, count+1): err = self.sensor_log.push(stream_id, 0, value) if err != Error.NO_ERROR: return [err, i] return [Error.NO_ERROR, count]
Push many copies of a reading to the RSL.
def idxstats(in_bam, data): index(in_bam, data["config"], check_timestamp=False) AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"]) samtools = config_utils.get_program("samtools", data["config"]) idxstats_out = subprocess.check_output([samtools, "idxstats", in_...
Return BAM index stats for the given file, using samtools idxstats.
def token_gen_call(username, password): secret_key = 'super-secret-key-please-change' mockusername = 'User2' mockpassword = 'Mypassword' if mockpassword == password and mockusername == username: return {"token" : jwt.encode({'user': username, 'data': 'mydata'}, secret_key, algorithm='HS256')} ...
Authenticate and return a token
def restart(self, key): if key in self.queue: if self.queue[key]['status'] in ['failed', 'done']: new_entry = {'command': self.queue[key]['command'], 'path': self.queue[key]['path']} self.add_new(new_entry) self.write() ...
Restart a previously finished entry.
def create_scheduler_file(scheduler: str, job: Job) -> str: logger.debug("Create Scheduler File Function") if job.scheduler_options is None: scheduler_options: Dict[str, Any] = {} else: scheduler_options = deepcopy(job.scheduler_options) try: setup_string = parse_setup(scheduler_...
Substitute values into a template scheduler file.
def filter_by_key(self, keys, ID=None): keys = to_list(keys) fil = lambda x: x in keys if ID is None: ID = self.ID return self.filter(fil, applyto='keys', ID=ID)
Keep only Measurements with given keys.
def delete(self): for field_name in self._fields: field = self.get_field(field_name) if not isinstance(field, PKField): field.delete() self.connection.srem(self.get_field('pk').collection_key, self._pk) delattr(self, "_pk")
Delete the instance from redis storage.
def add_request_session(self): session = new_request_session(self.config, self.cookies) self.request_sessions[thread.get_ident()] = session
Add a request session for current thread.
def spaceout_and_resize_panels(self): figure = self.figure theme = self.theme try: aspect_ratio = theme.themeables.property('aspect_ratio') except KeyError: aspect_ratio = self.coordinates.aspect( self.layout.panel_params[0]) if aspect_...
Adjust the space between the panels
def OnLineColor(self, event): color = event.GetValue().GetRGB() borders = self.bordermap[self.borderstate] post_command_event(self, self.BorderColorMsg, color=color, borders=borders)
Line color choice event handler
def _spherical_to_cartesian(cls, coord, center): r, theta, phi, r_dot, theta_dot, phi_dot = coord x = r * cos(phi) * cos(theta) y = r * cos(phi) * sin(theta) z = r * sin(phi) vx = r_dot * x / r - y * theta_dot - z * phi_dot * cos(theta) vy = r_dot * y / r + x * theta_dot ...
Spherical to cartesian conversion
def _router_request(router, method, data=None): if router not in ROUTERS: return False req_data = salt.utils.json.dumps([dict( action=router, method=method, data=data, type='rpc', tid=1)]) config = __salt__['config.option']('zenoss') log.debug('Making requ...
Make a request to the Zenoss API router
def transformer_tall_finetune_textclass(): hparams = transformer_tall() hparams.learning_rate_constant = 6.25e-5 hparams.learning_rate_schedule = ("linear_warmup*constant*linear_decay") hparams.multiproblem_schedule_max_examples = 0 hparams.multiproblem_target_eval_only = True hparams.learning_rate_warmup_s...
Hparams for transformer on LM for finetuning on text class problems.
def _write_header(self): self.output_buffer += serialize_header(header=self._header, signer=self.signer) self.output_buffer += serialize_header_auth( algorithm=self._encryption_materials.algorithm, header=self.output_buffer, data_encryption_key=self._derived_data_key,...
Builds the message header and writes it to the output stream.
def _is_scope_prefix(scope_name, prefix_name): if not prefix_name: return True if not scope_name.endswith("/"): scope_name += "/" if not prefix_name.endswith("/"): prefix_name += "/" return scope_name.startswith(prefix_name)
Checks that `prefix_name` is a proper scope prefix of `scope_name`.
def template(ctx, url, no_input, role_name): command_args = { 'role_name': role_name, 'subcommand': __name__, 'url': url, 'no_input': no_input, } t = Template(command_args) t.execute()
Initialize a new role from a Cookiecutter URL.
def _get_implied_apps(self, detected_apps): def __get_implied_apps(apps): _implied_apps = set() for app in apps: try: _implied_apps.update(set(self.apps[app]['implies'])) except KeyError: pass return _imp...
Get the set of apps implied by `detected_apps`.
def _void_array_to_list(restuple, _func, _args): shape = (restuple.e.len, 1) array_size = np.prod(shape) mem_size = 8 * array_size array_str_e = string_at(restuple.e.data, mem_size) array_str_n = string_at(restuple.n.data, mem_size) ls_e = np.frombuffer(array_str_e, float, array_size).tolist() ...
Convert the FFI result to Python data structures
def _get_form(self, config_name, only_required=False): if getattr(self, config_name, None): return import_object_by_string(getattr(self, config_name)) def use_field(field): if not only_required: return True return field.default == NOT_PROVIDED ...
Get form for given config else create form
def masked(self) -> np.ndarray: arr = self[:] arr.shape = self.shape arr = wt_kit.share_nans(arr, *self.parent.channels)[0] return np.nanmean( arr, keepdims=True, axis=tuple(i for i in range(self.ndim) if self.shape[i] == 1) )
Axis expression evaluated, and masked with NaN shared from data channels.
def count_packages(self): packages = [] for pkg in self.dmap.values(): packages += pkg self.count_dep += 1 self.count_pkg = len(set(packages))
Count dependencies and packages
def merge_dicts(d1, d2): merged = copy.deepcopy(d1) deep_update(merged, d2, True, []) return merged
Returns a new dict that is d1 and d2 deep merged.
def get(cls, **kwargs): data = cls._get(**kwargs) if data is None: new = cls() new.from_miss(**kwargs) return new return cls.deserialize(data)
Get a copy of the type from the cache and reconstruct it.
def instances_changed(self): value = bool(lib.EnvGetInstancesChanged(self._env)) lib.EnvSetInstancesChanged(self._env, int(False)) return value
True if any instance has changed.
def publish_page(page, languages): for language_code, lang_name in iter_languages(languages): url = page.get_absolute_url() if page.publisher_is_draft: page.publish(language_code) log.info('page "%s" published in %s: %s', page, lang_name, url) else: log.in...
Publish a CMS page in all given languages.
def enable_torque(self, ids): self._set_torque_enable(dict(zip(ids, itertools.repeat(True))))
Enables torque of the motors with the specified ids.
def _scene(self): return _EmbreeWrap(vertices=self.mesh.vertices, faces=self.mesh.faces, scale=self._scale)
A cached version of the pyembree scene.
def pip_install(package, fatal=False, upgrade=False, venv=None, constraints=None, **options): if venv: venv_python = os.path.join(venv, 'bin/pip') command = [venv_python, "install"] else: command = ["install"] available_options = ('proxy', 'src', 'log', 'index-url', )...
Install a python package
def add_slices(self, dashboard_id): data = json.loads(request.form.get('data')) session = db.session() Slice = models.Slice dash = ( session.query(models.Dashboard).filter_by(id=dashboard_id).first()) check_ownership(dash, raise_if_false=True) new_slices = ses...
Add and save slices to a dashboard