code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def _number_of_set_bits(x): x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f
module function_definition identifier parameters identifier block expression_statement augmented_assignment identifier binary_operator parenthesized_expression binary_operator identifier integer integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier integer integer parenthesized_expression binary_operator identifier integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier integer identifier integer expression_statement augmented_assignment identifier binary_operator identifier integer expression_statement augmented_assignment identifier binary_operator identifier integer return_statement binary_operator identifier integer
Returns the number of bits that are set in a 32bit int
def reverse_velocity_kalman_model(): om = np.array([[1,0,0,0], [0, 1, 0, 0]]) tm = np.array([[1,0,-1,0], [0,1,0,-1], [0,0,1,0], [0,0,0,1]]) return KalmanState(om, tm)
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list list list integer integer integer integer list integer integer integer integer expression_statement assignment identifier call attribute identifier identifier argument_list list list integer integer unary_operator integer integer list integer integer integer unary_operator integer list integer integer integer integer list integer integer integer integer return_statement call identifier argument_list identifier identifier
Return a KalmanState set up to model going backwards in time
def is1d(a:Collection)->bool: "Return `True` if `a` is one-dimensional" return len(a.shape) == 1 if hasattr(a, 'shape') else True
module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement string string_start string_content string_end return_statement conditional_expression comparison_operator call identifier argument_list attribute identifier identifier integer call identifier argument_list identifier string string_start string_content string_end true
Return `True` if `a` is one-dimensional
def add_domain_user_role(request, user, role, domain): manager = keystoneclient(request, admin=True).roles return manager.grant(role, user=user, domain=domain)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier attribute call identifier argument_list identifier keyword_argument identifier true identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier
Adds a role for a user on a domain.
def packet2dict(packet): dict_ = dict() frame = packet.frame_info for field in frame.field_names: dict_[field] = getattr(frame, field) tempdict = dict_ for layer in packet.layers: tempdict[layer.layer_name.upper()] = dict() tempdict = tempdict[layer.layer_name.upper()] for field in layer.field_names: tempdict[field] = getattr(layer, field) return dict_
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment subscript identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list expression_statement assignment identifier subscript identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier return_statement identifier
Convert PyShark packet into dict.
def build_task(self, name): try: self._gettask(name).value = ( self._gettask(name).task.resolve_and_build()) except TaskExecutionException as e: perror(e.header, indent="+0") perror(e.message, indent="+4") self._gettask(name).value = e.payload except Exception as e: perror("error evaluating target '%s' %s" % (name, type(self._gettask(name).task))) perror(traceback.format_exc(e), indent='+4') self._gettask(name).value = None self._gettask(name).last_build_time = time.time()
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment attribute call attribute identifier identifier argument_list identifier identifier parenthesized_expression call attribute attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute call attribute identifier identifier argument_list identifier identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call identifier argument_list attribute call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute call attribute identifier identifier argument_list identifier identifier none expression_statement assignment attribute call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list
Builds a task by name, resolving any dependencies on the way
def _resources(p): if p.resources: click.echo(",".join(p.resources)) else: click.echo(f"Provider '{p.name}' does not have resource helpers")
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content interpolation attribute identifier identifier string_content string_end
Callback func to display provider resources
def build_queryset(self): paths = [(os.path.join(self.build_prefix, 'index.html'), {})] self.request = None queryset = self.get_queryset() paginator = self.get_paginator(queryset, self.get_paginate_by(queryset)) for page in paginator.page_range: paths.append( (os.path.join(self.build_prefix, 'page', '%d' % page, 'index.html'), {'page': page})) for build_path, kwargs in paths: self.request = self.create_request(build_path) self.request.user = AnonymousUser() self.kwargs = kwargs self.prep_directory(build_path) target_path = os.path.join(settings.BUILD_DIR, build_path) self.build_file(target_path, self.get_content())
module function_definition identifier parameters identifier block expression_statement assignment identifier list tuple call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end dictionary expression_statement assignment attribute identifier identifier none expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list tuple call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end binary_operator string string_start string_content string_end identifier string string_start string_content string_end dictionary pair string string_start string_content string_end identifier for_statement pattern_list identifier identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute attribute identifier identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list
Override django-bakery's build logic to fake pagination.
def auto_load_configs(self): for app in apps.get_app_configs(): for model in app.get_models(): config = ModelConfig(model, getattr(app, model.__name__, None)) self.configs[self.get_model_name(model)] = config
module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list identifier attribute identifier identifier none expression_statement assignment subscript attribute identifier identifier call attribute identifier identifier argument_list identifier identifier
Auto load all configs from app configs
def file_exists(fname): try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
module function_definition identifier parameters identifier block try_statement block return_statement boolean_operator boolean_operator identifier call attribute attribute identifier identifier identifier argument_list identifier comparison_operator call attribute attribute identifier identifier identifier argument_list identifier integer except_clause identifier block return_statement false
Check if a file exists and is non-empty.
def md5sum(fname: str) -> str: with open(fname, "rb") as inp: md5 = hashlib.md5(inp.read()).hexdigest() return md5
module function_definition identifier parameters typed_parameter identifier type identifier type 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 attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier argument_list return_statement identifier
Compute MD5 sum of file.
def siblings_files(path): file_basename, extension = splitext(path) main_extension = extension.lower() files = {} if extension.lower() in list(extension_siblings.keys()): for text_extension in list(extension_siblings[main_extension].keys()): if isfile(file_basename + text_extension): files[file_basename + text_extension] = ( extension_siblings[main_extension][text_extension]) if len(files) > 0: mime_base_file = extension_siblings[main_extension][main_extension] else: mime_base_file = None return files, mime_base_file
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary if_statement comparison_operator call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list block for_statement identifier call identifier argument_list call attribute subscript identifier identifier identifier argument_list block if_statement call identifier argument_list binary_operator identifier identifier block expression_statement assignment subscript identifier binary_operator identifier identifier parenthesized_expression subscript subscript identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript subscript identifier identifier identifier else_clause block expression_statement assignment identifier none return_statement expression_list identifier identifier
Return a list of sibling files available.
def calcontime(data, inds=None): if not inds: inds = range(len(data['time'])) logger.info('No indices provided. Assuming all are valid.') scans = set([data['scan'][i] for i in inds]) total = 0. for scan in scans: time = [data['time'][i] for i in inds if data['scan'][i] == scan] total += max(time) - min(time) return total
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list list_comprehension subscript subscript identifier string string_start string_content string_end identifier for_in_clause identifier identifier expression_statement assignment identifier float for_statement identifier identifier block expression_statement assignment identifier list_comprehension subscript subscript identifier string string_start string_content string_end identifier for_in_clause identifier identifier if_clause comparison_operator subscript subscript identifier string string_start string_content string_end identifier identifier expression_statement augmented_assignment identifier binary_operator call identifier argument_list identifier call identifier argument_list identifier return_statement identifier
Given indices of good times, calculate total time per scan with indices.
def create_outbound_email(self, subject, description, email, email_config_id, **kwargs): url = 'tickets/outbound_email' priority = kwargs.get('priority', 1) data = { 'subject': subject, 'description': description, 'priority': priority, 'email': email, 'email_config_id': email_config_id, } data.update(kwargs) ticket = self._api._post(url, data=json.dumps(data)) return Ticket(**ticket)
module function_definition identifier parameters identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list dictionary_splat identifier
Creates an outbound email
def add_menu(self, menu): from MAVProxy.modules.mavproxy_map import mp_slipmap self.default_popup.add(menu) self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True))
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier true
add to the default popup menu
def _expire_data(self): expire_time_stamp = time.time() - self.expire_time self.timed_data = {d: t for d, t in self.timed_data.items() if t > expire_time_stamp}
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list if_clause comparison_operator identifier identifier
Remove all expired entries.
def run_migration(data, version_start, version_end): items = [] if version_start == 1 and version_end == 2: for item in data['accounts']: items.append(v2.upgrade(item)) if version_start == 2 and version_end == 1: for item in data: items.append(v2.downgrade(item)) items = {'accounts': items} return items
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier return_statement identifier
Runs migration against a data set.
def plotMatches2(listofNValues, errors, listOfScales, scaleErrors, fileName = "images/scalar_matches.pdf"): w, h = figaspect(0.4) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(w,h)) plotMatches(listofNValues, errors, fileName=None, fig=fig, ax=ax1) plotScaledMatches(listOfScales, scaleErrors, fileName=None, fig=fig, ax=ax2) plt.savefig(fileName) plt.close()
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call identifier argument_list float expression_statement assignment pattern_list identifier tuple_pattern identifier identifier call attribute identifier identifier argument_list integer integer keyword_argument identifier tuple identifier identifier expression_statement call identifier argument_list identifier identifier keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list identifier identifier keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list
Plot two figures side by side in an aspect ratio appropriate for the paper.
def lines(self): if self._cache.lines is None: self._cache.lines = _ImmutableLineList(self.text.split('\n')) return self._cache.lines
module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment attribute attribute identifier identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end return_statement attribute attribute identifier identifier identifier
Array of all the lines.
def start(self): while True: self.thread_debug("Interval starting") for thr in threading.enumerate(): self.thread_debug(" " + str(thr)) self.feed_monitors() start = time.time() self.workers_queue.join() end = time.time() diff = self.config['interval']['test'] - (end - start) if diff <= 0: self.stats.procwin = -diff self.thread_debug("Cannot keep up with tests! {} seconds late" .format(abs(diff))) else: self.thread_debug("waiting {} seconds...".format(diff)) time.sleep(diff)
module function_definition identifier parameters identifier block while_statement true block expression_statement 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 call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end parenthesized_expression binary_operator identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment attribute attribute identifier identifier identifier unary_operator identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier
The main loop, run forever.
def _get_states(self, result): if 'devices' not in result.keys(): return for device_states in result['devices']: device = self.__devices[device_states['deviceURL']] try: device.set_active_states(device_states['states']) except KeyError: pass
module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block return_statement for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier subscript identifier string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end except_clause identifier block pass_statement
Get states of devices.
def precedence(item): try: mro = item.__class__.__mro__ except AttributeError: return PRECEDENCE["Atom"] for i in mro: n = i.__name__ if n in PRECEDENCE_FUNCTIONS: return PRECEDENCE_FUNCTIONS[n](item) elif n in PRECEDENCE_VALUES: return PRECEDENCE_VALUES[n] return PRECEDENCE["Atom"]
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier attribute attribute identifier identifier identifier except_clause identifier block return_statement subscript identifier string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier identifier block return_statement call subscript identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block return_statement subscript identifier identifier return_statement subscript identifier string string_start string_content string_end
Returns the precedence of a given object.
def output_snapshot_profile(gandi, profile, output_keys, justify=13): schedules = 'schedules' in output_keys if schedules: output_keys.remove('schedules') output_generic(gandi, profile, output_keys, justify) if schedules: schedule_keys = ['name', 'kept_version'] for schedule in profile['schedules']: gandi.separator_line() output_generic(gandi, schedule, schedule_keys, justify)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement assignment identifier comparison_operator string string_start string_content string_end identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier identifier identifier identifier if_statement identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier identifier identifier identifier
Helper to output a snapshot_profile.
def extension_supported(request, extension_name): for extension in list_extensions(request): if extension.name == extension_name: return True return False
module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement true return_statement false
This method will determine if Cinder supports a given extension name.
def std_human_uid(kind=None): kind_list = alphabet if kind == 'animal': kind_list = animals elif kind == 'place': kind_list = places name = "{color} {adjective} {kind} of {attribute}".format( color=choice(colors), adjective=choice(adjectives), kind=choice(kind_list), attribute=choice(attributes) ) return name
module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier return_statement identifier
Return a random generated human-friendly phrase as low-probability unique id
def clear(self): with self._hlock: self.handlers.clear() with self._mlock: self.memoize.clear()
module function_definition identifier parameters identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list
Discards all registered handlers and cached results
def df_names_to_idx(names:IntsOrStrs, df:DataFrame): "Return the column indexes of `names` in `df`." if not is_listy(names): names = [names] if isinstance(names[0], int): return names return [df.columns.get_loc(c) for c in names]
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement string string_start string_content string_end if_statement not_operator call identifier argument_list identifier block expression_statement assignment identifier list identifier if_statement call identifier argument_list subscript identifier integer identifier block return_statement identifier return_statement list_comprehension call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier identifier
Return the column indexes of `names` in `df`.
def _get_filename_path(self, path): feature_filename = os.path.join(path, self.feature_type.value) if self.feature_name is not None: feature_filename = os.path.join(feature_filename, self.feature_name) return feature_filename
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier return_statement identifier
Helper function for creating filename without file extension
def rgb2hex(r: int, g: int, b: int) -> str: return '{:02x}{:02x}{:02x}'.format(r, g, b)
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier
Convert rgb values to a hex code.
def lognorm(x, mu, sigma=1.0): return stats.lognorm(sigma, scale=mu).pdf(x)
module function_definition identifier parameters identifier identifier default_parameter identifier float block return_statement call attribute call attribute identifier identifier argument_list identifier keyword_argument identifier identifier identifier argument_list identifier
Log-normal function from scipy
def norm_vec(vector): assert len(vector) == 3 v = np.array(vector) return v/np.sqrt(np.sum(v**2))
module function_definition identifier parameters identifier block assert_statement comparison_operator call identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement binary_operator identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator identifier integer
Normalize the length of a vector to one
def plot_fracs(self, Q=None, ax=None, fignum=None): from ..plotting import Tango Tango.reset() col = Tango.nextMedium() if ax is None: fig = pylab.figure(fignum) ax = fig.add_subplot(111) if Q is None: Q = self.Q ticks = numpy.arange(Q) bar = ax.bar(ticks - .4, self.fracs[:Q], color=col) ax.set_xticks(ticks, map(lambda x: r"${}$".format(x), ticks + 1)) ax.set_ylabel("Eigenvalue fraction") ax.set_xlabel("PC") ax.set_ylim(0, ax.get_ylim()[1]) ax.set_xlim(ticks.min() - .5, ticks.max() + .5) try: pylab.tight_layout() except: pass return bar
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list integer if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator identifier float subscript attribute identifier identifier slice identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list lambda lambda_parameters identifier call attribute string string_start string_content string_end identifier argument_list identifier binary_operator identifier integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer subscript call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list float binary_operator call attribute identifier identifier argument_list float try_statement block expression_statement call attribute identifier identifier argument_list except_clause block pass_statement return_statement identifier
Plot fractions of Eigenvalues sorted in descending order.
def drain(self, cycles=None): if not self._check_service_requirements(): self.init_timer.stop() return self.finish() if self.anybar: self.anybar.change("orange") self.init_timer.stop() log.info("Trapping CTRL+C and starting to drain.") signal.signal(signal.SIGINT, self._handle_ctrl_c) with ignored(KeyboardInterrupt): return self._drain(cycles)
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier with_statement with_clause with_item call identifier argument_list identifier block return_statement call attribute identifier identifier argument_list identifier
Execute _drain while trapping KeyboardInterrupt
def trends_available(self): url = 'https://api.twitter.com/1.1/trends/available.json' try: resp = self.get(url) except requests.exceptions.HTTPError as e: raise e return resp.json()
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block raise_statement identifier return_statement call attribute identifier identifier argument_list
Returns a list of regions for which Twitter tracks trends.
def do_email_notification(self, comment, entry, site): if not self.mail_comment_notification_recipients: return template = loader.get_template( 'comments/zinnia/entry/email/notification.txt') context = { 'comment': comment, 'entry': entry, 'site': site, 'protocol': PROTOCOL } subject = _('[%(site)s] New comment posted on "%(title)s"') % \ {'site': site.name, 'title': entry.title} message = template.render(context) send_mail( subject, message, settings.DEFAULT_FROM_EMAIL, self.mail_comment_notification_recipients, fail_silently=not settings.DEBUG )
module function_definition identifier parameters identifier identifier identifier identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment identifier binary_operator call identifier argument_list string string_start string_content string_end line_continuation dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier keyword_argument identifier not_operator attribute identifier identifier
Send email notification of a new comment to site staff.
def run(self, steps=10): try: super(GeneticMachine, self).run(steps) self._error = False except StopIteration: self._error = False except Exception: self._error = True
module function_definition identifier parameters identifier default_parameter identifier integer block try_statement block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier false except_clause identifier block expression_statement assignment attribute identifier identifier false except_clause identifier block expression_statement assignment attribute identifier identifier true
Executes up to `steps` instructions.
def _norm_index(dim, index, start, stop): length = stop - start if -length <= index < 0: normindex = index + length elif start <= index < stop: normindex = index - start else: fstr = "expected dim {} index in range [{}, {})" raise IndexError(fstr.format(dim, start, stop)) return normindex
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator unary_operator identifier identifier integer block expression_statement assignment identifier binary_operator identifier identifier elif_clause comparison_operator identifier identifier identifier block expression_statement assignment identifier binary_operator 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 identifier identifier identifier return_statement identifier
Return an index normalized to an farray start index.
def max_voltage_step(self): steps = [self.voltage_pairs[i].voltage - self.voltage_pairs[i + 1].voltage for i in range(len(self.voltage_pairs) - 1)] return max(steps) if len(steps) > 0 else 0
module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension binary_operator attribute subscript attribute identifier identifier identifier identifier attribute subscript attribute identifier identifier binary_operator identifier integer identifier for_in_clause identifier call identifier argument_list binary_operator call identifier argument_list attribute identifier identifier integer return_statement conditional_expression call identifier argument_list identifier comparison_operator call identifier argument_list identifier integer integer
Maximum absolute difference in adjacent voltage steps
def _get_listeners(instance, change): if ( change['mode'] not in listeners_disabled._quarantine and change['name'] in instance._listeners ): return instance._listeners[change['name']][change['mode']] return []
module function_definition identifier parameters identifier identifier block if_statement parenthesized_expression boolean_operator comparison_operator subscript identifier string string_start string_content string_end attribute identifier identifier comparison_operator subscript identifier string string_start string_content string_end attribute identifier identifier block return_statement subscript subscript attribute identifier identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement list
Gets listeners of changed Property on a HasProperties instance
def smudgeraw(target, offset, magicbytes): magicbytes = magicbytes.replace('\\x', '').decode('hex') _backup_bytes(target, offset, len(magicbytes)) _smudge_bytes(target, offset, magicbytes)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_end identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier
Smudge magic bytes with raw bytes
def getflags(fd): flags_ptr = ffi.new('uint64_t*') flags_buf = ffi.buffer(flags_ptr) fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf) return flags_ptr[0]
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier identifier return_statement subscript identifier integer
Gets per-file filesystem flags.
def _treat_devices_added(self): try: devices_details_list = self._plugin_rpc.get_devices_details_list( self._context, self._added_ports, self._agent_id) except Exception as exc: LOG.debug("Unable to get ports details for " "devices %(devices)s: %(exc)s", {'devices': self._added_ports, 'exc': exc}) return for device_details in devices_details_list: device = device_details['device'] LOG.info("Adding port %s", device) if 'port_id' in device_details: LOG.info("Port %(device)s updated. " "Details: %(device_details)s", {'device': device, 'device_details': device_details}) eventlet.spawn_n(self.process_added_port, device_details) else: LOG.debug("Missing port_id from device details: " "%(device)s. Details: %(device_details)s", {'device': device, 'device_details': device_details}) LOG.debug("Remove the port from added ports set, so it " "doesn't get reprocessed.") self._added_ports.discard(device)
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier return_statement for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Process the new devices.
def getCheckedOption(self): if self.__silentRButton.isChecked(): return GCPluginConfigDialog.SILENT if self.__statusbarRButton.isChecked(): return GCPluginConfigDialog.STATUS_BAR return GCPluginConfigDialog.LOG
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list block return_statement attribute identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list block return_statement attribute identifier identifier return_statement attribute identifier identifier
Returns what destination is selected
def mget(self, key, *keys, encoding=_NOTSET): return self.execute(b'MGET', key, *keys, encoding=encoding)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier default_parameter identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier list_splat identifier keyword_argument identifier identifier
Get the values of all the given keys.
def reduce_sum_square(attrs, inputs, proto_obj): square_op = symbol.square(inputs[0]) sum_op = symbol.sum(square_op, axis=attrs.get('axes'), keepdims=attrs.get('keepdims')) return sum_op, attrs, inputs
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement expression_list identifier identifier identifier
Reduce the array along a given axis by sum square value
def prep_rg_names(item, config, fc_name, fc_date): if fc_name and fc_date: lane_name = "%s_%s_%s" % (item["lane"], fc_date, fc_name) else: lane_name = item["description"] return {"rg": item["description"], "sample": item["description"], "lane": lane_name, "pl": (tz.get_in(["algorithm", "platform"], item) or tz.get_in(["algorithm", "platform"], item, "illumina")).lower(), "lb": tz.get_in(["metadata", "library"], item), "pu": tz.get_in(["metadata", "platform_unit"], item) or lane_name}
module function_definition identifier parameters identifier identifier identifier identifier block if_statement boolean_operator identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple subscript identifier string string_start string_content string_end identifier identifier else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end return_statement dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute parenthesized_expression boolean_operator call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier pair string string_start string_content string_end boolean_operator call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier identifier
Generate read group names from item inputs.
def _handle_multiple_svcallers(data, stage): svs = get_svcallers(data) if stage == "ensemble" and dd.get_svprioritize(data): svs.append("prioritize") out = [] for svcaller in svs: if svcaller in _get_callers([data], stage): base = copy.deepcopy(data) final_svs = [] for sv in data.get("sv", []): if (stage == "ensemble" or sv["variantcaller"] == svcaller or sv["variantcaller"] not in svs or svcaller not in _get_callers([data], stage, special_cases=True)): final_svs.append(sv) base["sv"] = final_svs base["config"]["algorithm"]["svcaller"] = svcaller base["config"]["algorithm"]["svcaller_orig"] = svs out.append(base) return out
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator identifier call identifier argument_list list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end list block if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator subscript identifier string string_start string_content string_end identifier comparison_operator subscript identifier string string_start string_content string_end identifier comparison_operator identifier call identifier argument_list list identifier identifier keyword_argument identifier true block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Retrieve configured structural variation caller, handling multiple.
def remove_unused_resources(issues, app_dir, ignore_layouts): for issue in issues: filepath = os.path.join(app_dir, issue.filepath) if issue.remove_file: remove_resource_file(issue, filepath, ignore_layouts) else: remove_resource_value(issue, filepath)
module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call identifier argument_list identifier identifier identifier else_clause block expression_statement call identifier argument_list identifier identifier
Remove the file or the value inside the file depending if the whole file is unused or not.
def write(self, fptr): self._validate(writing=True) length = 16 + 4 * len(self.compatibility_list) fptr.write(struct.pack('>I4s', length, b'ftyp')) fptr.write(self.brand.encode()) fptr.write(struct.pack('>I', self.minor_version)) for item in self.compatibility_list: fptr.write(item.encode())
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier true expression_statement assignment identifier binary_operator integer binary_operator integer call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list
Write a File Type box to file.
def complete(self, text, state): "Generic readline completion entry point." results = [w for w in self.words if w.startswith(text)] + [None] if results != [None]: return results[state] buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() results = [w for w in self.words if w.startswith(text)] + [None] if results != [None]: return results[state] if RE_SPACE.match(buffer): line.append('') return (self.complete_extra(line) + [None])[state]
module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier binary_operator list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause call attribute identifier identifier argument_list identifier list none if_statement comparison_operator identifier list none block return_statement subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier binary_operator list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause call attribute identifier identifier argument_list identifier list none if_statement comparison_operator identifier list none block return_statement subscript identifier identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_end return_statement subscript parenthesized_expression binary_operator call attribute identifier identifier argument_list identifier list none identifier
Generic readline completion entry point.
def getfile(data_name, path): data_source = get_data_object(data_name, use_data_config=False) if not data_source: if 'output' in data_name: floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.") sys.exit() url = "{}/api/v1/resources/{}/{}?content=true".format(floyd.floyd_host, data_source.resource_id, path) fname = os.path.basename(path) DataClient().download(url, filename=fname) floyd_logger.info("Download finished")
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier false if_statement not_operator identifier block if_statement comparison_operator string string_start string_content string_end 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 string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute call identifier argument_list identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end
Download a specific file from a dataset.
def create_all_tables(self): for klass in self.__get_classes(): if not klass.exists(): klass.create_table(read_capacity_units=1, write_capacity_units=1, wait=True)
module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier true
Create database tables for all known database data-models.
def probe(self, axis: str, distance: float) -> Dict[str, float]: return self._smoothie_driver.probe_axis(axis, distance)
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier type identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier
Run a probe and return the new position dict
def _get_date(self, decrypted_content): date_field = struct.unpack('<5B', decrypted_content[:5]) dw1 = date_field[0] dw2 = date_field[1] dw3 = date_field[2] dw4 = date_field[3] dw5 = date_field[4] y = (dw1 << 6) | (dw2 >> 2) mon = ((dw2 & 0x03) << 2) | (dw3 >> 6) d = (dw3 >> 1) & 0x1F h = ((dw3 & 0x01) << 4) | (dw4 >> 4) min_ = ((dw4 & 0x0F) << 2) | (dw5 >> 6) s = dw5 & 0x3F return datetime(y, mon, d, h, min_, s)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier slice integer expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier integer parenthesized_expression binary_operator identifier integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier integer integer parenthesized_expression binary_operator identifier integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier integer integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier integer integer parenthesized_expression binary_operator identifier integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier integer integer parenthesized_expression binary_operator identifier integer expression_statement assignment identifier binary_operator identifier integer return_statement call identifier argument_list identifier identifier identifier identifier identifier identifier
This method is used to decode the packed dates of entries
def blend_color(color, color2): r1, g1, b1 = hex_to_rgb(color) r2, g2, b2 = hex_to_rgb(color2) r3 = int(0.5 * r1 + 0.5 * r2) g3 = int(0.5 * g1 + 0.5 * g2) b3 = int(0.5 * b1 + 0.5 * b2) return rgb_to_hex((r3, g3, b3))
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list binary_operator binary_operator float identifier binary_operator float identifier expression_statement assignment identifier call identifier argument_list binary_operator binary_operator float identifier binary_operator float identifier expression_statement assignment identifier call identifier argument_list binary_operator binary_operator float identifier binary_operator float identifier return_statement call identifier argument_list tuple identifier identifier identifier
Blend two colors together.
def _handle_response(self, response): if not response.ok: raise ScrapydResponseError( "Scrapyd returned a {0} error: {1}".format( response.status_code, response.text)) try: json = response.json() except ValueError: raise ScrapydResponseError("Scrapyd returned an invalid JSON " "response: {0}".format(response.text)) if json['status'] == 'ok': json.pop('status') return json elif json['status'] == 'error': raise ScrapydResponseError(json['message'])
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block raise_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 attribute identifier identifier if_statement comparison_operator subscript identifier string string_start string_content string_end 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 identifier elif_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list subscript identifier string string_start string_content string_end
Handles the response received from Scrapyd.
def _obtain_token(self): if self.expiration and self.expiration > datetime.datetime.now(): return resp = requests.post("{}/1.1/oauth/token".format(API_URL), data={ "client_id": self.client_id, "client_secret": self.client_secret, "grant_type": "client_credentials" }).json() if "error" in resp: raise APIError("LibCal Auth Failed: {}, {}".format(resp["error"], resp.get("error_description"))) self.expiration = datetime.datetime.now() + datetime.timedelta(seconds=resp["expires_in"]) self.token = resp["access_token"] print(self.token)
module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list block return_statement expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list 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 identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier binary_operator call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement call identifier argument_list attribute identifier identifier
Obtain an auth token from client id and client secret.
def init(self): if not self.export_enable: return None server_uri = '{}:{}'.format(self.host, self.port) try: s = KafkaProducer(bootstrap_servers=server_uri, value_serializer=lambda v: json.dumps(v).encode('utf-8'), compression_type=self.compression) except Exception as e: logger.critical("Cannot connect to Kafka server %s (%s)" % (server_uri, e)) sys.exit(2) else: logger.info("Connected to the Kafka server %s" % server_uri) return s
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement none expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier lambda lambda_parameters identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call attribute identifier identifier argument_list integer else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier
Init the connection to the Kafka server.
def negociate_content(default='json-ld'): mimetype = request.accept_mimetypes.best_match(ACCEPTED_MIME_TYPES.keys()) return ACCEPTED_MIME_TYPES.get(mimetype, default)
module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier identifier
Perform a content negociation on the format given the Accept header
def _keep_alive(self): send_next_keep_alive_at = 0 while not self.is_closed: if not self.is_ready: self._reconnect() continue if time.monotonic() > send_next_keep_alive_at: command = KEEP_ALIVE_COMMAND_PREAMBLE + [self.wb1, self.wb2] self._send_raw(command) need_response_by = time.monotonic() + KEEP_ALIVE_TIME timeout = max(0, need_response_by - time.monotonic()) ready = select.select([self._socket], [], [], timeout) if ready[0]: try: response = bytearray(12) self._socket.recv_into(response) if response[:5] == bytearray(KEEP_ALIVE_RESPONSE_PREAMBLE): send_next_keep_alive_at = need_response_by except (socket.error, socket.timeout): with self._lock: self.is_ready = False elif send_next_keep_alive_at < need_response_by: with self._lock: self.is_ready = False
module function_definition identifier parameters identifier block expression_statement assignment identifier integer while_statement not_operator attribute identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list continue_statement if_statement comparison_operator call attribute identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator identifier list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list integer binary_operator identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list list attribute identifier identifier list list identifier if_statement subscript identifier integer block try_statement block expression_statement assignment identifier call identifier argument_list integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator subscript identifier slice integer call identifier argument_list identifier block expression_statement assignment identifier identifier except_clause tuple attribute identifier identifier attribute identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement assignment attribute identifier identifier false elif_clause comparison_operator identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement assignment attribute identifier identifier false
Send keep alive messages continuously to bridge.
async def initialize(self): flavors = await self._list_flavors() images = await self._list_images() self.flavors_map = bidict() self.images_map = bidict() self.images_details = {} for flavor in flavors: self.flavors_map.put(flavor['id'], flavor['name'], on_dup_key='OVERWRITE', on_dup_val='OVERWRITE') for image in images: self.images_details[image['id']] = { 'name': image['name'], 'created_at': image['created_at'], 'latest': 'latest' in image['tags'] } self.images_map.put(image['id'], image['name'], on_dup_key='OVERWRITE', on_dup_val='OVERWRITE')
module function_definition identifier parameters identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list expression_statement assignment identifier await call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier dictionary for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end subscript identifier 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 for_statement identifier identifier block expression_statement assignment subscript attribute identifier identifier subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end comparison_operator string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end subscript identifier 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
Initialize static data like images and flavores and set it as object property
def cat(dataset, query, bounds, indent, compact, dst_crs, pagesize, sortby): dump_kwds = {"sort_keys": True} if indent: dump_kwds["indent"] = indent if compact: dump_kwds["separators"] = (",", ":") table = bcdata.validate_name(dataset) for feat in bcdata.get_features( table, query=query, bounds=bounds, sortby=sortby, crs=dst_crs ): click.echo(json.dumps(feat, **dump_kwds))
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end true if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end tuple string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier dictionary_splat identifier
Write DataBC features to stdout as GeoJSON feature objects.
def availability_rtf() -> bool: unrtf = tools['unrtf'] if unrtf: return True elif pyth: log.warning("RTF conversion: unrtf missing; " "using pyth (less efficient)") return True else: return False
module function_definition identifier parameters type identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement identifier block return_statement true elif_clause identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement true else_clause block return_statement false
Is an RTF processor available?
def _shutdown(self, message=None, code=0): if self._shutdown_complete: sys.exit(code) if self.shutdown_callback is not None: self.shutdown_callback(message, code) if self.pidfile is not None: self._close_pidfile() self._shutdown_complete = True sys.exit(code)
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier integer block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list identifier
Shutdown and cleanup everything.
def pop(self): popped = False result = None current_node = self._first_node while not popped: next_node = current_node.next() next_next_node = next_node.next() if not next_next_node: self._last_node = current_node self._last_node.update_next(None) self._size -= 1 result = next_node.data() popped = True current_node = next_node return result
module function_definition identifier parameters identifier block expression_statement assignment identifier false expression_statement assignment identifier none expression_statement assignment identifier attribute identifier identifier while_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list none expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier true expression_statement assignment identifier identifier return_statement identifier
Removes the last node from the list
def write_case_data(self, file): file.write("function mpc = %s\n" % self._fcn_name) file.write('\n%%%% MATPOWER Case Format : Version %d\n' % 2) file.write("mpc.version = '%d';\n" % 2) file.write("\n%%%%----- Power Flow Data -----%%%%\n") file.write("%%%% system MVA base\n") file.write("%sbaseMVA = %g;\n" % (self._prefix, self.case.base_mva))
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence escape_sequence string_end integer expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier attribute attribute identifier identifier identifier
Writes the case data in MATPOWER format.
def bubble_to_js(bblfile:str, jsdir:str=None, oriented:bool=False, **style): js_converter.bubble_to_dir(bblfile, jsdir, oriented=bool(oriented), **style) return jsdir
module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier false dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier call identifier argument_list identifier dictionary_splat identifier return_statement identifier
Write in jsdir a graph equivalent to those depicted in bubble file
def check_version(ctx, param, value): if ctx.resilient_parsing: return if not value and ctx.invoked_subcommand != 'run': ctx.call_on_close(_check_version)
module function_definition identifier parameters identifier identifier identifier block if_statement attribute identifier identifier block return_statement if_statement boolean_operator not_operator identifier comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier
Check for latest version of renku on PyPI.
def _get_dynamic_acl_info(self, switch_ip): cmds = ["enable", "show ip access-lists dynamic", "show ip access-lists summary dynamic"] switch = self._switches.get(switch_ip) _, acls, bindings = self._run_eos_cmds(cmds, switch) parsed_acls = self._parse_acl_config(acls) parsed_bindings = self._parse_binding_config(bindings) return parsed_acls, parsed_bindings
module function_definition identifier parameters identifier identifier block 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 expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier
Retrieve ACLs, ACLs rules and interface bindings from switch
def _get_user(self, username, attrs=ALL_ATTRS): username = ldap.filter.escape_filter_chars(username) user_filter = self.user_filter_tmpl % { 'username': self._uni(username) } r = self._search(self._byte_p2(user_filter), attrs, self.userdn) if len(r) == 0: return None if attrs == NO_ATTR: dn_entry = r[0][0] else: dn_entry = r[0] return dn_entry
module function_definition identifier parameters identifier identifier default_parameter identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier binary_operator attribute identifier identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier attribute identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement none if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript subscript identifier integer integer else_clause block expression_statement assignment identifier subscript identifier integer return_statement identifier
Get a user from the ldap
def _get_jar(self, command, alts=None, allow_missing=False): dirs = [] for bdir in [self._gatk_dir, self._picard_ref]: dirs.extend([bdir, os.path.join(bdir, os.pardir, "gatk")]) if alts is None: alts = [] for check_cmd in [command] + alts: for dir_check in dirs: try: check_file = config_utils.get_jar(check_cmd, dir_check) return check_file except ValueError as msg: if str(msg).find("multiple") > 0: raise else: pass if allow_missing: return None else: raise ValueError("Could not find jar %s in %s:%s" % (command, self._picard_ref, self._gatk_dir))
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier list for_statement identifier list attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list list identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier list for_statement identifier binary_operator list identifier identifier block for_statement identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement comparison_operator call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end integer block raise_statement else_clause block pass_statement if_statement identifier block return_statement none else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier attribute identifier identifier
Retrieve the jar for running the specified command.
def format_assistants_lines(cls, assistants): lines = cls._format_files(assistants, 'assistants') if assistants: lines.append('') assistant = strip_prefix(random.choice(assistants), 'assistants').replace(os.path.sep, ' ').strip() if len(assistants) == 1: strings = ['After you install this DAP, you can find help about the Assistant', 'by running "da {a} -h" .'] else: strings = ['After you install this DAP, you can find help, for example about the Assistant', '"{a}", by running "da {a} -h".'] lines.extend([l.format(a=assistant) for l in strings]) return lines
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement assignment identifier call attribute call attribute call identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end identifier argument_list if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list_comprehension call attribute identifier identifier argument_list keyword_argument identifier identifier for_in_clause identifier identifier return_statement identifier
Return formatted assistants from the given list in human readable form.
def download(url, encoding='utf-8'): import requests response = requests.get(url) response.encoding = encoding return response.text
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier return_statement attribute identifier identifier
Returns the text fetched via http GET from URL, read as `encoding`
def list_all_requests_view(request, requestType): request_type = get_object_or_404(RequestType, url_name=requestType) requests = Request.objects.filter(request_type=request_type) if not request_type.managers.filter(incumbent__user=request.user): requests = requests.exclude( ~Q(owner__user=request.user), private=True, ) page_name = "Archives - All {0} Requests".format(request_type.name.title()) return render_to_response('list_requests.html', { 'page_name': page_name, 'requests': requests, 'request_type': request_type, }, context_instance=RequestContext(request))
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list unary_operator call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier true expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier keyword_argument identifier call identifier argument_list identifier
Show all the requests for a given type in list form.
def exit(self, status=0, message=None): if status: self.logger.error(message) if self.__parser__: self.__parser__.exit(status, message) else: sys.exit(status)
module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none block if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier
Delegates to `ArgumentParser.exit`
def groups_set_topic(self, room_id, topic, **kwargs): return self.__call_api_post('groups.setTopic', roomId=room_id, topic=topic, kwargs=kwargs)
module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Sets the topic for the private group.
def __get_wbfmt_format_txt(self, data_nt): format_txt_val = getattr(data_nt, "format_txt") if format_txt_val == 1: return self.fmtname2wbfmtobj.get("very light grey") if format_txt_val == 2: return self.fmtname2wbfmtobj.get("light grey") return self.fmtname2wbfmtobj.get(format_txt_val)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end if_statement comparison_operator identifier integer block return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argument_list identifier
Return format for text cell from namedtuple field, 'format_txt'.
def _following_siblings( self, qname: Union[QualName, bool] = None) -> List[InstanceNode]: if qname and self.qual_name != qname: return [] res = [] en = self for _ in self.after: en = en.next() res.append(en) return res
module function_definition identifier parameters identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier type identifier none type generic_type identifier type_parameter type identifier block if_statement boolean_operator identifier comparison_operator attribute identifier identifier identifier block return_statement list expression_statement assignment identifier list expression_statement assignment identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
XPath - return the list of receiver's following siblings.
def print_tree(self, *, verbose=True): print("{0} ({1})".format(self.natural_name, self.filepath)) self._print_branch("", depth=0, verbose=verbose)
module function_definition identifier parameters identifier keyword_separator default_parameter identifier true block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_end keyword_argument identifier integer keyword_argument identifier identifier
Print a ascii-formatted tree representation of the data contents.
def unsubscribe(self): self.subscription = None self._user_assignment.clear() self.assignment.clear() self.subscribed_pattern = None
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier none expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none
Clear all topic subscriptions and partition assignments
def GetHashObject(self): hash_object = rdf_crypto.Hash() hash_object.num_bytes = self._bytes_read for algorithm in self._hashers: setattr(hash_object, algorithm, self._hashers[algorithm].digest()) return hash_object
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier call attribute subscript attribute identifier identifier identifier identifier argument_list return_statement identifier
Returns a `Hash` object with appropriate fields filled-in.
def _invalid_frame(fobj): fin = fobj.f_code.co_filename invalid_module = any([fin.endswith(item) for item in _INVALID_MODULES_LIST]) return invalid_module or (not os.path.isfile(fin))
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier return_statement boolean_operator identifier parenthesized_expression not_operator call attribute attribute identifier identifier identifier argument_list identifier
Select valid stack frame to process.
def api_download(service, fileId, authorisation): data = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b') headers = {'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(authorisation)} url = service + 'api/download/' + fileId r = requests.get(url, headers=headers, stream=True) r.raise_for_status() content_length = int(r.headers['Content-length']) pbar = progbar(content_length) for chunk in r.iter_content(chunk_size=CHUNK_SIZE): data.write(chunk) pbar.update(len(chunk)) pbar.close() data.seek(0) return data
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list integer return_statement identifier
Given a Send url, download and return the encrypted data and metadata
def _get_client_and_key(url, user, password, verbose=0): session = {} session['client'] = six.moves.xmlrpc_client.Server(url, verbose=verbose, use_datetime=True) session['key'] = session['client'].auth.login(user, password) return session
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute attribute identifier identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier true expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute subscript identifier string string_start string_content string_end identifier identifier argument_list identifier identifier return_statement identifier
Return the client object and session key for the client
def _fix_offset(self, state, size, arch=None): if state is not None: arch = state.arch if arch is None: raise ValueError('Either "state" or "arch" must be specified.') offset = arch.registers[self.reg_name][0] if size in self.alt_offsets: return offset + self.alt_offsets[size] elif size < self.size and arch.register_endness == 'Iend_BE': return offset + (self.size - size) return offset
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript subscript attribute identifier identifier attribute identifier identifier integer if_statement comparison_operator identifier attribute identifier identifier block return_statement binary_operator identifier subscript attribute identifier identifier identifier elif_clause boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement binary_operator identifier parenthesized_expression binary_operator attribute identifier identifier identifier return_statement identifier
This is a hack to deal with small values being stored at offsets into large registers unpredictably
def document_path_path(cls, project, database, document_path): return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document_path=**}", project=project, database=database, document_path=document_path, )
module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Return a fully-qualified document_path string.
def remove(self, name): fut = self.execute(b'REMOVE', name) return wait_ok(fut)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call identifier argument_list identifier
Remove a master from Sentinel's monitoring.
def removeXmlElement(name, directory, file_pattern, logger=None): for path, dirs, files in os.walk(os.path.abspath(directory)): for filename in fnmatch.filter(files, file_pattern): filepath = os.path.join(path, filename) remove_xml_element_file(name, filepath)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier block for_statement identifier call attribute identifier identifier argument_list identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call identifier argument_list identifier identifier
Recursively walk a directory and remove XML elements
def structure_repr(self): ret = '{%s}' % ', '.join([str(x) for x in self.elements]) return self._wrap_packed(ret)
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier
Return the LLVM IR for the structure representation
def show_multi_buffer(self): from safe.gui.tools.multi_buffer_dialog import ( MultiBufferDialog) dialog = MultiBufferDialog( self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_()
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list
Show the multi buffer tool.
def _complete_trajectory(self, trajectory, index): assert isinstance(trajectory, Trajectory) assert trajectory.last_time_step.action is None self._completed_trajectories.append(trajectory) self._trajectories[index] = Trajectory()
module function_definition identifier parameters identifier identifier identifier block assert_statement call identifier argument_list identifier identifier assert_statement comparison_operator attribute attribute identifier identifier identifier none expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list
Completes the given trajectory at the given index.
def remove_all_callbacks(self): for cb_id in list(self._next_tick_callback_removers.keys()): self.remove_next_tick_callback(cb_id) for cb_id in list(self._timeout_callback_removers.keys()): self.remove_timeout_callback(cb_id) for cb_id in list(self._periodic_callback_removers.keys()): self.remove_periodic_callback(cb_id)
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier
Removes all registered callbacks.
def sigterm(self, signum, frame): self.logger.warning("Caught signal %s. Stopping daemon." % signum) sys.exit(0)
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list integer
These actions will be done after SIGTERM.
def lower_coerce_type_block_type_data(ir_blocks, type_equivalence_hints): allowed_key_type_spec = (GraphQLInterfaceType, GraphQLObjectType) allowed_value_type_spec = GraphQLUnionType for key, value in six.iteritems(type_equivalence_hints): if (not isinstance(key, allowed_key_type_spec) or not isinstance(value, allowed_value_type_spec)): msg = (u'Invalid type equivalence hints received! Hint {} ({}) -> {} ({}) ' u'was unexpected, expected a hint in the form ' u'GraphQLInterfaceType -> GraphQLUnionType or ' u'GraphQLObjectType -> GraphQLUnionType'.format(key.name, str(type(key)), value.name, str(type(value)))) raise GraphQLCompilationError(msg) equivalent_type_names = { key.name: {x.name for x in value.types} for key, value in six.iteritems(type_equivalence_hints) } new_ir_blocks = [] for block in ir_blocks: new_block = block if isinstance(block, CoerceType): target_class = get_only_element_from_collection(block.target_class) if target_class in equivalent_type_names: new_block = CoerceType(equivalent_type_names[target_class]) new_ir_blocks.append(new_block) return new_ir_blocks
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier tuple identifier identifier expression_statement assignment identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block if_statement parenthesized_expression boolean_operator not_operator call identifier argument_list identifier identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier parenthesized_expression call attribute concatenated_string 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 identifier argument_list attribute identifier identifier call identifier argument_list call identifier argument_list identifier attribute identifier identifier call identifier argument_list call identifier argument_list identifier raise_statement call identifier argument_list identifier expression_statement assignment identifier dictionary_comprehension pair attribute identifier identifier set_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier call identifier argument_list subscript identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Rewrite CoerceType blocks to explicitly state which types are allowed in the coercion.
def setConf(self, key, value): self.sparkSession.conf.set(key, value)
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier
Sets the given Spark SQL configuration property.
def magnitude(self): return math.sqrt( reduce(lambda x, y: x + y, [x ** 2 for x in self.to_list()]) )
module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list call identifier argument_list lambda lambda_parameters identifier identifier binary_operator identifier identifier list_comprehension binary_operator identifier integer for_in_clause identifier call attribute identifier identifier argument_list
Return magnitude of the vector.
def format_percent_field(__, prec, number, locale): prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec))
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier conditional_expression identifier comparison_operator identifier none call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list none return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier tuple identifier identifier
Formats a percent field.
def _get_comments(group_tasks): comments = {} for status, human in _COMMENTS: num_tasks = _get_number_of_tasks_for(status, group_tasks) if num_tasks: space = " " if status in _PENDING_SUB_STATUSES else "" comments[status] = '{space}* {num_tasks} {human}:\n'.format( space=space, num_tasks=num_tasks, human=human) return comments
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator identifier identifier string string_start string_end expression_statement assignment subscript identifier identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier
Get the human readable comments and quantities for the task types.
def with_base_config(base_config, extra_config): config = copy.deepcopy(base_config) config.update(extra_config) return config
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Returns the given config dict merged with a base agent conf.
def _convert_to_array(array_like, dtype): if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier
Convert Matrix attributes which are array-like or buffer to array.