code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def __do_series_search(self, url): root = self.__fetch_data(url) series_ids = [] data = {} num_results_returned = 0 num_results_total = int(root.get('count')) for child in root.getchildren(): num_results_returned += 1 series_id = child.get('id') series_ids.append(series_id) data[series_id] = {"id": series_id} fields = ["realtime_start", "realtime_end", "title", "observation_start", "observation_end", "frequency", "frequency_short", "units", "units_short", "seasonal_adjustment", "seasonal_adjustment_short", "last_updated", "popularity", "notes"] for field in fields: data[series_id][field] = child.get(field) if num_results_returned > 0: data = pd.DataFrame(data, columns=series_ids).T for field in ["realtime_start", "realtime_end", "observation_start", "observation_end", "last_updated"]: data[field] = data[field].apply(self._parse, format=None) data.index.name = 'series id' else: data = None return data, num_results_total
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list expression_statement assignment identifier dictionary expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment subscript subscript identifier identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier keyword_argument identifier identifier identifier for_statement identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript identifier identifier call attribute subscript identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier none expression_statement assignment attribute attribute identifier identifier identifier string string_start string_content string_end else_clause block expression_statement assignment identifier none return_statement expression_list identifier identifier
helper function for making one HTTP request for data, and parsing the returned results into a DataFrame
def parse_year_days(year_info): leap_month, leap_days = _parse_leap(year_info) res = leap_days for month in range(1, 13): res += (year_info >> (16 - month)) % 2 + 29 return res
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier identifier for_statement identifier call identifier argument_list integer integer block expression_statement augmented_assignment identifier binary_operator binary_operator parenthesized_expression binary_operator identifier parenthesized_expression binary_operator integer identifier integer integer return_statement identifier
Parse year days from a year info.
def link_file(f, fldr): fname = os.path.join(fldr,f) if os.path.isfile(fname): return '<a href="/aikif/data/core/' + f + '">' + f + '</a>' else: return f
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block return_statement binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end else_clause block return_statement identifier
creates a html link for a file using folder fldr
def copy_spline_array(a): b = spline_array() b.x_splines = a.x_splines b.y_splines = a.y_splines b.max_y_splines = a.max_y_splines b.xmin = a.xmin b.xmax = a.xmax b.ymin = a.ymin b.ymax = a.ymax b.xlabel = a.xlabel b.ylabel = a.ylabel b.zlabel = a.zlabel b.simple = a.simple b.generate_y_values() return b
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
This returns an instance of a new spline_array with all the fixins, and the data from a.
def basis(self): precision_adj = self.dt / 100 return np.arange(self.start, self.stop - precision_adj, self.dt)
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier integer return_statement call attribute identifier identifier argument_list attribute identifier identifier binary_operator attribute identifier identifier identifier attribute identifier identifier
Compute basis rather than storing it.
def raw_encode(self, value): if type(value) in self.encoders: encoder = self.encoders[type(value)] return encoder(self, value) raise ValueError("No encoder for value '%s' of type '%s'" % (value, type(value)))
module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier call identifier argument_list identifier return_statement call identifier argument_list identifier identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call identifier argument_list identifier
Run the encoder on a value
def _parse_and_check_elements(self, data): crc = data[-1] test_crc = crc32(data[:-1]) & 0x0ff elem_data = data[2:-1] if test_crc == crc: while len(elem_data) > 0: (eid, elen) = struct.unpack('BB', elem_data[:2]) self.elements[self.element_mapping[eid]] = \ elem_data[2:2 + elen].decode('ISO-8859-1') elem_data = elem_data[2 + elen:] return True return False
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier unary_operator integer expression_statement assignment identifier binary_operator call identifier argument_list subscript identifier slice unary_operator integer integer expression_statement assignment identifier subscript identifier slice integer unary_operator integer if_statement comparison_operator identifier identifier block while_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier slice integer expression_statement assignment subscript attribute identifier identifier subscript attribute identifier identifier identifier line_continuation call attribute subscript identifier slice integer binary_operator integer identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier slice binary_operator integer identifier return_statement true return_statement false
Parse and check the CRC and length of the elements part of the memory
def _add_attend_to_encoder_cache(cache, attention_name, hparams, num_layers, key_channels, value_channels, vars_3d_num_heads, scope_prefix, encoder_output): for layer in range(num_layers): layer_name = "layer_%d" % layer with tf.variable_scope("%sdecoder/%s/%s/multihead_attention" % (scope_prefix, layer_name, attention_name)): k_encdec = common_attention.compute_attention_component( encoder_output, key_channels, name="k", vars_3d_num_heads=vars_3d_num_heads) k_encdec = common_attention.split_heads(k_encdec, hparams.num_heads) v_encdec = common_attention.compute_attention_component( encoder_output, value_channels, name="v", vars_3d_num_heads=vars_3d_num_heads) v_encdec = common_attention.split_heads(v_encdec, hparams.num_heads) cache[layer_name][attention_name] = { "k_encdec": k_encdec, "v_encdec": v_encdec } return cache
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier block for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier with_statement with_clause with_item call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment subscript subscript identifier identifier identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier return_statement identifier
Add attend-to-encoder layers to cache.
def showMenu( self, pos ): menu = QMenu(self) menu.setAttribute(Qt.WA_DeleteOnClose) menu.addAction('Clear').triggered.connect(self.clearFilepath) menu.addSeparator() menu.addAction('Copy Filepath').triggered.connect(self.copyFilepath) menu.exec_(self.mapToGlobal(pos))
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier
Popups a menu for this widget.
def passengers(self) -> Set["PassengerUnit"]: return {PassengerUnit(unit, self._game_data) for unit in self._proto.passengers}
module function_definition identifier parameters identifier type generic_type identifier type_parameter type string string_start string_content string_end block return_statement set_comprehension call identifier argument_list identifier attribute identifier identifier for_in_clause identifier attribute attribute identifier identifier identifier
Units inside a Bunker, CommandCenter, Nydus, Medivac, WarpPrism, Overlord
def save_context(context): file_path = _get_context_filepath() content = format_to_http_prompt(context, excluded_options=EXCLUDED_OPTIONS) with io.open(file_path, 'w', encoding='utf-8') as f: f.write(content)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier
Save a Context object to user data directory.
def after_feature(context, feature): context.pctl.stop_all() shutil.rmtree(os.path.join(context.pctl.patroni_path, 'data')) context.dcs_ctl.cleanup_service_tree() if feature.status == 'failed': shutil.copytree(context.pctl.output_dir, context.pctl.output_dir + '_failed')
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier binary_operator attribute attribute identifier identifier identifier string string_start string_content string_end
stop all Patronis, remove their data directory and cleanup the keys in etcd
def scrolling_base_widget(self): def orig_iter(w): while hasattr(w, 'original_widget'): w = w.original_widget yield w yield w def is_scrolling_widget(w): return hasattr(w, 'get_scrollpos') and hasattr(w, 'rows_max') for w in orig_iter(self): if is_scrolling_widget(w): return w raise ValueError('Not compatible to be wrapped by ScrollBar: %r' % w)
module function_definition identifier parameters identifier block function_definition identifier parameters identifier block while_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier expression_statement yield identifier expression_statement yield identifier function_definition identifier parameters identifier block return_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end for_statement identifier call identifier argument_list identifier block if_statement call identifier argument_list identifier block return_statement identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier
Nearest `original_widget` that is compatible with the scrolling API
def init_text(self): d = self.declaration if d.text: self.set_text(d.text) if d.text_color: self.set_text_color(d.text_color) if d.text_alignment: self.set_text_alignment(d.text_alignment) if d.font_family or d.text_size: self.refresh_font() if hasattr(d, 'max_lines') and d.max_lines: self.set_max_lines(d.max_lines)
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement boolean_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier
Init text properties for this widget
def detail(self, block_identifier: BlockSpecification) -> ChannelDetails: return self.token_network.detail( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier
Returns the channel details.
def find_message(self): while True: self.msg = self.mlog.recv_match(condition=args.condition) if self.msg is not None and self.msg.get_type() != 'BAD_DATA': break if self.mlog.f.tell() > self.filesize - 10: self.paused = True break self.last_timestamp = getattr(self.msg, '_timestamp')
module function_definition identifier parameters identifier block while_statement true block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block break_statement if_statement comparison_operator call attribute attribute attribute identifier identifier identifier identifier argument_list binary_operator attribute identifier identifier integer block expression_statement assignment attribute identifier identifier true break_statement expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end
find the next valid message
def _clean_intenum(obj): if isinstance(obj, dict): for key, value in obj.items(): if isinstance(value, IntEnum): obj[key] = value.value elif isinstance(value, (dict, list)): obj[key] = _clean_intenum(value) elif isinstance(obj, list): for i, value in enumerate(obj): if isinstance(value, IntEnum): obj[i] = value.value elif isinstance(value, (dict, list)): obj[i] = _clean_intenum(value) return obj
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier attribute identifier identifier elif_clause call identifier argument_list identifier tuple identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier attribute identifier identifier elif_clause call identifier argument_list identifier tuple identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier return_statement identifier
Remove all IntEnum classes from a map.
def add(self, entry, local_file): row = self.rowClass() for key, val in entry.items(): if key in self.columns: setattr(row, key, val) row.local_filename = os.path.join('.', os.path.relpath(local_file)) self.rows.append(row)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Add a metadata row.
def spawn(self, command): env = dict(os.environ) env["MRQ_IS_SUBPROCESS"] = "1" env.update(self.extra_env or {}) parts = shlex.split(command) for p in list(parts): if "=" in p: env[p.split("=")[0]] = p[len(p.split("=")[0]) + 1:] parts.pop(0) else: break p = subprocess.Popen(parts, shell=False, close_fds=True, env=env, cwd=os.getcwd()) self.processes.append({ "subprocess": p, "pid": p.pid, "command": command, "psutil": psutil.Process(pid=p.pid) })
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list boolean_operator attribute identifier identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer subscript identifier slice binary_operator call identifier argument_list subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer expression_statement call attribute identifier identifier argument_list integer else_clause block break_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier false keyword_argument identifier true keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier
Spawns a new process and adds it to the pool
def _get_property(device_path: Union[Path, str], property_name: str) -> str: with open(str(Path(device_path, property_name))) as file: return file.readline().strip()
module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type identifier type identifier block with_statement with_clause with_item as_pattern call identifier argument_list call identifier argument_list call identifier argument_list identifier identifier as_pattern_target identifier block return_statement call attribute call attribute identifier identifier argument_list identifier argument_list
Gets the given property for a device.
def update_condition(self, service_id, version_number, name_key, **kwargs): body = self._formdata(kwargs, FastlyCondition.FIELDS) content = self._fetch("/service/%s/version/%d/condition/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyCondition(self, content)
module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier
Updates the specified condition.
def change_state(self, state): if state is not self.state: if self.debug: self.print_debug(b'state => ' + STATE_NAMES[state].encode()) if self.state is STATE_NOT_STARTED: self.read_in_state_not_started = b'' self.state = state
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute subscript identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier string string_start string_end expression_statement assignment attribute identifier identifier identifier
Change the state of the remote process, logging the change
def with_path(self, path, *, encoded=False): if not encoded: path = self._PATH_QUOTER(path) if self.is_absolute(): path = self._normalize_path(path) if len(path) > 0 and path[0] != "/": path = "/" + path return URL(self._val._replace(path=path, query="", fragment=""), encoded=True)
module function_definition identifier parameters identifier identifier keyword_separator default_parameter identifier false block if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier return_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_end keyword_argument identifier string string_start string_end keyword_argument identifier true
Return a new URL with path replaced.
def download(self, url, path=None, force=False): logger.debug(str((url, path, force))) method = self._download return self._create_worker(method, url, path=path, force=force)
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement call attribute identifier identifier argument_list call identifier argument_list tuple identifier identifier identifier expression_statement assignment identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Download file given by url and save it to path.
def _run(cls): if cls._thread: with cls._lock: for task in cls.tasks: cls._execute_task(task) cls.tasks.sort() cls._last_execution = time.time() while cls._thread: with cls._lock: if cls.tasks: for task in cls.tasks: if task.next_execution - cls._last_execution < 0.5: cls._execute_task(task) else: break cls.tasks.sort() cls._last_execution = time.time() cls._sleep_delay = cls.tasks[0].next_execution - cls._last_execution else: cls._sleep_delay = 1 sleep_delay = max(0.1, cls._sleep_delay) time.sleep(sleep_delay)
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block with_statement with_clause with_item attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list while_statement attribute identifier identifier block with_statement with_clause with_item attribute identifier identifier block if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator binary_operator attribute identifier identifier attribute identifier identifier float block expression_statement call attribute identifier identifier argument_list identifier else_clause block break_statement expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier binary_operator attribute subscript attribute identifier identifier integer identifier attribute identifier identifier else_clause block expression_statement assignment attribute identifier identifier integer expression_statement assignment identifier call identifier argument_list float attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier
Background thread's main function, execute registered tasks accordingly to their frequencies
def find_node(self, node, path): for hash_value in path: if isinstance(node, LeafStatisticsNode): break for stats in node.get_child_keys(): if hash(stats) == hash_value: node = node.get_child_node(stats) break else: break return node
module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block break_statement for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier break_statement else_clause block break_statement return_statement identifier
Finds a node by the given path from the given node.
def flush(self): if not self.nostdout: self.stdout.flush() if self.file is not None: self.file.flush()
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list
Force commit changes to the file and stdout
def _add_slide_number(self, slide_no): if self.builder.config.slide_numbers: self.body.append( '\n<div class="slide-no">%s</div>\n' % (slide_no,), )
module function_definition identifier parameters identifier identifier block if_statement attribute attribute attribute identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple identifier
Add the slide number to the output if enabled.
def show(movie): for key, value in sorted(movie.iteritems(), cmp=metadata_sorter, key=lambda x: x[0]): if isinstance(value, list): if not value: continue other = value[1:] value = value[0] else: other = [] printer.p('<b>{key}</b>: {value}', key=key, value=value) for value in other: printer.p('{pad}{value}', value=value, pad=' ' * (len(key) + 2))
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier lambda lambda_parameters identifier subscript identifier integer block if_statement call identifier argument_list identifier identifier block if_statement not_operator identifier block continue_statement expression_statement assignment identifier subscript identifier slice integer expression_statement assignment identifier subscript identifier integer else_clause block expression_statement assignment identifier list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator call identifier argument_list identifier integer
Show the movie metadata.
def memory_usage(method): def wrapper(*args, **kwargs): logging.info('Memory before method %s is %s.', method.__name__, runtime.memory_usage().current()) result = method(*args, **kwargs) logging.info('Memory after method %s is %s', method.__name__, runtime.memory_usage().current()) return result return wrapper
module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list return_statement identifier return_statement identifier
Log memory usage before and after a method.
def addStrikeoutAnnot(self, rect): CheckParent(self) val = _fitz.Page_addStrikeoutAnnot(self, rect) if not val: return val.thisown = True val.parent = weakref.proxy(self) self._annot_refs[id(val)] = val return val
module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement not_operator identifier block return_statement expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier call identifier argument_list identifier identifier return_statement identifier
Strike out content in a rectangle or quadrilateral.
def enqueue_command(self, command, data): if command == CommandType.TrialEnd or (command == CommandType.ReportMetricData and data['type'] == 'PERIODICAL'): self.assessor_command_queue.put((command, data)) else: self.default_command_queue.put((command, data)) qsize = self.default_command_queue.qsize() if qsize >= QUEUE_LEN_WARNING_MARK: _logger.warning('default queue length: %d', qsize) qsize = self.assessor_command_queue.qsize() if qsize >= QUEUE_LEN_WARNING_MARK: _logger.warning('assessor queue length: %d', qsize)
module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator comparison_operator identifier attribute identifier identifier parenthesized_expression boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier
Enqueue command into command queues
def _fetch(self, params, required, defaults): defaults.update(params) pp_params = self._check_and_update_params(required, defaults) pp_string = self.signature + urlencode(pp_params) response = self._request(pp_string) response_params = self._parse_response(response) log.debug('PayPal Request:\n%s\n', pprint.pformat(defaults)) log.debug('PayPal Response:\n%s\n', pprint.pformat(response_params)) nvp_params = {} tmpd = defaults.copy() tmpd.update(response_params) for k, v in tmpd.items(): if k in self.NVP_FIELDS: nvp_params[str(k)] = v if 'timestamp' in nvp_params: nvp_params['timestamp'] = paypaltime2datetime(nvp_params['timestamp']) nvp_obj = PayPalNVP(**nvp_params) nvp_obj.init(self.request, params, response_params) nvp_obj.save() return nvp_obj
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript identifier call identifier argument_list identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
Make the NVP request and store the response.
def getvalue(self) -> str: return self.buffer.byte_buf.decode(encoding=self.encoding, errors=self.errors)
module function_definition identifier parameters identifier type identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier
Get the internal contents as a str
def _process_key(self, key): if self.mode != ray.WORKER_MODE: if key.startswith(b"FunctionsToRun"): with profiling.profile("fetch_and_run_function"): self.fetch_and_execute_function_to_run(key) return if key.startswith(b"RemoteFunction"): with profiling.profile("register_remote_function"): (self.worker.function_actor_manager. fetch_and_register_remote_function(key)) elif key.startswith(b"FunctionsToRun"): with profiling.profile("fetch_and_run_function"): self.fetch_and_execute_function_to_run(key) elif key.startswith(b"ActorClass"): self.worker.function_actor_manager.imported_actor_classes.add(key) else: raise Exception("This code should be unreachable.")
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier return_statement if_statement call attribute identifier identifier argument_list string string_start string_content string_end block with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement parenthesized_expression call attribute attribute attribute identifier identifier identifier identifier argument_list identifier elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end
Process the given export key from redis.
def _init_metadata_table(): _metadata_table = sqlalchemy.Table( 'metadata', _METADATA, sqlalchemy.Column( 'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"), nullable=False, primary_key=True), sqlalchemy.Column('key', sqlalchemy.UnicodeText, primary_key=True), sqlalchemy.Column('value', sqlalchemy.UnicodeText, index=True), sqlalchemy.Column('type', sqlalchemy.UnicodeText), ) return _metadata_table
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier false keyword_argument identifier true call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier keyword_argument identifier true call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier keyword_argument identifier true call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier return_statement identifier
Initialise the "metadata" table in the db.
def __substitute_replace_pairs(self): self._set_magic_constants() routine_source = [] i = 0 for line in self._routine_source_code_lines: self._replace['__LINE__'] = "'%d'" % (i + 1) for search, replace in self._replace.items(): tmp = re.findall(search, line, re.IGNORECASE) if tmp: line = line.replace(tmp[0], replace) routine_source.append(line) i += 1 self._routine_source_code = "\n".join(routine_source)
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier list expression_statement assignment identifier integer for_statement identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier integer for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier integer expression_statement assignment attribute identifier identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier
Substitutes all replace pairs in the source of the stored routine.
def label(self): if self.__doc__ and self.__doc__.strip(): return self.__doc__.strip().splitlines()[0] return humanize(self.__class__.__name__)
module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list block return_statement subscript call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list integer return_statement call identifier argument_list attribute attribute identifier identifier identifier
A human readable label
def _compute_ogg_page_crc(page): page_zero_crc = page[:OGG_FIRST_PAGE_HEADER_CRC_OFFSET] + \ b"\00" * OGG_FIRST_PAGE_HEADER_CRC.size + \ page[OGG_FIRST_PAGE_HEADER_CRC_OFFSET + OGG_FIRST_PAGE_HEADER_CRC.size:] return ogg_page_crc(page_zero_crc)
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator subscript identifier slice identifier binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier line_continuation subscript identifier slice binary_operator identifier attribute identifier identifier return_statement call identifier argument_list identifier
Compute CRC of an Ogg page.
def remove_column(table, remove_index): for row_index in range(len(table)): old_row = table[row_index] new_row = [] for column_index in range(len(old_row)): if column_index != remove_index: new_row.append(old_row[column_index]) table[row_index] = new_row return table
module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier list for_statement identifier call identifier argument_list call identifier argument_list identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier
Removes the specified column from the table.
def received_message(self, address, data): self.value_cache.set(address, data) if self.notify: self.notify(address, data) try: listeners = self.address_listeners[address] except KeyError: listeners = [] for listener in listeners: listener(address, data)
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier try_statement block expression_statement assignment identifier subscript attribute identifier identifier identifier except_clause identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier
Process a message received from the KNX bus.
def add_lambda_integration(self): lambda_uri = self.generate_uris()['lambda_uri'] self.client.put_integration( restApiId=self.api_id, resourceId=self.resource_id, httpMethod=self.trigger_settings['method'], integrationHttpMethod='POST', uri=lambda_uri, type='AWS') self.add_integration_response() self.log.info("Successfully added Lambda intergration to API")
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end
Attach lambda found to API.
def rename(self, old_name, new_name): try: self.api.rename(mkey(old_name), mkey(new_name)) except ResponseError, exc: if "no such key" in exc.args: raise KeyError(old_name) raise
module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier call identifier argument_list identifier except_clause identifier identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block raise_statement call identifier argument_list identifier raise_statement
Rename key to a new name.
def JsonResponseModel(self): old_model = self.response_type_model self.__response_type_model = 'json' yield self.__response_type_model = old_model
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement yield expression_statement assignment attribute identifier identifier identifier
In this context, return raw JSON instead of proto.
def _GenConfig(self, cfg): merged = self.default.copy() for setting, vals in iteritems(cfg): option, operator = (setting.split(None, 1) + [None])[:2] vals = set(vals) default = set(self.default.get(option, [])) if operator == "+": vals = default.union(vals) elif operator == "-": vals = default.difference(vals) merged[option] = list(vals) return rdf_protodict.AttributedDict(**merged)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier subscript parenthesized_expression binary_operator call attribute identifier identifier argument_list none integer list none slice integer expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier list if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier
Interpolate configurations with defaults to generate actual configs.
def normpath(path): scheme, netloc, path_ = parse(path) return unparse(scheme, netloc, os.path.normpath(path_))
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier return_statement call identifier argument_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier
Normalize ``path``, collapsing redundant separators and up-level refs.
def find_description(self, name): "Find a description for the given appliance name." for desc in self.virtual_system_descriptions: values = desc.get_values_by_type(DescType.name, DescValueType.original) if name in values: break else: raise Exception("Failed to find description for %s" % name) return desc
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier if_statement comparison_operator identifier identifier block break_statement else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier
Find a description for the given appliance name.
def create(cls, config_file=None): if cls.instance is None: cls.instance = cls(config_file) cls.instance.load_ini() if config_file and config_file != cls.instance.config_file: raise RuntimeError("Configuration initialized a second time with a different file!") return cls.instance
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list if_statement boolean_operator identifier comparison_operator identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement attribute identifier identifier
Return the default configuration.
def return_standard_conf(): result = resource_string(__name__, 'daemon/dagobahd.yml') result = result % {'app_secret': os.urandom(24).encode('hex')} return result
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier binary_operator identifier dictionary pair string string_start string_content string_end call attribute call attribute identifier identifier argument_list integer identifier argument_list string string_start string_content string_end return_statement identifier
Return the sample config file.
def restore_bucket(self, table_name): if table_name.startswith(self.__prefix): return table_name.replace(self.__prefix, '', 1) return None
module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list attribute identifier identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_end integer return_statement none
Restore bucket from SQL
def resolve_type_spec(self, name, lineno): if name in self.type_specs: return self.type_specs[name].link(self) if '.' in name: include_name, component = name.split('.', 1) if include_name in self.included_scopes: return self.included_scopes[include_name].resolve_type_spec( component, lineno ) raise ThriftCompilerError( 'Unknown type "%s" referenced at line %d%s' % ( name, lineno, self.__in_path() ) )
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator identifier attribute identifier identifier block return_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier call attribute identifier identifier argument_list
Finds and links the TypeSpec with the given name.
def inv_n(x): assert x.ndim == 3 assert x.shape[1] == x.shape[2] c = np.array([ [cofactor_n(x, j, i) * (1 - ((i+j) % 2)*2) for j in range(x.shape[1])] for i in range(x.shape[1])]).transpose(2,0,1) return c / det_n(x)[:, np.newaxis, np.newaxis]
module function_definition identifier parameters identifier block assert_statement comparison_operator attribute identifier identifier integer assert_statement comparison_operator subscript attribute identifier identifier integer subscript attribute identifier identifier integer expression_statement assignment identifier call attribute call attribute identifier identifier argument_list list_comprehension list_comprehension binary_operator call identifier argument_list identifier identifier identifier parenthesized_expression binary_operator integer binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier identifier integer integer for_in_clause identifier call identifier argument_list subscript attribute identifier identifier integer for_in_clause identifier call identifier argument_list subscript attribute identifier identifier integer identifier argument_list integer integer integer return_statement binary_operator identifier subscript call identifier argument_list identifier slice attribute identifier identifier attribute identifier identifier
given N matrices, return N inverses
def dispatch_hook(cls, _pkt=b"", *args, **kargs): if _pkt and len(_pkt) >= 1: if orb(_pkt[0]) == 0x41: return LoWPANUncompressedIPv6 if orb(_pkt[0]) == 0x42: return LoWPAN_HC1 if orb(_pkt[0]) >> 3 == 0x18: return LoWPANFragmentationFirst elif orb(_pkt[0]) >> 3 == 0x1C: return LoWPANFragmentationSubsequent elif orb(_pkt[0]) >> 6 == 0x02: return LoWPANMesh elif orb(_pkt[0]) >> 6 == 0x01: return LoWPAN_IPHC return cls
module function_definition identifier parameters identifier default_parameter identifier string string_start string_end list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement boolean_operator identifier comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator call identifier argument_list subscript identifier integer integer block return_statement identifier if_statement comparison_operator call identifier argument_list subscript identifier integer integer block return_statement identifier if_statement comparison_operator binary_operator call identifier argument_list subscript identifier integer integer integer block return_statement identifier elif_clause comparison_operator binary_operator call identifier argument_list subscript identifier integer integer integer block return_statement identifier elif_clause comparison_operator binary_operator call identifier argument_list subscript identifier integer integer integer block return_statement identifier elif_clause comparison_operator binary_operator call identifier argument_list subscript identifier integer integer integer block return_statement identifier return_statement identifier
Depending on the payload content, the frame type we should interpretate
def modify_pattern(self, pattern, group): pattern = group_regex.sub(r'?P<{}_\1>'.format(self.name), pattern) return r'(?P<{}>{})'.format(group, pattern)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier
Rename groups in regex pattern and enclose it in named group
def runm(): signal.signal(signal.SIGINT, signal_handler) count = int(sys.argv.pop(1)) processes = [Process(target=run, args=()) for x in range(count)] try: for p in processes: p.start() except KeyError: pass finally: for p in processes: p.join()
module function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list integer expression_statement assignment identifier list_comprehension call identifier argument_list keyword_argument identifier identifier keyword_argument identifier tuple for_in_clause identifier call identifier argument_list identifier try_statement block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement finally_clause block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list
This is super minimal and pretty hacky, but it counts as a first pass.
def _parse_top_cfg(content, filename): try: obj = salt.utils.yaml.safe_load(content) if isinstance(obj, list): log.debug('MakoStack cfg `%s` parsed as YAML', filename) return obj except Exception as err: pass log.debug('MakoStack cfg `%s` parsed as plain text', filename) return content.splitlines()
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier except_clause as_pattern identifier as_pattern_target identifier block pass_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list
Allow top_cfg to be YAML
def next_sample(self): if self._allow_read is False: raise StopIteration if self.seq is not None: if self.cur < self.num_image: idx = self.seq[self.cur] else: if self.last_batch_handle != 'discard': self.cur = 0 raise StopIteration self.cur += 1 if self.imgrec is not None: s = self.imgrec.read_idx(idx) header, img = recordio.unpack(s) if self.imglist is None: return header.label, img else: return self.imglist[idx][0], img else: label, fname = self.imglist[idx] return label, self.read_image(fname) else: s = self.imgrec.read() if s is None: if self.last_batch_handle != 'discard': self.imgrec.reset() raise StopIteration header, img = recordio.unpack(s) return header.label, img
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier false block raise_statement identifier if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier else_clause block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier integer raise_statement identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block return_statement expression_list attribute identifier identifier identifier else_clause block return_statement expression_list subscript subscript attribute identifier identifier identifier integer identifier else_clause block expression_statement assignment pattern_list identifier identifier subscript attribute identifier identifier identifier return_statement expression_list identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier none block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list raise_statement identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier return_statement expression_list attribute identifier identifier identifier
Helper function for reading in next sample.
def run(self): logging.info("Starting GeoJSON MongoDB loading process.") mongo = dict(uri=self.mongo, db=self.db, collection=self.collection) self.load(self.source, **mongo) logging.info("Finished loading {0} into MongoDB".format(self.source))
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier
Top level runner to load State and County GeoJSON files into Mongo DB
def samples(self): names = self.series.dimensions for values in zip(*(getattr(self.series, name) for name in names)): yield dict(zip(names, values))
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier for_statement identifier call identifier argument_list list_splat generator_expression call identifier argument_list attribute identifier identifier identifier for_in_clause identifier identifier block expression_statement yield call identifier argument_list call identifier argument_list identifier identifier
Yield the samples as dicts, keyed by dimensions.
def write(self, fout=None, fmt=SPARSE, schema_only=False, data_only=False): assert not (schema_only and data_only), 'Make up your mind.' assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS)) close = False if fout is None: close = True fout = StringIO() if not data_only: print('% ' + re.sub("\n", "\n% ", '\n'.join(self.comment)), file=fout) print("@relation " + self.relation, file=fout) self.write_attributes(fout=fout) if not schema_only: print("@data", file=fout) for d in self.data: line_str = self.write_line(d, fmt=fmt) if line_str: print(line_str, file=fout) if isinstance(fout, StringIO) and close: return fout.getvalue()
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier identifier default_parameter identifier false default_parameter identifier false block assert_statement not_operator parenthesized_expression boolean_operator identifier identifier string string_start string_content string_end assert_statement comparison_operator identifier identifier binary_operator string string_start string_content string_end tuple identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier false if_statement comparison_operator identifier none block expression_statement assignment identifier true expression_statement assignment identifier call identifier argument_list if_statement not_operator identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content escape_sequence string_end call attribute string string_start string_content escape_sequence string_end identifier argument_list attribute identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement identifier block expression_statement call identifier argument_list identifier keyword_argument identifier identifier if_statement boolean_operator call identifier argument_list identifier identifier identifier block return_statement call attribute identifier identifier argument_list
Write an arff structure to a string.
def main(): print("Python version %s" % sys.version) print("Testing compatibility for function defined with *args") test_func_args(func_old_args) test_func_args(func_new) print("Testing compatibility for function defined with **kwargs") test_func_kwargs(func_old_kwargs) test_func_kwargs(func_new) print("All tests successful - we can change *args and **kwargs to' \ ' named args.") return 0
module function_definition identifier parameters block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content escape_sequence string_end return_statement integer
Main function calls the test functs
def delete(ctx, family_file, family_type, case_id): if not (family_file or case_id): LOG.error("Please provide a family file") ctx.abort() adapter = ctx.obj['adapter'] family = None family_id = None if family_file: with open(family_file, 'r') as family_lines: family = get_case( family_lines=family_lines, family_type=family_type ) family_id = family.family_id case_id = case_id or family_id if not case_id: LOG.warning("Please provide a case id") ctx.abort() existing_case = adapter.case({'case_id': case_id}) if not existing_case: LOG.warning("Case %s does not exist in database" %case_id) context.abort start_deleting = datetime.now() try: delete_command( adapter=adapter, case_obj=existing_case, ) except (CaseError, IOError) as error: LOG.warning(error) ctx.abort()
module function_definition identifier parameters identifier identifier identifier identifier block if_statement not_operator parenthesized_expression boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier none expression_statement assignment identifier none if_statement identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier boolean_operator identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list
Delete the variants of a case.
async def get_all_platforms(self) -> AsyncIterator[Platform]: for name in self._classes.keys(): yield await self.get_platform(name)
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement yield await call attribute identifier identifier argument_list identifier
Returns all platform instances
def on_backward_end(self, **kwargs): "accumulated step and reset samples, True will result in no stepping" if (self.acc_batches % self.n_step) == 0: for p in (self.learn.model.parameters()): if p.requires_grad: p.grad.div_(self.acc_samples) self.acc_samples = 0 else: return {'skip_step':True, 'skip_zero':True}
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end if_statement comparison_operator parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier integer block for_statement identifier parenthesized_expression call attribute attribute attribute identifier identifier identifier identifier argument_list block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier integer else_clause block return_statement dictionary pair string string_start string_content string_end true pair string string_start string_content string_end true
accumulated step and reset samples, True will result in no stepping
def memory_full(): current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement parenthesized_expression comparison_operator call attribute identifier identifier argument_list attribute identifier identifier
Check if the memory is too full for further caching.
def makedirs(path): path = Path(path) if not path.exists(): path.mkdir(parents=True)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list keyword_argument identifier true
Creates the directory tree if non existing.
def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess) if match: return match[0] return None
module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier true default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier identifier identifier if_statement identifier block return_statement subscript identifier integer return_statement none
Returns just the best item, or ``None``
def assumes(*args): args = tuple(args) def decorator(func): func.assumptions = args return func return decorator
module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier identifier return_statement identifier return_statement identifier
Stores a function's assumptions as an attribute.
def iterator(self): for ent_cls in list(self.__entity_set_map.keys()): for ent in self.__entity_set_map[ent_cls]: yield EntityState.get_state(ent)
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block for_statement identifier subscript attribute identifier identifier identifier block expression_statement yield call attribute identifier identifier argument_list identifier
Returns an iterator over all entity states held by this Unit Of Work.
def _coulomb(n1, n2, k, r): delta = [x2 - x1 for x1, x2 in zip(n1['velocity'], n2['velocity'])] distance = sqrt(sum(d ** 2 for d in delta)) if distance < 0.1: delta = [uniform(0.1, 0.2) for _ in repeat(None, 3)] distance = sqrt(sum(d ** 2 for d in delta)) if distance < r: force = (k / distance) ** 2 n1['force'] = [f - force * d for f, d in zip(n1['force'], delta)] n2['force'] = [f + force * d for f, d in zip(n2['force'], delta)]
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list_comprehension binary_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call identifier generator_expression binary_operator identifier integer for_in_clause identifier identifier if_statement comparison_operator identifier float block expression_statement assignment identifier list_comprehension call identifier argument_list float float for_in_clause identifier call identifier argument_list none integer expression_statement assignment identifier call identifier argument_list call identifier generator_expression binary_operator identifier integer for_in_clause identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier integer expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension binary_operator identifier binary_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension binary_operator identifier binary_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end identifier
Calculates Coulomb forces and updates node data.
def grok_seconds(lease): if lease.endswith('s'): return int(lease[0:-1]) elif lease.endswith('m'): return int(lease[0:-1]) * 60 elif lease.endswith('h'): return int(lease[0:-1]) * 3600 return None
module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement call identifier argument_list subscript identifier slice integer unary_operator integer elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block return_statement binary_operator call identifier argument_list subscript identifier slice integer unary_operator integer integer elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block return_statement binary_operator call identifier argument_list subscript identifier slice integer unary_operator integer integer return_statement none
Ensures that we are returning just seconds
def targets(tgt, tgt_type='glob', **kwargs): roster_file = os.path.abspath('terraform.tfstate') if __opts__.get('roster_file'): roster_file = os.path.abspath(__opts__['roster_file']) if not os.path.isfile(roster_file): log.error("Can't find terraform state file '%s'", roster_file) return {} log.debug('terraform roster: using %s state file', roster_file) if not roster_file.endswith('.tfstate'): log.error("Terraform roster can only be used with terraform state files") return {} raw = _parse_state_file(roster_file) log.debug('%s hosts in terraform state file', len(raw)) return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement dictionary expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement dictionary expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier return_statement call subscript identifier string string_start string_content string_end argument_list identifier identifier identifier string string_start string_content string_end
Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate
def run_region(data, region, vrn_files, out_file): broad_runner = broad.runner_from_config(data["config"]) if broad_runner.gatk_type() == "gatk4": genomics_db = _run_genomicsdb_import(vrn_files, region, out_file, data) return _run_genotype_gvcfs_genomicsdb(genomics_db, region, out_file, data) else: vrn_files = _batch_gvcfs(data, region, vrn_files, dd.get_ref_file(data), out_file) return _run_genotype_gvcfs_gatk3(data, region, vrn_files, dd.get_ref_file(data), out_file)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier return_statement call identifier argument_list identifier identifier identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier identifier identifier call attribute identifier identifier argument_list identifier identifier return_statement call identifier argument_list identifier identifier identifier call attribute identifier identifier argument_list identifier identifier
Perform variant calling on gVCF inputs in a specific genomic region.
def _to_pb(self): client = self._instance._client location = client.instance_admin_client.location_path( client.project, self.location_id ) cluster_pb = instance_pb2.Cluster( location=location, serve_nodes=self.serve_nodes, default_storage_type=self.default_storage_type, ) return cluster_pb
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier return_statement identifier
Create cluster proto buff message for API calls
def main(): e = mod_env.Internet('VAIS - Load testing', 'Simulation of several websites') e.create(800) print(e) print(npc.web_users.params)
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer expression_statement call identifier argument_list identifier expression_statement call identifier argument_list attribute attribute identifier identifier identifier
generates a virtual internet, sets pages and runs web_users on it
def logfile_generator(self): if not self.args['exclude']: start_limits = [f.start_limit for f in self.filters if hasattr(f, 'start_limit')] if start_limits: for logfile in self.args['logfile']: logfile.fast_forward(max(start_limits)) if len(self.args['logfile']) > 1: for logevent in self._merge_logfiles(): yield logevent else: for logevent in self.args['logfile'][0]: if self.args['timezone'][0] != 0 and logevent.datetime: logevent._datetime = (logevent.datetime + timedelta(hours=self .args['timezone'][0])) yield logevent
module function_definition identifier parameters identifier block if_statement not_operator subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier if_clause call identifier argument_list identifier string string_start string_content string_end if_statement identifier block for_statement identifier subscript attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier if_statement comparison_operator call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end integer block for_statement identifier call attribute identifier identifier argument_list block expression_statement yield identifier else_clause block for_statement identifier subscript subscript attribute identifier identifier string string_start string_content string_end integer block if_statement boolean_operator comparison_operator subscript subscript attribute identifier identifier string string_start string_content string_end integer integer attribute identifier identifier block expression_statement assignment attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier call identifier argument_list keyword_argument identifier subscript subscript attribute identifier identifier string string_start string_content string_end integer expression_statement yield identifier
Yield each line of the file, or the next line if several files.
def array_map(f, ar): "Apply an ordinary function to all values in an array." flat_ar = ravel(ar) out = zeros(len(flat_ar), flat_ar.typecode()) for i in range(len(flat_ar)): out[i] = f(flat_ar[i]) out.shape = ar.shape return out
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement assignment subscript identifier identifier call identifier argument_list subscript identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement identifier
Apply an ordinary function to all values in an array.
def get(self, url, params=None): r = self.session.get(url, params=params) return self._response_parser(r, expect_json=False)
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false
Initiate a GET request
def ssh_cmd(self, name, ssh_command): if not self.container_exists(name=name): exit("Unknown container {0}".format(name)) if not self.container_running(name=name): exit("Container {0} is not running".format(name)) ip = self.get_container_ip(name) if not ip: exit("Failed to get network address for " "container {0}".format(name)) if ssh_command: ssh.do_cmd('root', ip, 'password', " ".join(ssh_command)) else: ssh.launch_shell('root', ip, 'password')
module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call attribute identifier identifier argument_list keyword_argument identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement not_operator call attribute identifier identifier argument_list keyword_argument identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier string string_start string_content string_end
SSH into given container and executre command if given
async def report(self, msg, timeout=5): try: host_manager = await self.env.connect(self.host_manager, timeout=timeout) except: raise ConnectionError("Could not reach host manager ({})." .format(self.host_manager)) ret = await host_manager.handle(msg) return ret
module function_definition identifier parameters identifier identifier default_parameter identifier integer block try_statement block expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier except_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier await call attribute identifier identifier argument_list identifier return_statement identifier
Report message to the host manager.
def draw_actions(self): now = time.time() for act in self._past_actions: if act.pos and now < act.deadline: remain = (act.deadline - now) / (act.deadline - act.time) if isinstance(act.pos, point.Point): size = remain / 3 self.all_surfs(_Surface.draw_circle, act.color, act.pos, size, 1) else: self.all_surfs(_Surface.draw_rect, act.color, act.pos, 1)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block if_statement boolean_operator attribute identifier identifier comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator attribute identifier identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier if_statement call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier binary_operator identifier integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier identifier integer else_clause block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier integer
Draw the actions so that they can be inspected for accuracy.
def _validate_type_scalar(self, value): if isinstance( value, _int_types + (_str_type, float, date, datetime, bool) ): return True
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier binary_operator identifier tuple identifier identifier identifier identifier identifier block return_statement true
Is not a list or a dict
def filter_silenced(self): stashes = [ ('client', '/silence/{}'.format(self.event['client']['name'])), ('check', '/silence/{}/{}'.format( self.event['client']['name'], self.event['check']['name'])), ('check', '/silence/all/{}'.format(self.event['check']['name'])) ] for scope, path in stashes: if self.stash_exists(path): self.bail(scope + ' alerts silenced')
module function_definition identifier parameters identifier block expression_statement assignment identifier list tuple string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end tuple string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end tuple string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end for_statement pattern_list identifier identifier identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end
Determine whether a check is silenced and shouldn't handle.
def _copy_finfo(finfo, storage_dir, pass_uptodate=False): out_file = _get_file_upload_path(finfo, storage_dir) if not shared.up_to_date(out_file, finfo): logger.info("Storing in local filesystem: %s" % out_file) shutil.copy(finfo["path"], out_file) return out_file if pass_uptodate: return out_file
module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement not_operator call attribute identifier identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier return_statement identifier if_statement identifier block return_statement identifier
Copy a file into the output storage directory.
def save_grade_entry(self, grade_entry_form, *args, **kwargs): if grade_entry_form.is_for_update(): return self.update_grade_entry(grade_entry_form, *args, **kwargs) else: return self.create_grade_entry(grade_entry_form, *args, **kwargs)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call attribute identifier identifier argument_list block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier else_clause block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier
Pass through to provider GradeEntryAdminSession.update_grade_entry
def at_least_libvips(x, y): major = version(0) minor = version(1) return major > x or (major == x and minor >= y)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list integer expression_statement assignment identifier call identifier argument_list integer return_statement boolean_operator comparison_operator identifier identifier parenthesized_expression boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier
Is this at least libvips x.y?
def handle_incoming_response(self, call_id, payload): self.log.debug('handle_incoming_response: in [typehint: %s, call ID: %s]', payload['typehint'], call_id) typehint = payload["typehint"] handler = self.handlers.get(typehint) def feature_not_supported(m): msg = feedback["handler_not_implemented"] self.editor.raw_message(msg.format(typehint, self.launcher.ensime_version)) if handler: with catch(NotImplementedError, feature_not_supported): handler(call_id, payload) else: self.log.warning('Response has not been handled: %s', Pretty(payload))
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute attribute identifier identifier identifier if_statement identifier block with_statement with_clause with_item call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier
Get a registered handler for a given response and execute it.
def init_conv_weight(layer): n_filters = layer.filters filter_shape = (layer.kernel_size,) * get_n_dim(layer) weight = np.zeros((n_filters, n_filters) + filter_shape) center = tuple(map(lambda x: int((x - 1) / 2), filter_shape)) for i in range(n_filters): filter_weight = np.zeros((n_filters,) + filter_shape) index = (i,) + center filter_weight[index] = 1 weight[i, ...] = filter_weight bias = np.zeros(n_filters) layer.set_weights( (add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1]))) )
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator tuple attribute identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator tuple identifier identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list lambda lambda_parameters identifier call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer identifier for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator tuple identifier identifier expression_statement assignment identifier binary_operator tuple identifier identifier expression_statement assignment subscript identifier identifier integer expression_statement assignment subscript identifier identifier ellipsis identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list tuple call identifier argument_list identifier call attribute identifier identifier argument_list list integer integer call identifier argument_list identifier call attribute identifier identifier argument_list list integer integer
initilize conv layer weight.
def validate_unique(self, *args, **kwargs): super(EighthSignup, self).validate_unique(*args, **kwargs) if self.has_conflict(): raise ValidationError({NON_FIELD_ERRORS: ("EighthSignup already exists for the User and the EighthScheduledActivity's block",)})
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier if_statement call attribute identifier identifier argument_list block raise_statement call identifier argument_list dictionary pair identifier tuple string string_start string_content string_end
Checked whether more than one EighthSignup exists for a User on a given EighthBlock.
def post(self) -> Vpn: vpn = Vpn() session.add(vpn) self.update(vpn) session.flush() session.commit() return vpn, 201, { 'Location': url_for('vpn', vpn_id=vpn.id) }
module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement expression_list identifier integer dictionary pair string string_start string_content string_end call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier
Creates the vpn with the given data.
def generate_cli_main_parser(): parser = argparse.ArgumentParser( description='Create, Update, Delete, List DNS entries') parser.add_argument('--version', help='show the current version of lexicon', action='version', version='%(prog)s {0}' .format(discovery.lexicon_version())) parser.add_argument('--delegated', help='specify the delegated domain') parser.add_argument('--config-dir', default=os.getcwd(), help='specify the directory where to search lexicon.yml and ' 'lexicon_[provider].yml configuration files ' '(default: current directory).') subparsers = parser.add_subparsers( dest='provider_name', help='specify the DNS provider to use') subparsers.required = True for provider, available in discovery.find_providers().items(): provider_module = importlib.import_module( 'lexicon.providers.' + provider) provider_parser = getattr(provider_module, 'provider_parser') subparser = subparsers.add_parser(provider, help='{0} provider'.format(provider), parents=[generate_base_provider_parser()]) provider_parser(subparser) if not available: subparser.epilog = ('WARNING: some required dependencies for this provider are not ' 'installed. Please install lexicon[{0}] first before using it.' .format(provider)) return parser
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier true for_statement pattern_list identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier list call identifier argument_list expression_statement call identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment attribute identifier identifier parenthesized_expression call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier return_statement identifier
Using all providers available, generate a parser that will be used by Lexicon CLI
def azm(self): azm1 = self.get('BEARING', None) azm2 = self.get('AZM2', None) if azm1 is None and azm2 is None: return None if azm2 is None: return azm1 + self.declination if azm1 is None: return (azm2 + 180) % 360 + self.declination return (azm1 + (azm2 + 180) % 360) / 2.0 + self.declination
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block return_statement none if_statement comparison_operator identifier none block return_statement binary_operator identifier attribute identifier identifier if_statement comparison_operator identifier none block return_statement binary_operator binary_operator parenthesized_expression binary_operator identifier integer integer attribute identifier identifier return_statement binary_operator binary_operator parenthesized_expression binary_operator identifier binary_operator parenthesized_expression binary_operator identifier integer integer float attribute identifier identifier
Corrected azimuth, taking into account backsight, declination, and compass corrections.
def create_buffer(self, ignore_unsupported=False): bufferdict = OrderedDict() for branch in self.iterbranches(): if not self.GetBranchStatus(branch.GetName()): continue if not BaseTree.branch_is_supported(branch): log.warning( "ignore unsupported branch `{0}`".format(branch.GetName())) continue bufferdict[branch.GetName()] = Tree.branch_type(branch) self.set_buffer(TreeBuffer( bufferdict, ignore_unsupported=ignore_unsupported))
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list for_statement identifier call attribute identifier identifier argument_list block if_statement not_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block continue_statement if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list continue_statement expression_statement assignment subscript identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier keyword_argument identifier identifier
Create this tree's TreeBuffer
def id(cls): if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immutable(Column(Integer, primary_key=True, nullable=False))
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement call identifier argument_list call identifier argument_list call identifier argument_list keyword_argument identifier false keyword_argument identifier attribute identifier identifier keyword_argument identifier true keyword_argument identifier false else_clause block return_statement call identifier argument_list call identifier argument_list identifier keyword_argument identifier true keyword_argument identifier false
Database identity for this model, used for foreign key references from other models
def _GetURLContent(url): response = urllib_request.urlopen(url) encoding = response.info().get('Content-Encoding') if encoding == 'gzip': content = _Gunzip(response.read()) else: content = response.read() return content
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier
Download and return the content of URL.
def render_js_template(self, template_path, element_id, context=None): context = context or {} return u"<script type='text/template' id='{}'>\n{}\n</script>".format( element_id, self.render_template(template_path, context) )
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier dictionary return_statement call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier
Render a js template.
def _put_json(self, instance, space=None, rel_path=None, extra_params=None, id_field=None): model = type(instance) if space is None and model not in (Space, Event): raise Exception( 'In general, `API._put_json` should always ' 'be called with a `space` argument.' ) if not extra_params: extra_params = {} if not id_field: id_field = 'number' url = '{0}/{1}/{2}/{3}.json?{4}'.format( settings.API_ROOT_PATH, settings.API_VERSION, rel_path or model.rel_path, instance[id_field], urllib.urlencode(extra_params), ) response = requests.put( url=url, data=json.dumps(instance.data), headers={ 'X-Api-Key': self.key, 'X-Api-Secret': self.secret, 'Content-type': "application/json", }, ) if response.status_code == 204: return instance else: raise Exception( 'Code {0} returned from `{1}`. Response text: "{2}".'.format( response.status_code, url, response.text ) )
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier tuple identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier dictionary if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier boolean_operator identifier attribute identifier identifier subscript identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier integer block return_statement identifier else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier attribute identifier identifier
Base level method for adding new data to the API
def _search_val(matches, compiled_pattern, fld_val): mtch = compiled_pattern.search(fld_val) if mtch: matches.append(fld_val)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier
Search for user-regex in scalar data values.
def _inject_patched_examples(self, existing_item, patched_item): for key, _ in patched_item.examples.items(): patched_example = patched_item.examples[key] existing_examples = existing_item.examples if key in existing_examples: existing_examples[key].fields.update(patched_example.fields) else: error_msg = 'Example defined in patch {} must correspond to a pre-existing example.' raise InvalidSpec(error_msg.format( quote(patched_item.name)), patched_example.lineno, patched_example.path)
module function_definition identifier parameters identifier identifier identifier block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement call attribute attribute subscript identifier identifier identifier identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier
Injects patched examples into original examples.
def append(self, state, symbol, action, destinationstate, production = None): if action not in (None, "Accept", "Shift", "Reduce"): raise TypeError rule = {"action":action, "dest":destinationstate} if action == "Reduce": if rule is None: raise TypeError("Expected production parameter") rule["rule"] = production while isinstance(symbol, TerminalSymbol) and isinstance(symbol.gd, Iterable) and len(symbol.gd) == 1 and isinstance(list(symbol.gd)[0], Grammar): symbol = TerminalSymbol(list(symbol.gd)[0]) if not isinstance(symbol, Symbol): raise TypeError("Expected symbol, got %s" % symbol) self[state][symbol] = rule
module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier tuple none string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block raise_statement identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement comparison_operator identifier string string_start string_content string_end block if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier while_statement boolean_operator boolean_operator boolean_operator call identifier argument_list identifier identifier call identifier argument_list attribute identifier identifier identifier comparison_operator call identifier argument_list attribute identifier identifier integer call identifier argument_list subscript call identifier argument_list attribute identifier identifier integer identifier block expression_statement assignment identifier call identifier argument_list subscript call identifier argument_list attribute identifier identifier integer if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment subscript subscript identifier identifier identifier identifier
Appends a new rule