Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
375,100
def require_template_debug(f): def _(*args, **kwargs): TEMPLATE_DEBUG = getattr(settings, , False) return f(*args, **kwargs) if TEMPLATE_DEBUG else return _
Decorated function is a no-op if TEMPLATE_DEBUG is False
375,101
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second): if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError(.format( fraction_of_second)) milliseconds = int(fraction_of_second * definitions.MILLISECONDS_PER_SECOND) return .format( time_el...
Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a ...
375,102
def do_db(self, arg): if arg[]: self.db_get_config() elif arg[]: self.db_use_local_file(arg, filename=arg[]) elif arg[]: self.db_use_aws_instance(arg[], arg) elif arg[]: self.db_aws_list_regions() elif arg[]: se...
Usage: db get_config db use_local_file [<filename>] db use_aws_instance [<instance_id>] db aws_list_regions db aws_get_region db aws_set_region [<region_name>] db aws_list_instances db aws_create_instance [<instance_id> <size> <username> <p...
375,103
def get_POST_data(self): self._postprocess() self._apply_mapping( self.mapping.get(self._POST["P0502010__b"], self.mapping["else"]) ) self._check_required_fields() return self._POST
Returns: dict: POST data, which can be sent to webform using \ :py:mod:`urllib` or similar library
375,104
def until(self, regex): logger.debug(, regex) r = re.compile(regex, re.M) self.tn.expect([r])
Wait until the regex encountered
375,105
def create_app(app_name, config={}, db=None, celery=None): track_mode = os.environ[] == if track_mode: print() active_db = os.environ[] == if track_mode: print() from webargs.flaskparser import parser from . import error_handler, hacker, cli hacker.hack_webargs() ...
App Factory 工具 策略是: - 初始化app - 根据app_name,装载指定的模块 - 尝试装载app.run_app - 如果指定了`FANTASY_PRIMARY_NODE`,则尝试进行migrate操作 - 装载error handler :return:
375,106
def start_with(self, x): _args = [] for arg in self.all: if _is_collection(x): for _x in x: if arg.startswith(x): _args.append(arg) break else: if arg.startswith(x): ...
Returns all arguments beginning with given string (or list thereof).
375,107
def read_uint16(self): if self.pos + 2 > self.remaining_length: return NC.ERR_PROTOCOL msb = self.payload[self.pos] self.pos += 1 lsb = self.payload[self.pos] self.pos += 1 word = (msb << 8) + lsb return NC.ERR_SUCCESS, word
Read 2 bytes.
375,108
def find_matching_endpoints(self, discovery_ns): def match_func(operation, ns, rule): return operation in self.matching_operations return list(iter_endpoints(self.graph, match_func))
Compute current matching endpoints. Evaluated as a property to defer evaluation.
375,109
def run_analysis(self, argv): args = self._parser.parse_args(argv) if not HAVE_ST: raise RuntimeError( "Trying to run fermipy analysis, but donverbosityworkdir_regex\.xml$|\.npy$basenorm') gta.fit(covar=True) gta.print_roi() gta.print_params(...
Run this analysis
375,110
def train_cv(self, num_folds, fold, random=None): if random is None: return Instances( javabridge.call(self.jobject, "trainCV", "(II)Lweka/core/Instances;", num_folds, fold)) else: return Instances( javabrid...
Generates a training fold for cross-validation. :param num_folds: the number of folds of cross-validation, eg 10 :type num_folds: int :param fold: the current fold (0-based) :type fold: int :param random: the random number generator :type random: Random :return: ...
375,111
def _antenna_uvw(uvw, antenna1, antenna2, chunks, nr_of_antenna): if antenna1.ndim != 1: raise ValueError("antenna1 shape should be (row,)") if antenna2.ndim != 1: raise ValueError("antenna2 shape should be (row,)") if uvw.ndim != 2 or uvw.shape[1] != 3: raise ValueError("uvw...
numba implementation of antenna_uvw
375,112
def _fileobj_to_fd(fileobj): if isinstance(fileobj, int): fd = fileobj else: try: fd = int(fileobj.fileno()) except (AttributeError, TypeError, ValueError): raise ValueError("Invalid file object: {0!r}".format(fileobj)) if fd < 0: raise ValueError...
Return a file descriptor from a file object. If given an integer will simply return that integer back.
375,113
def mget(self, ids, index=None, doc_type=None, **query_params): if not ids: return [] body = [] for value in ids: if isinstance(value, tuple): if len(value) == 3: a, b, c = value body.append({"_index": a, ...
Get multi JSON documents. ids can be: list of tuple: (index, type, id) list of ids: index and doc_type are required
375,114
def mpl_get_cb_bound_below_plot(ax): position = ax.get_position() figW, figH = ax.get_figure().get_size_inches() fig_aspect = figH / figW box_aspect = ax.get_data_ratio() pb = position.frozen() pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect).bounds ax_size = ax.get_position().bo...
Return the coordinates for a colorbar axes below the provided axes object. Take into account the changes of the axes due to aspect ratio settings. Parts of this code are taken from the transforms.py file from matplotlib Important: Use only AFTER fig.subplots_adjust(...) Use as: =======
375,115
def check_labels_file_header(filename): with tf.gfile.Open(filename, ) as f: magic = read32(f) read32(f) if magic != 2049: raise ValueError( % (magic, f.name))
Validate that filename corresponds to labels for the MNIST dataset.
375,116
def _check_embedded_object(embedded_object, type, value, element_kind, element_name): if embedded_object not in (, ): raise ValueError( _format("{0} {1!A} specifies an invalid value for " "embedded_object: {2!A} (must be or )", ...
Check whether embedded-object-related parameters are ok.
375,117
def imap(requests, stream=False, size=2, exception_handler=None): pool = Pool(size) def send(r): return r.send(stream=stream) for request in pool.imap_unordered(send, requests): if request.response is not None: yield request.response elif exception_handler: ...
Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. default is 2 :param exception_h...
375,118
def update_lazyevals(self): if self.lazy_evals is None: return elif isinstance(self.lazy_evals, LazyEval): self.lazy_evals.get_updated() else: for lz in self.lazy_evals: lz.get_updated()
Update all LazyEvals in self self.lzy_evals must be set to LazyEval object(s) enough to update all owned LazyEval objects.
375,119
def _prune_maps_to_sequences(self): B 3 for c, seq in self.atom_sequences.iteritems(): res_ids = [r[0] for r in seq] for_removal = [] for k, _, _ in self.atom_to_seqres_sequence_maps[c]: if k not in res_ids: for_removal.append(k...
When we merge the SIFTS maps, we can extend the sequence maps such that they have elements in their domain that we removed from the sequence e.g. 1A2P, residue 'B 3 ' is removed because Rosetta barfs on it. Here, we prune the maps so that their domains do not have elements that were removed fr...
375,120
def add(self, child): if isinstance(child, StateVariable): self.add_state_variable(child) elif isinstance(child, DerivedVariable): self.add_derived_variable(child) elif isinstance(child, ConditionalDerivedVariable): self.add_conditional_derived_varia...
Adds a typed child object to the behavioral object. @param child: Child object to be added.
375,121
def copy(self, empty=False): newobject = self.__new__(self.__class__) if empty: return for prop in ["_properties","_side_properties", "_derived_properties","_build_properties" ]: if pro...
returns an independent copy of the current object.
375,122
def scp(args): if args.scp_args[0] == "--": del args.scp_args[0] user_or_hostname_chars = string.ascii_letters + string.digits for i, arg in enumerate(args.scp_args): if arg[0] in user_or_hostname_chars and ":" in arg: hostname, colon, path = arg.partition(":") u...
Transfer files to or from EC2 instance. Use "--" to separate scp args from aegea args: aegea scp -- -r local_dir instance_name:~/remote_dir
375,123
def setCommonInput(configObj, createOutwcs=True): if not in configObj: configObj[] = False if not createOutwcs or not configObj[]: reportResourceUsage(imageObjectList, outwcs, num_cores) except ValueError: imageObjectList = None return imageObjectList,...
The common interface interpreter for MultiDrizzle tasks which not only runs 'process_input()' but 'createImageObject()' and 'defineOutput()' as well to fully setup all inputs for use with the rest of the MultiDrizzle steps either as stand-alone tasks or internally to MultiDrizzle itself. Parameters ...
375,124
def next_frame_savp_gan(): hparams = next_frame_savp() hparams.use_gan = True hparams.use_vae = False hparams.gan_loss_multiplier = 0.001 hparams.optimizer_adam_beta1 = 0.5 hparams.learning_rate_constant = 2e-4 hparams.gan_loss = "cross_entropy" hparams.learning_rate_decay_steps = 100000 hparams.le...
SAVP - GAN only model.
375,125
def set_iscsi_info(self, target_name, lun, ip_address, port=, auth_method=None, username=None, password=None): return self._call_method(, target_name, lun, ip_address, port, auth_method, username, ...
Set iscsi details of the system in uefi boot mode. The initiator system is set with the target details like IQN, LUN, IP, Port etc. :param target_name: Target Name for iscsi. :param lun: logical unit number. :param ip_address: IP address of the target. :param port: port ...
375,126
def import_parameters_from_file(parameters_file): params = {} with open(parameters_file, ) as f: matches = re.findall(, f.read()) for m in matches: params[m[0]] = ast.literal_eval(m[1]) return params
Try importing a parameter dictionary from file. We expect values in parameters_file to be defined as follows: param1: value1 param2: [value2, value3]
375,127
def shapeRef_to_iriref(self, ref: ShExDocParser.ShapeRefContext) -> ShExJ.IRIREF: if ref.ATPNAME_NS(): return ShExJ.IRIREF(self._lookup_prefix(ref.ATPNAME_NS().getText()[1:])) elif ref.ATPNAME_LN(): prefix, local = ref.ATPNAME_LN().getText()[1:].split(, 1) re...
shapeRef: ATPNAME_NS | ATPNAME_LN | '@' shapeExprLabel
375,128
def list_sensors(parent_class, sensor_items, filter, strategy, status, use_python_identifiers, tuple, refresh): filter_re = re.compile(filter) found_sensors = [] none_strat = resource.normalize_strategy_parameters() sensor_dict = dict(sensor_items) for sensor_identifier in sort...
Helper for implementing :meth:`katcp.resource.KATCPResource.list_sensors` Parameters ---------- sensor_items : tuple of sensor-item tuples As would be returned the items() method of a dict containing KATCPSensor objects keyed by Python-identifiers. parent_class: KATCPClientResource or ...
375,129
def create_process(cmd, root_helper=None, addl_env=None, log_output=True): if root_helper: cmd = shlex.split(root_helper) + cmd cmd = map(str, cmd) log_output and LOG.info("Running command: %s", cmd) env = os.environ.copy() if addl_env: env.update(addl_env) obj = subproces...
Create a process object for the given command. The return value will be a tuple of the process object and the list of command arguments used to create it.
375,130
def _setup_no_fallback(parser): cli_dest = halp = ( s built-in default logic.{0} plugin options--tox-pyenv-no-fallback-Fstore_falseIf `pyenv which {basepython}` exits non-zero when looking up the python executable, allow fallback to tox\ ), )
Add the option, --tox-pyenv-no-fallback. If this option is set, do not allow fallback to tox's built-in strategy for looking up python executables if the call to `pyenv which` by this plugin fails. This will allow the error to raise instead of falling back to tox's default behavior.
375,131
def _mark_lines(lines, sender): global EXTRACTOR candidate = get_signature_candidate(lines) markers = list( * len(lines)) for i, line in reversed(list(enumerate(candidate))): j = len(lines) - len(candidate) + i if not line.strip(): ...
Mark message lines with markers to distinguish signature lines. Markers: * e - empty line * s - line identified as signature * t - other i.e. ordinary text line >>> mark_message_lines(['Some text', '', 'Bob'], 'Bob') 'tes'
375,132
def bam2fastq(self, input_bam, output_fastq, output_fastq2=None, unpaired_fastq=None): self._ensure_folders(output_fastq, output_fastq2, unpaired_fastq) cmd = self.tools.java + " -Xmx" + self.pm.javamem cmd += " -jar " + self.tools.picard + " SamToFastq" cmd +=...
Create command to convert BAM(s) to FASTQ(s). :param str input_bam: Path to sequencing reads file to convert :param output_fastq: Path to FASTQ to write :param output_fastq2: Path to (R2) FASTQ to write :param unpaired_fastq: Path to unpaired FASTQ to write :return str: Command ...
375,133
def slip_reader(port, trace_function): partial_packet = None in_escape = False while True: waiting = port.inWaiting() read_bytes = port.read(1 if waiting == 0 else waiting) if read_bytes == b: waiting_for = "header" if partial_packet is None else "content" ...
Generator to read SLIP packets from a serial port. Yields one full SLIP packet at a time, raises exception on timeout or invalid data. Designed to avoid too many calls to serial.read(1), which can bog down on slow systems.
375,134
def generate(self): key = self._propose_new_key() while self.key_exists(key): _logger.warning( ) key = self._propose_new_key() return key
Generate a new string and return it.
375,135
def set_auto_reply(self, message, status=AutoReplyStatus.ALWAYS_ENABLED, start=None, end=None, external_message=None, audience=AutoReplyAudience.ALL): start_is_none = start is None end_is_none = end is None if (not start_is_none and end_is_none) or (sta...
Set an automatic reply for the account. Args: message (str): The message to be sent in replies. If external_message is provided this is the message sent to internal recipients status (OutlookAccount.AutoReplyStatus): Whether the auto-reply should be always enabled, scheduled,...
375,136
def get_player_id(player): players_df = get_all_player_ids("all_data") player = players_df[players_df.DISPLAY_LAST_COMMA_FIRST == player] if len(player) == 0: er = "Invalid player name passed or there is no player with that name." raise ValueError(er) player_id = player.PERSON_...
Returns the player ID(s) associated with the player name that is passed in. There are instances where players have the same name so there are multiple player IDs associated with it. Parameters ---------- player : str The desired player's name in 'Last Name, First Name' format. Passing in ...
375,137
def _headers(self, **kwargs): headers = BASE_HEADERS.copy() if self._token: headers[] = self._token headers.update(kwargs) return headers
Returns dict containing base headers for all requests to the server.
375,138
def save(self, filename, content): with open(filename, "w") as f: if hasattr(content, ): f.write(.join([row for row in content])) else: print() f.write(str(content))
default is to save a file from list of lines
375,139
def update(self, data): updated = self.set_property(, data.description) updated |= self.set_property(, data.state) tags = {x[]: x[] for x in data.tags or {}} existing_tags = {x.key: x for x in self.tags} for key, value in list(tags.items()): update...
Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(ami)` on the object. Args: data (bunch): Data fetched from AWS ...
375,140
def ontologyShapeTree(self): treedict = {} if self.all_shapes: treedict[0] = self.toplayer_shapes for element in self.all_shapes: if element.children(): treedict[element] = element.children() return treedict return ...
Returns a dict representing the ontology tree Top level = {0:[top properties]} Multi inheritance is represented explicitly
375,141
def group_experiments(experiments: TomographyExperiment, method: str = ) -> TomographyExperiment: allowed_methods = [, ] assert method in allowed_methods, f" should be one of {allowed_methods}." if method == : return group_experiments_greedy(experiments) elif method ==...
Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number of QPU runs. Background ---------- Given some PauliTerm operator, the 'natural' tensor product basis to diagonalize this term is the one which diagonalizes each Pauli operator in the product term-by-t...
375,142
def _neg32(ins): output = _32bit_oper(ins.quad[2]) output.append() output.append() output.append() REQUIRES.add() return output
Negates top of the stack (32 bits in DEHL)
375,143
def _process_model_dict(self, d): del d[] del d[] del d[] del d[] del d[] del d[] del d[] del d[] del d[] del d[] del d[] del d[] if d[] == self.default_model_expr: del d[] d["name"] = ...
Remove redundant items from a model's configuration dict. Parameters ---------- d : dict Modified in place. Returns ------- dict Modified `d`.
375,144
def _is_valid_integer(self, inpt, metadata): if not isinstance(inpt, int): return False if metadata.get_minimum_integer() and inpt < metadata.get_maximum_integer(): return False if metadata.get_maximum_integer() and inpt > metadata.get_minimum_integer(): ...
Checks if input is a valid integer value
375,145
def received_message(self, message): if message.data.decode() == : self.pipe.send(message) self.send(, False)
Checks if the client has sent a ready message. A ready message causes ``send()`` to be called on the ``parent end`` of the pipe. Clients need to ensure that the pipe assigned to ``self.pipe`` is the ``parent end`` of a pipe. This ensures completion of the underlying websocket c...
375,146
def _append_path(new_path): for path in sys.path: path = os.path.abspath(path) if new_path == path: return sys.path.append(new_path)
Given a path string, append it to sys.path
375,147
def avail_images(call=None): if call == : raise SaltCloudSystemExit( ) ret = {} conn = get_conn() response = conn.getCreateObjectOptions() for image in response[]: ret[image[][][]] = { : image[][][], : image[][], ...
Return a dict of all available VM images on the cloud provider.
375,148
def unlink(self): links = self.registry.get(self.source) if self in links: links.pop(links.index(self))
Unregisters the Link
375,149
def level(self): ev = self._query_waiters.request(self.__do_query_level) ev.wait(1.0) return self._level
Returns the current output level by querying the remote controller.
375,150
def _log_likelihood_per_sample(X, means, covars): logden = _log_multivariate_density(X, means, covars) logden_max = logden.max(axis=1) log_likelihood = np.log(np.sum(np.exp(logden.T - logden_max) + Epsilon, axis=0)) log_likelihood += logden_max post_proba = np.exp(logden - log_likelihood...
Theta = (theta_1, theta_2, ... theta_M) Likelihood of mixture parameters given data: L(Theta | X) = product_i P(x_i | Theta) log likelihood: log L(Theta | X) = sum_i log(P(x_i | Theta)) and note that p(x_i | Theta) = sum_j prior_j * p(x_i | theta_j) Probability of sample x being generated fro...
375,151
def normalize_ident(ident): if isinstance(ident, tuple) and len(ident) == 2: return ident[0], ident[1] else: return ident, None
Splits a generic identifier. If ``ident`` is a tuple, then ``(ident[0], ident[1])`` is returned. Otherwise, ``(ident[0], None)`` is returned.
375,152
def _getColumnNeighborhood(self, centerColumn): if self._wrapAround: return topology.wrappingNeighborhood(centerColumn, self._inhibitionRadius, self._columnDimensions) else: return topology.neighborhood(cente...
Gets a neighborhood of columns. Simply calls topology.neighborhood or topology.wrappingNeighborhood A subclass can insert different topology behavior by overriding this method. :param centerColumn (int) The center of the neighborhood. @returns (1D numpy array of integers) The columns in the ...
375,153
def _build_resolver(cls, session: AppSession): args = session.args dns_timeout = args.dns_timeout if args.timeout: dns_timeout = args.timeout if args.inet_family == : family = IPFamilyPreference.ipv4_only elif args.inet_family == : f...
Build resolver.
375,154
def multi_pop(d, *args): retval = {} for key in args: if key in d: retval[key] = d.pop(key) return retval
pops multiple keys off a dict like object
375,155
def read_unsigned_var_int(file_obj): result = 0 shift = 0 while True: byte = struct.unpack(b"<B", file_obj.read(1))[0] result |= ((byte & 0x7F) << shift) if (byte & 0x80) == 0: break shift += 7 return result
Read a value using the unsigned, variable int encoding.
375,156
def isEnabled( self ): if ( self._disableWithLayer and self._layer ): lenabled = self._layer.isEnabled() else: lenabled = True return self._enabled and lenabled
Returns whether or not this node is enabled.
375,157
def robust_topological_sort(graph: Graph) -> list: assert check_argument_types() components = strongly_connected_components(graph) node_component = {} for component in components: for node in component: node_component[node] = component component_graph = {} for component in components: component_g...
Identify strongly connected components then perform a topological sort of those components.
375,158
def subscribe(self, stream, callback, transform=""): if self.status == "disconnected" or self.status == "disconnecting" or self.status == "connecting": self.connect() if self.status is not "connected": return False logging.debug("Subscribing to %s", stream) ...
Given a stream, a callback and an optional transform, sets up the subscription
375,159
def do(self, arg): ".example - This is an example plugin for the command line debugger" print "This is an example command." print "%s.do(%r, %r):" % (__name__, self, arg) print " last event", self.lastEvent print " prefix", self.cmdprefix print " arguments", self.split_tokens(arg)
.example - This is an example plugin for the command line debugger
375,160
def get_code(self): if self.code is None: self.code = urlopen(self.url).read() return self.code
Opens the link and returns the response's content.
375,161
def tparse(instring, lenout=_default_len_out): errmsg = stypes.stringToCharP(lenout) lenout = ctypes.c_int(lenout) instring = stypes.stringToCharP(instring) sp2000 = ctypes.c_double() libspice.tparse_c(instring, lenout, ctypes.byref(sp2000), errmsg) return sp2000.value, stypes.toPythonStrin...
Parse a time string and return seconds past the J2000 epoch on a formal calendar. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html :param instring: Input time string, UTC. :type instring: str :param lenout: Available space in output error message string. :type lenout: int ...
375,162
def start(self, max): try: self.widget.max = max display(self.widget) except: pass
Displays the progress bar for a given maximum value. :param float max: Maximum value of the progress bar.
375,163
def get_metrics(self, name=None): return self._get_elements(self.metrics, , Metric, name=name)
Get metrics for this operator. Args: name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If `name` is not supplied, then all metrics for this operator are returned. Returns: list(Metric): List of matching metrics...
375,164
def load_json(filename): try: if PY2: args = else: args = with open(filename, args) as fid: data = json.load(fid) return data, None except Exception as err: return None, str(err)
Load a json file as a dictionary
375,165
def register_user(self, data): error = False msg = "" email_re = re.compile( r"(^[-! r r, re.IGNORECASE) if re.match(r"^[-_|~0-9A-Z]{4,}$", data["username"], re.IGNORECASE) is None: error = True msg = _("...
Parses input and register user
375,166
def mutation_jwt_refresh_token_required(fn): @wraps(fn) def wrapper(cls, *args, **kwargs): token = kwargs.pop(current_app.config[]) try: verify_refresh_jwt_in_argument(token) except Exception as e: return cls(AuthInfoField(message=str(e))) return fn(...
A decorator to protect a mutation. If you decorate anmutation with this, it will ensure that the requester has a valid refresh token before allowing the mutation to be called.
375,167
def get_one(cls, db, *args, **kwargs): data = db[cls.collection].find_one(*args, **kwargs) if data: return cls.wrap_incoming(data, db) else: return None
Returns an object that corresponds to given query or ``None``. Example:: item = Item.get_one(db, {'title': u'Hello'})
375,168
def get_handler(self, request): try: f = self._json_rpc_methods[request.method] except (AttributeError, KeyError): raise RPCMethodError("Received invalid method ".format(request.method)) return f
Get callable from JSON RPC request :param RPCRequest request: JSON RPC request :return: Method :rtype: callable
375,169
def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb): row_chunk_size = min(df_shape[0], 1000) col_chunk_size = min(((max_chunk_kb*elem_per_kb)//row_chunk_size), df_shape[1]) return (row_chunk_size, col_chunk_size)
Sets chunk size to use for writing data matrix. Note. Calculation used here is for compatibility with cmapM and cmapR. Input: - df_shape (tuple): shape of input data_df. - max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy - elem_per_kb (int): Number...
375,170
def autobuild_arm_program(elfname, test_dir=os.path.join(, ), patch=True): try: family = utilities.get_family() family.for_all_targets(family.tile.short_name, lambda x: arm.build_program(family.tile, elfname, x, patch=patch)) unit_test.build_units(os.path.join(,), fa...
Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those.
375,171
def mirrored(setup): @wraps(setup) def wrapped_setup(self): self.mirror, self.mock = mirror() return setup(self, self.mirror, self.mock) return wrapped_setup
Convience decorator for setUp in testcases:: @mirrored def setUp(self, mirror, mock): ... is the same as:: def setUp(self): self.mirror, self.mock = mirror() mirror, mock = self.mirror, self.mock ...
375,172
def permission_denied(request, template_name=None, extra_context=None): if template_name is None: template_name = (, ) context = { : request.path, } if extra_context: context.update(extra_context) return HttpResponseForbidden(loader.render_to_string( template_nam...
Default 403 handler. Templates: `403.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/')
375,173
def _merge_sections(sec_a, sec_b): sec_b.ids = list(sec_a.ids) + list(sec_b.ids[1:]) sec_b.ntype = sec_a.ntype sec_b.pid = sec_a.pid sec_a.ids = [] sec_a.pid = -1 sec_a.ntype = 0
Merge two sections Merges sec_a into sec_b and sets sec_a attributes to default
375,174
def bulk_create_posts(self, posts, post_categories, post_tags, post_media_attachments): Post.objects.bulk_create(posts) for post_wp_id, categories in six.iteritems(post_categories): Post.objects.get(site_id=self.site_id, wp_id=post_wp_id).categories.add(*categories) ...
Actually do a db bulk creation of posts, and link up the many-to-many fields :param posts: the list of Post objects to bulk create :param post_categories: a mapping of Categories to add to newly created Posts :param post_tags: a mapping of Tags to add to newly created Posts :param post_...
375,175
def _do_exit(self, cmd, args): if cmd == : if not args: return else: self.stderr.write(textwrap.dedent()).format(args) if not args: return True if len(args) > 1: self.stderr.write(textwrap.dedent(...
\ Exit shell. exit | C-D Exit to the parent shell. exit root | end Exit to the root shell. exit all Exit to the command line.
375,176
def evolved_transformer_decoder(decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, cache=None, ...
Evolved Transformer decoder. See arxiv.org/abs/1901.11117 for more details. Args: decoder_input: a Tensor. encoder_output: a Tensor. decoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()). encoder_decoder_attention_bias: bias Tensor for encoder-decod...
375,177
def _validate_name(name): if name is None: return if not all([name[0].isalnum(), name[-1].isalnum()]): raise ValueError("Bucket names must start and end with a number or letter.") return name
Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid.
375,178
def compute_panel(cls, data, scales, params): msg = raise NotImplementedError(msg.format(cls.__name__))
Positions must override this function Notes ----- Make necessary adjustments to the columns in the dataframe. Create the position transformation functions and use self.transform_position() do the rest. See Also -------- position_jitter.compute_panel
375,179
def _run_evolve(ssm_file, cnv_file, work_dir, data): exe = os.path.join(os.path.dirname(sys.executable), "evolve.py") assert os.path.exists(exe), "Could not find evolve script for PhyloWGS runs." out_dir = os.path.join(work_dir, "evolve") out_file = os.path.join(out_dir, "top_k_trees") if not u...
Run evolve.py to infer subclonal composition.
375,180
def invoke(self): self._iter += 1 if self._iter - max(self._trainer.best_iter, self._annealed_iter) >= self._patience: if self._annealed_times >= self._anneal_times: logging.info("ending") self._trainer.exit() else: self._t...
Run it, return whether to end training.
375,181
def process_next_message(self, timeout): message = self.worker_manager.receive(timeout) if isinstance(message, Acknowledgement): self.task_manager.task_start(message.task, message.worker) elif isinstance(message, Result): self.task_manager.task_done(message.task...
Processes the next message coming from the workers.
375,182
def get_handlers(self, kind=None): with self._lock: if kind is not None: try: return self._handlers[kind][:] except KeyError: return [] return self.__all_handlers.copy()
Retrieves the handlers of the given kind. If kind is None, all handlers are returned. :param kind: The kind of the handlers to return :return: A list of handlers, or an empty list
375,183
def close(self): if self.done: return self.result self.done = True if not self._got_data: self.logger.debug() prober.charset_name, prober.language, ...
Stop analyzing the current document and come up with a final prediction. :returns: The ``result`` attribute, a ``dict`` with the keys `encoding`, `confidence`, and `language`.
375,184
def _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None): with tf.compat.v1.name_scope(name, , [fn_arg_list, result, grads]): def _convert_to_tensor(x, name): ctt = lambda x_: x_ if x_ is None else tf.convert_to_tensor( value=x_, name=name) ...
Helper to `maybe_call_fn_and_grads`.
375,185
def _add_field_column(self, field): @self.add_column(name=field) def get_my_label(cluster_id): return self.cluster_meta.get(field, cluster_id)
Add a column for a given label field.
375,186
def getVariable(self, name): return lock_and_call( lambda: Variable(self._impl.getVariable(name)), self._lock )
Get the variable with the corresponding name. Args: name: Name of the variable to be found. Raises: TypeError: if the specified variable does not exist.
375,187
def get_owned_games(self, steamID, include_appinfo=1, include_played_free_games=0, appids_filter=None, format=None): parameters = { : steamID, : include_appinfo, : include_played_free_games } if forma...
Request a list of games owned by a given steam id. steamID: The users id include_appinfo: boolean. include_played_free_games: boolean. appids_filter: a json encoded list of app ids. format: Return format. None defaults to json. (json, xml, vdf)
375,188
def dAbr_dV(dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St): dAf_dPf = spdiag(2 * Sf.real()) dAf_dQf = spdiag(2 * Sf.imag()) dAt_dPt = spdiag(2 * St.real()) dAt_dQt = spdiag(2 * St.imag()) dAf_dVa = dAf_dPf * dSf_dVa.real() + dAf_dQf * dSf_dVa.imag() dAt_dVa = dAt_dPt * dSt_dVa.real(...
Partial derivatives of squared flow magnitudes w.r.t voltage. Computes partial derivatives of apparent power w.r.t active and reactive power flows. Partial derivative must equal 1 for lines with zero flow to avoid division by zero errors (1 comes from L'Hopital).
375,189
def build_error_handler(*tasks): def _handler(error, tasks=[]): [t(error) for t in tasks] return error.jsonify(), error.status_code, error.headers return functools.partial(_handler, tasks=tasks)
Provides a generic error function that packages a flask_buzz exception so that it can be handled nicely by the flask error handler:: app.register_error_handler( FlaskBuzz, FlaskBuzz.build_error_handler(), ) Additionally, extra tasks may be applied to the error p...
375,190
def find_multiline_pattern(self, regexp, cursor, findflag): pattern = to_text_string(regexp.pattern()) text = to_text_string(self.toPlainText()) try: regobj = re.compile(pattern) except sre_constants.error: return if findflag & QTextDocume...
Reimplement QTextDocument's find method Add support for *multiline* regular expressions
375,191
def version_history(soup, html_flag=True): "extract the article version history details" convert = lambda xml_string: xml_to_html(html_flag, xml_string) version_history = [] related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup)) for tag in related_object_tags: article...
extract the article version history details
375,192
def print_variables_info(self, output_file=sys.stdout): table = ( + ) for name, var_info in list(self.variables.items()): table += .format(name, var_info[0], var_info[1]) print(prefix_indent(, table), file=output_file)
Print variables information in human readble format.
375,193
def locate_file(filename, env_var=, directory=): f = locate_by_env(filename, env_var) or locate_by_dir(filename, directory) return os.path.abspath(f) if can_locate(f) else None
Locates a file given an environment variable or directory :param filename: filename to search for :param env_var: environment variable to look under :param directory: directory to look in :return: (string) absolute path to filename or None if not found
375,194
def has_perm(self, perm): if in perm: app_label, codename = perm.split() permissions = self.permissions.filter( content_type__app_label = app_label, codename = codename) groups = self.groups.filter( permissions__conte...
Checks if key has the given django's auth Permission
375,195
def add_filter_rule( self, name, condition, filters, actions, active=1, way=): filters[] = condition new_rule = { : name, : active, : filters, : actions } new_rules = [zobjects.FilterRule.from_dict(new_rule)] ...
:param: name filter name :param: condition allof or anyof :param: filters dict of filters :param: actions dict of actions :param: way string discribing if filter is for 'in' or 'out' messages :returns: list of user's zobjects.FilterRule
375,196
def _flatten(self, element): result = [(element.text or )] if element.attrib.get(): result.append(Symbol(element.attrib.get()).textbox) for sel in element: result.append(self._flatten(sel)) result.append(sel.tail or ) return .join(re...
Recursively enter and extract text from all child elements.
375,197
def check_ok_button(self): login = self.login.text() password = self.password.text() url = self.url.text() if self.layers.count() >= 1 and login and password and url: self.ok_button.setEnabled(True) else: self.ok_button.setEnabled(False)
Helper to enable or not the OK button.
375,198
def limit_spec(self, spec): if list(spec.keys()) == []: return spec
Whenever we do a Pseudo ID lookup from the database, we need to limit based on the memberships -> organization -> jurisdiction, so we scope the resolution.
375,199
def return_self_updater(func): newobj @functools.wraps(func) def decorator(k,v): func(k,v) return v return decorator
Run func, but still return v. Useful for using knowledge.update with operates like append, extend, etc. e.g. return_self(lambda k,v: v.append('newobj'))