code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def itermonthdays(cls, year, month): for day in NepCal.itermonthdates(year, month): if day.month == month: yield day.day else: yield 0
Similar to itermonthdates but returns day number instead of NepDate object
def reduce(self): support = frozenset(range(1, self.nvars+1)) new_clauses = set() for clause in self.clauses: vs = list(support - {abs(uniqid) for uniqid in clause}) if vs: for num in range(1 << len(vs)): new_part = {v if bit_on(num, i)...
Reduce to a canonical form.
def signals(self, signals=('QUIT', 'USR1', 'USR2')): for sig in signals: signal.signal(getattr(signal, 'SIG' + sig), self.handler)
Register our signal handler
def ensure_iam(self, publisher=None): topic = self.get_topic_param() client = self.session.client('pubsub', 'v1', 'projects.topics') policy = client.execute_command('getIamPolicy', {'resource': topic}) policy.pop('etag') found = False for binding in policy.get('bindings',...
Ensure the given identities are in the iam role bindings for the topic.
def update_active(self): if self.active is not None: self.update_state(self.active, "normal") if self.current_iid == self.active: self._active = None return self._active = self.current_iid if self.active is not None: self.update_state(self....
Update the active marker on the marker Canvas
def _symbolic_product_helper(): from sympy import symbols, Matrix D11, D12, D13, D21, D22, D23, D31, D32, D33 =\ symbols('D11, D12, D13, D21, D22, D23, D31, D32, D33') D = Matrix([[D11, D12, D13], [D21, D22, D23], [D31, D32, D33]]) grad = Matrix([['dx', 'dy', 'dz']]).T div = grad.T a = d...
Use SymPy to generate the 3D products for diffusion_stencil_3d.
def SetValue(self, row, col, value, refresh=True): value = "".join(value.split("\n")) key = row, col, self.grid.current_table old_code = self.grid.code_array(key) if old_code is None: old_code = "" if value != old_code: self.grid.actions.set_code(key, valu...
Set the value of a cell, merge line breaks
def memoize(f): @wraps(f) def w(*args, **kw): memoize.mem[f] = v = f(*args, **kw) return v return w
Cache value returned by the function.
def make_end_to_end_distance_plot(nb_segments, end_to_end_distance, neurite_type): plt.figure() plt.plot(nb_segments, end_to_end_distance) plt.title(neurite_type) plt.xlabel('Number of segments') plt.ylabel('End-to-end distance') plt.show()
Plot end-to-end distance vs number of segments
def print_col_perc_table(table, row_labels, col_labels): r1c1, r1c2, r2c1, r2c2 = map(float, table) col1 = r1c1 + r2c1 col2 = r1c2 + r2c2 blocks = [ (r1c1, col1), (r1c2, col2), (r2c1, col1), (r2c2, col2)] new_table = [] for cell, row in blocks: try: ...
given a table, print the cols as percentages
def handle_finish(queue_name): task_id = request.form.get('task_id', type=str) owner = request.form.get('owner', request.remote_addr, type=str) error = request.form.get('error', type=str) is not None try: work_queue.finish(queue_name, task_id, owner, error=error) except work_queue.Error, e: ...
Marks a task on a queue as finished.
def pub(self, topic, message): with self.random_connection() as client: client.pub(topic, message) return self.wait_response()
Publish the provided message to the provided topic
def serve(opts): resources = _load(opts.resources, opts.output_dir) opts.output_dir = resources.output_dir if not os.path.exists(opts.output_dir): sys.stderr.write("Resources dir '{}' not found. Did you fetch?\n".format(opts.output_dir)) return 1 backend.PyPIResource.build_pypi_indexes(...
Run a light-weight HTTP server hosting previously mirrored resources
def _check_y(y): if not isinstance(y, np.ndarray): raise TypeError("y must be numpy array. Typically y contains " "the entire test set labels. Got " + str(y) + " of type " + str(type(y)))
Makes sure a `y` argument is a vliad numpy dataset.
def cross_entropy_error(self, input_data, targets, average=True, cache=None, prediction=False): if cache is not None: activations = cache else: activations = \ self.feed_forward(input_data, prediction=prediction) loss = cross_entr...
Return the cross entropy error
def new_bundle(self, name: str, created_at: dt.datetime=None) -> models.Bundle: new_bundle = self.Bundle(name=name, created_at=created_at) return new_bundle
Create a new file bundle.
def OnContextMenu(self, event): self.grid.PopupMenu(self.grid.contextmenu) event.Skip()
Context menu event handler
def format_installed_dap_list(simple=False): lines = [] if simple: for pkg in sorted(get_installed_daps()): lines.append(pkg) else: for pkg, instances in sorted(get_installed_daps_detailed().items()): versions = [] for instance in instances: ...
Formats all installed DAPs in a human readable form to list of lines
def ensure_annotations(resources, data): transcript_gff = tz.get_in(["rnaseq", "transcripts"], resources) if transcript_gff and utils.file_exists(transcript_gff): out_dir = os.path.join(tz.get_in(["dirs", "work"], data), "inputs", "data", "annotations") resources["...
Prepare any potentially missing annotations for downstream processing in a local directory.
def pw_compare_class_sets(self, cset1: Set[ClassId], cset2: Set[ClassId]) -> Tuple[ICValue, ICValue, ICValue]: pairs = self.mica_ic_df.loc[cset1, cset2] max0 = pairs.max(axis=0) max1 = pairs.max(axis=1) idxmax0 = pairs.idxmax(axis=0) idxmax1 = pairs.idxmax(axis=1) mean0 =...
Compare two class profiles
def _attach_obj(self, req, obj): json.dump(obj, req) req['content-type'] = self._content_type
Helper method to attach obj to req as JSON data.
def process_view(self, request, view_func, view_args, view_kwargs): view_keys = list(VIEW_METHOD_DATA.keys()) for key in view_keys: del VIEW_METHOD_DATA[key] self.view_data = {} try: cbv = view_func.view_class except AttributeError: cbv = False...
Collect data on Class-Based Views
def humanTimeConverter(): if len(sys.argv) == 2: print humanFriendlyTime(seconds=int(sys.argv[1])) else: for line in sys.stdin: print humanFriendlyTime(int(line)) sys.exit(0)
Cope whether we're passed a time in seconds on the command line or via stdin
def _add_get_tracking_url(cls): def get_tracking_url(self): url = reverse('admin:tracking_fields_trackingevent_changelist') object_id = '{0}%3A{1}'.format( ContentType.objects.get_for_model(self).pk, self.pk ) return '{0}?object={1}'.format(url, object_id) ...
Add a method to get the tracking url of an object.
def _update_color_rgb(self, event=None): if event is None or event.widget.old_value != event.widget.get(): r = self.red.get() g = self.green.get() b = self.blue.get() h, s, v = rgb_to_hsv(r, g, b) self.hue.set(h) self.saturation.set(s) ...
Update display after a change in the RGB spinboxes.
def isHereDoc(self, block, column): dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isHereDoc(data, column)
Check if character at column is a here document
def _query_uncompressed(options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, check_keys=False): op_query, max_bson_size = _query( options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, ...
Internal query message helper.
def authenticate(self, username, password): if username is None or password is None: return False if not re.match("^[A-Za-z0-9_-]*$", username): return False user_dn = self.get_user_dn(username) server = ldap3.Server( self.uri, use_...
Authenticate the user with a bind on the LDAP server
def enable_mesos_basic_authentication(principal, password): restart = False secrets_file = '/etc/mesos/secrets' secrets_entry = '%s %s' % (principal, password) if not file_contains(filename=secrets_file, text=secrets_entry, use_sudo=True): file_append(filename=secrets_fi...
enables and adds a new authorized principal
def find_packages(name, pkg_dir): for c in (FileSystemPackageBuilder, ZipPackageBuilder, ExcelPackageBuilder): package_path, cache_path = c.make_package_path(pkg_dir, name) if package_path.exists(): yield c.type_code, package_path, cache_path
Locate pre-built packages in the _packages directory
def import_usr_dir(usr_dir): if not usr_dir: return if usr_dir == INTERNAL_USR_DIR_PACKAGE: importlib.import_module(INTERNAL_USR_DIR_PACKAGE) return dir_path = os.path.abspath(os.path.expanduser(usr_dir).rstrip("/")) containing_dir, module_name = os.path.split(dir_path) tf.logging.info("Importing ...
Import module at usr_dir, if provided.
def _to_desired_dates(self, arr): times = utils.times.extract_months( arr[internal_names.TIME_STR], self.months ) return arr.sel(time=times)
Restrict the xarray DataArray or Dataset to the desired months.
async def remove_user(self, username): client_facade = client.UserManagerFacade.from_connection( self.connection()) user = tag.user(username) await client_facade.RemoveUser([client.Entity(user)])
Remove a user from this controller.
def _get_asset(self, asset_uid): uri = self.uri + '/v2/assets/' + asset_uid headers = self._get_headers() return self.service._get(uri, headers=headers)
Returns raw response for an given asset by its unique id.
def pop_range(self, start, stop=None, withscores=True, **options): return self.backend.execute( self.client.zpopbyscore(self.id, start, stop, withscores=withscores, **options), partial(self._range, withscores))
Remove and return a range from the ordered set by score.
def post_message(self, msg): super(mavlogfile, self).post_message(msg) if self.planner_format: self.f.read(1) self.timestamp = msg._timestamp self._last_message = msg if msg.get_type() != "BAD_DATA": self._last_timestamp = msg._timestamp msg._link ...
add timestamp to message
def use_plenary_grade_system_view(self): self._object_views['grade_system'] = PLENARY for session in self._get_provider_sessions(): try: session.use_plenary_grade_system_view() except AttributeError: pass
Pass through to provider GradeSystemLookupSession.use_plenary_grade_system_view
def serve(self, host='127.0.0.1', port=5000): from meinheld import server, middleware server.listen((host, port)) server.run(middleware.WebSocketMiddleware(self.app))
Serve predictions as an API endpoint.
def paragraph(node): text = '' if node.string_content is not None: text = node.string_content o = nodes.paragraph('', ' '.join(text)) o.line = node.sourcepos[0][0] for n in MarkDown(node): o.append(n) return o
Process a paragraph, which includes all content under it
def usergroups_list(self, **kwargs) -> SlackResponse: self._validate_xoxp_token() return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
List all User Groups for a team
def count(self): cursor = self.conn.cursor() with contextlib.closing(cursor): cursor.execute('SELECT COUNT(*) FROM events') res = cursor.fetchone() return res[0]
Return the number of events in the db.
def copy_path_to_clipboard(self): path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug('path copied: %s' % path)
Copies the file path to the clipboard
def increment(self, key: Any, by: int = 1) -> None: if key is not None: self[key] = self.get(key, 0) + by
Increments the value set against a key. If the key is not present, 0 is assumed as the initial state
def _get_project_types(self): project_types = get_available_project_types() projects = [] for project in project_types: projects.append(project.PROJECT_TYPE_NAME) return projects
Get all available project types.
def make_dir(cls, directory_name): if not os.path.exists(directory_name): os.makedirs(directory_name)
Create a directory in the system
def validate(self, value): if not isinstance(value, (list, tuple)) or isinstance(value, str_types): self.raise_error('Only lists and tuples may be used in the ListField vs provided {0}' .format(type(value).__name__)) super(ListField, self).validate(value)
Make sure that the inspected value is of type `list` or `tuple`
def tcp_receive(self): data = self.conn.recv(self.BUFFER_SIZE) if type(data) != str: data = data.decode("utf-8") return str(data)
Receive data from TCP port.
def do_GET(self): if not self._client_allowed(): return try: (_, _, path, query, _) = urlsplit(self.path) params = parse_qs(query) for prefix, handler in self._GET_handlers: if self._maybe_handle(prefix, handler, path, params): return if path == '/': self....
GET method implementation for BaseHTTPRequestHandler.
def _get_deadline(results, timeout=None): start_time = time() all_deadlines = set(result.get_deadline() for result in results) all_deadlines.discard(None) if timeout is not None: all_deadlines.add(start_time + timeout) return min(all_deadlines) if all_deadlines else None
returns the earliest deadline point in time
def _make_parser(streamer, the_struct): "Return a function that parses the given structure into a dict" struct_items = [s.split(":") for s in the_struct.split()] names = [s[0] for s in struct_items] types = ''.join(s[1] for s in struct_items) def f(message_stream): return streamer.parse_as_d...
Return a function that parses the given structure into a dict
def plot_losses(self, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]: "Plot training and validation losses." fig, ax = plt.subplots(1,1) losses = self._split_list(self.losses, skip_start, skip_end) iterations = self._split_list(range_of(self.losses), skip_s...
Plot training and validation losses.
def getSheet(book=None,sheet=None): if book and not book.lower() in [x.lower() for x in bookNames()]: print("book %s doesn't exist"%book) return if book is None: book=activeBook().lower() if book is None: print("no book given or selected") return if sheet and not ...
returns the pyorigin object for a sheet.
def on_pubmsg(self, connection, event): for message in event.arguments(): self.log(event, message) command_args = filter(None, message.split()) command_name = command_args.pop(0) for handler in self.events["command"]: if handler.event.args["command...
Log any public messages, and also handle the command event.
def catch_error(func): import amqp try: import pika.exceptions connect_exceptions = ( pika.exceptions.ConnectionClosed, pika.exceptions.AMQPConnectionError, ) except ImportError: connect_exceptions = () connect_exceptions += ( select.error,...
Catch errors of rabbitmq then reconnect
def unlock(self): if not hasattr(self, 'session'): raise RuntimeError('Error detected! The session that you want to close does not exist any more!') logger.debug("Closed database session of '%s'" % self._database) self.session.close() del self.session
Closes the session to the database.
def replay_data(self, replay_path): with gfile.Open(self.abs_replay_path(replay_path), "rb") as f: return f.read()
Return the replay data given a path to the replay.
def are_plugins_in_order(plugins_conf, *plugins_names): all_plugins_names = [plugin['name'] for plugin in plugins_conf or []] start_index = 0 for plugin_name in plugins_names: try: start_index = all_plugins_names.index(plugin_name, start_index) except ValueError: retu...
Check if plugins are configured in given order.
def _get(self, url, query=None, **kwargs): return self._request('get', url, query, **kwargs)
Wrapper for the HTTP GET request.
def BIF_templates(self): network_template = Template('network $name {\n}\n') variable_template = Template( ) property_template = Template(' property $prop ;\n') probability_template = Template( ) return network_template, variable_template, property_template, probability_templa...
Create template for writing in BIF format
def on_top_level_changed(self, top_level): if top_level: self.undock_action.setDisabled(True) else: self.undock_action.setDisabled(False)
Actions to perform when a plugin is undocked to be moved.
def add_capability(self, cls): if _debug: Collector._debug("add_capability %r", cls) bases = (self.__class__, cls) if _debug: Collector._debug(" - bases: %r", bases) self.capabilities.append(cls) newtype = type(self.__class__.__name__ + '+' + cls.__name__, bases, {}) s...
Add a capability to this object.
def should_stop_early(self) -> bool: if self._patience is None: return False else: return self._epochs_with_no_improvement >= self._patience
Returns true if improvement has stopped for long enough.
def reload_sources(self, names): try: self.like.logLike.loadSourceMaps(names, True, True) self._scale_srcmap(self._src_expscale, check_header=False, names=names) except: for name in names: self.reload_source(name)
Recompute the source map for a list of sources in the model.
def units(self, varname): if not varname in self.mapping.vars: raise fgFDMError('Unknown variable %s' % varname) return self.mapping.vars[varname].units
return the default units of a variable
def _checkAndConvertIndex(self, index): if index < 0: index = len(self) + index if index < 0 or index >= self._doc.blockCount(): raise IndexError('Invalid block index', index) return index
Check integer index, convert from less than zero notation
def download_content_gui(**args): global row if not args ['directory']: args ['directory'] = args ['query'].replace(' ', '-') root1 = Frame(root) t1 = threading.Thread(target = search_function, args = (root1, args['query'], args['website'], args['file_type'], args['limit'],args['option'])) t1.start() t...
function to fetch links and download them
def hash_key(self, key): for i, destination_key in enumerate(self._dict): if key < destination_key: return destination_key return key
"Hash" all keys in a timerange to the same value.
def OnAttributesToolbarToggle(self, event): self.main_window.attributes_toolbar.SetGripperVisible(True) attributes_toolbar_info = \ self.main_window._mgr.GetPane("attributes_toolbar") self._toggle_pane(attributes_toolbar_info) event.Skip()
Format toolbar toggle event handler
def encode(self, value): if type(value) == str and self.enum and value in self.enum: value = self.enum[value] if type(value) == int: if self.shift > 0: value <<= self.shift if self.mask is not None: value &= self.mask return sel...
Encodes the given value according to this FieldDefinition.
def load_search_space(path): content = json.dumps(get_json_content(path)) if not content: raise ValueError('searchSpace file should not be empty') return content
load search space content
def start(self, *args, **kwargs): self.queue = Queue() thread = Thread(target=self._threaded, args=args, kwargs=kwargs) thread.start() return Asynchronous.Result(self.queue, thread)
Start execution of the function.
def edit(community): form = EditCommunityForm(formdata=request.values, obj=community) deleteform = DeleteCommunityForm() ctx = mycommunities_ctx() ctx.update({ 'form': form, 'is_new': False, 'community': community, 'deleteform': deleteform, }) if form.validate_on_...
Create or edit a community.
def wait_for_relation(service_name, relation_name, timeout=120): start_time = time.time() while True: relation = unit_info(service_name, 'relations').get(relation_name) if relation is not None and relation['state'] == 'up': break if time.time() - start_time >= timeout: ...
Wait `timeout` seconds for a given relation to come up.
def _get_data_attr(data, attr): if isinstance(data, dict): data = data['__id'] data_obj = Data.objects.get(id=data) return getattr(data_obj, attr)
Get data object field.
def add_reader(self, fd, callback): " Start watching the file descriptor for read availability. " h = msvcrt.get_osfhandle(fd) self._read_fds[h] = callback
Start watching the file descriptor for read availability.
def _find_usage_instances(self): paginator = self.conn.get_paginator('describe_db_instances') for page in paginator.paginate(): for instance in page['DBInstances']: self.limits['Read replicas per master']._add_current_usage( len(instance['ReadReplicaDBInst...
find usage for DB Instances and related limits
def convert(cls, record): if isinstance(record, list): return [cls._convert(r) for r in record] else: return [cls._convert(record)]
Converts a single dictionary or list of dictionaries into converted list of dictionaries.
def _pid_to_id(self, pid): return d1_common.url.joinPathElements( self._base_url, self._version_tag, "resolve", d1_common.url.encodePathElement(pid), )
Converts a pid to a URI that can be used as an OAI-ORE identifier.
def _getEventsByDay(self, request, firstDay, lastDay): return getAllEventsByDay(request, firstDay, lastDay, home=self)
Return my child events for the dates given, grouped by day.
def update_command(args): updated = update_requirements_file( args.requirements_file, args.skip_packages) if updated: print('Updated requirements in {}:'.format(args.requirements_file)) for item in updated: print(' * {} from {} to {}.'.format(*item)) else: print('...
Updates all dependencies the specified requirements file.
def _SafeEncodeBytes(field, value): try: if field.repeated: result = [base64.urlsafe_b64encode(byte) for byte in value] else: result = base64.urlsafe_b64encode(value) complete = True except TypeError: result = value complete = False return Code...
Encode the bytes in value as urlsafe base64.
def remove_external_references_from_srl_layer(self): if self.srl_layer is not None: for pred in self.srl_layer.get_predicates(): pred.remove_external_references() pred.remove_external_references_from_roles()
Removes all external references present in the term layer
def light(cls): "Make the current foreground color light." wAttributes = cls._get_text_attributes() wAttributes |= win32.FOREGROUND_INTENSITY cls._set_text_attributes(wAttributes)
Make the current foreground color light.
def _add_header_domains_xml(self, document): for domain, attrs in self.header_domains.items(): header_element = document.createElement( 'allow-http-request-headers-from' ) header_element.setAttribute('domain', domain) header_element.setAttribute('h...
Generates the XML elements for allowed header domains.
def update_entries(entries: Entries, data: dict) -> None: for entry in entries: entry.update(data)
Update each entry in the list with some data.
def build(self) -> Application: pipelines = self._build_pipelines() self._factory.new('Application', pipelines) return self._factory['Application']
Put the application together.
def _get_stream(self) -> Iterator: if self._stream is None: self._stream = iter(self._get_stream_fn()) return self._stream
Possibly create and return raw dataset stream iterator.
def read_mac(self): words = [self.read_efuse(2), self.read_efuse(1)] bitstring = struct.pack(">II", *words) bitstring = bitstring[2:8] try: return tuple(ord(b) for b in bitstring) except TypeError: return tuple(bitstring)
Read MAC from EFUSE region
def timestep_text(self): if self.header.analysis_period.timestep == 1: return 'Hourly' else: return '{} Minute'.format(int(60 / self.header.analysis_period.timestep))
Return a text string representing the timestep of the collection.
def _send(self): while len(self.queue) > 0: metric = self.queue.popleft() path = '%s.%s.%s' % ( metric.getPathPrefix(), metric.getCollectorPath(), metric.getMetricPath() ) topic, value, timestamp = str(metric).split(...
Take metrics from queue and send it to Datadog API
def paired_paths(main_path, fmt, formats): if not formats: return [(main_path, {'extension': os.path.splitext(main_path)[1]})] formats = long_form_multiple_formats(formats) base = base_path(main_path, fmt) paths = [full_path(base, fmt) for fmt in formats] if main_path not in paths: r...
Return the list of paired notebooks, given main path, and the list of formats
def doc_open(): doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') if sys.platform == 'darwin': subprocess.check_call(['open', doc_index]) elif sys.platform == 'win32': subprocess.check_call(['start', doc_index], shell=True) elif sys.platform == 'linux2': sub...
Build the HTML docs and open them in a web browser.
def _bpe_to_words(sentence, delimiter='@@'): words = [] word = '' delimiter_len = len(delimiter) for subwords in sentence: if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter: word += subwords[:-delimiter_len] else: word += subwords ...
Convert a sequence of bpe words into sentence.
def q(self, val): self._q = np.asarray(val) self.Q = cumsum(val)
Setter method for q.
def diff(self): self._copyfiles = False self._updatefiles = False self._purge = False self._creatdirs = False self._updatefiles = False self.log('Difference of directory %s from %s\n' % (self._dir2, self._dir1)) self._diff(self._dir1, self._dir2)
Only report difference in content between two directories
def init(self, aggregators): assert len(aggregators) == self.num_aggregation_workers, aggregators if len(self.remote_evaluators) < self.num_aggregation_workers: raise ValueError( "The number of aggregation workers should not exceed the " "number of total evalu...
Deferred init so that we can pass in previously created workers.
def largest_indices(arr, n): "Returns the `n` largest indices from a numpy array `arr`." flat = arr.flatten() indices = np.argpartition(flat, -n)[-n:] indices = indices[np.argsort(-flat[indices])] return np.unravel_index(indices, arr.shape)
Returns the `n` largest indices from a numpy array `arr`.
def show_setup(self): shell = os.getenv('SHELL') if not shell: raise SystemError("No $SHELL env var found") shell = os.path.basename(shell) if shell not in self.script_body: raise SystemError("Unsupported shell: %s" % shell) tplvars = { "prog":...
Provide a helper script for the user to setup completion.
def apis(self): value = self.attributes['apis'] if isinstance(value, six.string_types): value = shlex.split(value) return value
List of API to test
def lookup_dirent(event, filesystem_content, journal_content): for dirent in filesystem_content[event.inode]: if dirent.path.endswith(event.name): return dirent path = lookup_folder(event, filesystem_content) if path is not None: return Dirent(event.inode, path, -1, None, False, ...
Lookup the dirent given a journal event.