_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q56500
OpanXYZ.dist_single
train
def dist_single(self, g_num, at_1, at_2): """ Distance between two atoms. Parameters ---------- g_num |int| -- Index of the desired geometry at_1 |int| -- Index of the first atom at_2 |int| -- Index of the second atom Return...
python
{ "resource": "" }
q56501
OpanXYZ.dist_iter
train
def dist_iter(self, g_nums, ats_1, ats_2, invalid_error=False): """ Iterator over selected interatomic distances. Distances are in Bohrs as with :meth:`dist_single`. See `above <toc-generators_>`_ for more information on calling options. Parameters ---------- g...
python
{ "resource": "" }
q56502
OpanXYZ.angle_single
train
def angle_single(self, g_num, at_1, at_2, at_3): """ Spanning angle among three atoms. The indices `at_1` and `at_3` can be the same (yielding a trivial zero angle), but `at_2` must be different from both `at_1` and `at_3`. Parameters ---------- g_num ...
python
{ "resource": "" }
q56503
OpanXYZ.angle_iter
train
def angle_iter(self, g_nums, ats_1, ats_2, ats_3, invalid_error=False): """ Iterator over selected atomic angles. Angles are in degrees as with :meth:`angle_single`. See `above <toc-generators_>`_ for more information on calling options. Parameters ---------- g...
python
{ "resource": "" }
q56504
OpanXYZ.dihed_iter
train
def dihed_iter(self, g_nums, ats_1, ats_2, ats_3, ats_4, \ invalid_error=False): """ Iterator over selected dihedral angles. Angles are in degrees as with :meth:`dihed_single`. See `above <toc-generators_>`_ for more information on ca...
python
{ "resource": "" }
q56505
OpanXYZ.displ_single
train
def displ_single(self, g_num, at_1, at_2): """ Displacement vector between two atoms. Returns the displacement vector pointing from `at_1` toward `at_2` from geometry `g_num`. If `at_1` == `at_2` a strict zero vector is returned. Displacement vector is returned in units of Bohr...
python
{ "resource": "" }
q56506
OpanXYZ.displ_iter
train
def displ_iter(self, g_nums, ats_1, ats_2, invalid_error=False): """ Iterator over indicated displacement vectors. Displacements are in Bohrs as with :meth:`displ_single`. See `above <toc-generators_>`_ for more information on calling options. Parameters ---------- ...
python
{ "resource": "" }
q56507
OpanXYZ._none_subst
train
def _none_subst(self, *args): """ Helper function to insert full ranges for |None| for X_iter methods. Custom method, specifically tailored, taking in the arguments from an X_iter method and performing the replacement of |None| after error-checking the arguments for a max of one |None| ...
python
{ "resource": "" }
q56508
guess_external_url
train
def guess_external_url(local_host, port): """Return a URL that is most likely to route to `local_host` from outside. The point is that we may be running on a remote host from the user's point of view, so they can't access `local_host` from a Web browser just by typing ``http://localhost:12345/``. "...
python
{ "resource": "" }
q56509
DataFrameBuilder._check_column_lengths
train
def _check_column_lengths(self): """ Make sure columns are of the same length or else DataFrame construction will fail. """ column_lengths_dict = { name: len(xs) for (name, xs) in self.columns_dict.items() } unique_column_length...
python
{ "resource": "" }
q56510
OpanVPT2.new_from_files
train
def new_from_files(self, basepath, basename, repo, \ bohrs=False, \ software=_E_SW.ORCA, \ repo_clobber=False, **kwargs): """ Initialize with data from files. """ # Imports import os from os import path as osp ...
python
{ "resource": "" }
q56511
remote_exception
train
def remote_exception(exc, tb): """ Metaclass that wraps exception type in RemoteException """ if type(exc) in exceptions: typ = exceptions[type(exc)] return typ(exc, tb) else: try: typ = type(exc.__class__.__name__, (RemoteException, type(exc)), ...
python
{ "resource": "" }
q56512
reads_overlapping_variants
train
def reads_overlapping_variants(variants, samfile, **kwargs): """ Generates sequence of tuples, each containing a variant paired with a list of AlleleRead objects. Parameters ---------- variants : varcode.VariantCollection samfile : pysam.AlignmentFile use_duplicate_reads : bool ...
python
{ "resource": "" }
q56513
group_reads_by_allele
train
def group_reads_by_allele(allele_reads): """ Returns dictionary mapping each allele's nucleotide sequence to a list of supporting AlleleRead objects. """ allele_to_reads_dict = defaultdict(list) for allele_read in allele_reads: allele_to_reads_dict[allele_read.allele].append(allele_read)...
python
{ "resource": "" }
q56514
AlleleRead.from_locus_read
train
def from_locus_read(cls, locus_read, n_ref): """ Given a single LocusRead object, return either an AlleleRead or None Parameters ---------- locus_read : LocusRead Read which overlaps a variant locus but doesn't necessarily contain the alternate nucleotide...
python
{ "resource": "" }
q56515
most_common_nucleotides
train
def most_common_nucleotides(partitioned_read_sequences): """ Find the most common nucleotide at each offset to the left and right of a variant. Parameters ---------- partitioned_read_sequences : list of tuples Each tuple has three elements: - sequence before mutant nucleotid...
python
{ "resource": "" }
q56516
point_displ
train
def point_displ(pt1, pt2): """ Calculate the displacement vector between two n-D points. pt1 - pt2 .. todo:: Complete point_disp docstring """ #Imports import numpy as np # Make iterable if not np.iterable(pt1): pt1 = np.float64(np.array([pt1])) else: pt1 = np.fl...
python
{ "resource": "" }
q56517
point_dist
train
def point_dist(pt1, pt2): """ Calculate the Euclidean distance between two n-D points. |pt1 - pt2| .. todo:: Complete point_dist docstring """ # Imports from scipy import linalg as spla dist = spla.norm(point_displ(pt1, pt2)) return dist
python
{ "resource": "" }
q56518
point_rotate
train
def point_rotate(pt, ax, theta): """ Rotate a 3-D point around a 3-D axis through the origin. Handedness is a counter-clockwise rotation when viewing the rotation axis as pointing at the observer. Thus, in a right-handed x-y-z frame, a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point...
python
{ "resource": "" }
q56519
point_reflect
train
def point_reflect(pt, nv): """ Reflect a 3-D point through a plane intersecting the origin. nv defines the normal vector to the plane (needs not be normalized) .. todo:: Complete point_reflect docstring Raises ------ ValueError : If pt or nv are not reducible to 3-D vectors ValueError : I...
python
{ "resource": "" }
q56520
geom_reflect
train
def geom_reflect(g, nv): """ Reflection symmetry operation. nv is normal vector to reflection plane g is assumed already translated to center of mass @ origin .. todo:: Complete geom_reflect docstring """ # Imports import numpy as np # Force g to n-vector g = make_nd_vec(g, nd=N...
python
{ "resource": "" }
q56521
geom_rotate
train
def geom_rotate(g, ax, theta): """ Rotation symmetry operation. ax is rotation axis g is assumed already translated to center of mass @ origin Sense of rotation is the same as point_rotate .. todo:: Complete geom_rotate docstring """ # Imports import numpy as np # Force g to n-...
python
{ "resource": "" }
q56522
symm_op
train
def symm_op(g, ax, theta, do_refl): """ Perform general point symmetry operation on a geometry. .. todo:: Complete symm_op docstring """ # Imports import numpy as np # Depend on lower functions' geometry vector coercion. Just # do the rotation and, if indicated, the reflection. gx =...
python
{ "resource": "" }
q56523
geom_find_rotsymm
train
def geom_find_rotsymm(g, atwts, ax, improp, \ nmax=_DEF.SYMM_MATCH_NMAX, \ tol=_DEF.SYMM_MATCH_TOL): """ Identify highest-order symmetry for a geometry on a given axis. Regular and improper axes possible. .. todo:: Complete geom_find_rotsymm docstring """ # Imports import num...
python
{ "resource": "" }
q56524
g_subset
train
def g_subset(g, atwts, atwt, digits=_DEF.SYMM_ATWT_ROUND_DIGITS): """ Extract a subset of a geometry matching a desired atom. .. todo:: Complete g_subset docstring """ # Imports import numpy as np # Ensure g and atwts are n-D vectors g = make_nd_vec(g, nd=None, t=np.float64, ...
python
{ "resource": "" }
q56525
mtx_refl
train
def mtx_refl(nv, reps=1): """ Generate block-diagonal reflection matrix about nv. reps must be >=1 and indicates the number of times the reflection matrix should be repeated along the block diagonal. Typically this will be the number of atoms in a geometry. .. todo:: Complete mtx_refl docstring ...
python
{ "resource": "" }
q56526
mtx_rot
train
def mtx_rot(ax, theta, reps=1): """ Generate block-diagonal rotation matrix about ax. [copy handedness from somewhere] .. todo:: Complete mtx_rot docstring """ # Imports import numpy as np from scipy import linalg as spla from ..const import PRM # Ensure |ax| is large enough for...
python
{ "resource": "" }
q56527
ff
train
def ff(items, targets): """First-Fit This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. Complexity O(n^2) """ bins = [(target, []) for target in targets] skip = [] for item in items: for target, content in bins: if item...
python
{ "resource": "" }
q56528
ffd
train
def ffd(items, targets, **kwargs): """First-Fit Decreasing This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. This algorithm differs only from Next-Fit Decreasing in having a 'sort'; that is, the items are pre-sorted (largest to smallest). Com...
python
{ "resource": "" }
q56529
mr
train
def mr(items, targets, **kwargs): """Max-Rest Complexity O(n^2) """ bins = [(target, []) for target in targets] skip = [] for item in items: capacities = [target - sum(content) for target, content in bins] weighted = weight(capacities, **kwargs) (target, content), capa...
python
{ "resource": "" }
q56530
bf
train
def bf(items, targets, **kwargs): """Best-Fit Complexity O(n^2) """ bins = [(target, []) for target in targets] skip = [] for item in items: containers = [] capacities = [] for target, content in bins: capacity = target - sum(content) if item <= ...
python
{ "resource": "" }
q56531
bfd
train
def bfd(items, targets, **kwargs): """Best-Fit Decreasing Complexity O(n^2) """ sizes = zip(items, weight(items, **kwargs)) sizes = sorted(sizes, key=operator.itemgetter(1), reverse=True) items = map(operator.itemgetter(0), sizes) return bf(items, targets, **kwargs)
python
{ "resource": "" }
q56532
trim_sequences
train
def trim_sequences(variant_sequence, reference_context): """ A VariantSequence and ReferenceContext may contain a different number of nucleotides before the variant locus. Furthermore, the VariantSequence is always expressed in terms of the positive strand against which it aligned, but reference tra...
python
{ "resource": "" }
q56533
count_mismatches_before_variant
train
def count_mismatches_before_variant(reference_prefix, cdna_prefix): """ Computes the number of mismatching nucleotides between two cDNA sequences before a variant locus. Parameters ---------- reference_prefix : str cDNA sequence of a reference transcript before a variant locus cdna...
python
{ "resource": "" }
q56534
count_mismatches_after_variant
train
def count_mismatches_after_variant(reference_suffix, cdna_suffix): """ Computes the number of mismatching nucleotides between two cDNA sequences after a variant locus. Parameters ---------- reference_suffix : str cDNA sequence of a reference transcript after a variant locus cdna_suffix...
python
{ "resource": "" }
q56535
compute_offset_to_first_complete_codon
train
def compute_offset_to_first_complete_codon( offset_to_first_complete_reference_codon, n_trimmed_from_reference_sequence): """ Once we've aligned the variant sequence to the ReferenceContext, we need to transfer reading frame from the reference transcripts to the variant sequences. P...
python
{ "resource": "" }
q56536
match_variant_sequence_to_reference_context
train
def match_variant_sequence_to_reference_context( variant_sequence, reference_context, min_transcript_prefix_length, max_transcript_mismatches, include_mismatches_after_variant=False, max_trimming_attempts=2): """ Iteratively trim low-coverage subsequences of a var...
python
{ "resource": "" }
q56537
GeneticCode._check_codons
train
def _check_codons(self): """ If codon table is missing stop codons, then add them. """ for stop_codon in self.stop_codons: if stop_codon in self.codon_table: if self.codon_table[stop_codon] != "*": raise ValueError( ...
python
{ "resource": "" }
q56538
GeneticCode.copy
train
def copy( self, name, start_codons=None, stop_codons=None, codon_table=None, codon_table_changes=None): """ Make copy of this GeneticCode object with optional replacement values for all fields. """ new_start_...
python
{ "resource": "" }
q56539
Listener.start
train
def start(self): """ Start listening to changes """ self.running = True self.thread = threading.Thread(target=self._main_loop) self.thread.start()
python
{ "resource": "" }
q56540
Listener.subscribe
train
def subscribe(self, field_names): """ Subscribe to given fields. Special fields cannot be subscribed to and will be checked on every iteration. These include: * loco name * coordinates * fuel level * gradient * current heading * is in tunnel ...
python
{ "resource": "" }
q56541
PatternGenerator.set_matrix_dimensions
train
def set_matrix_dimensions(self, bounds, xdensity, ydensity): """ Change the dimensions of the matrix into which the pattern will be drawn. Users of this class should call this method rather than changing the bounds, xdensity, and ydensity parameters directly. Subclasses can ove...
python
{ "resource": "" }
q56542
PatternGenerator.state_push
train
def state_push(self): "Save the state of the output functions, to be restored with state_pop." for of in self.output_fns: if hasattr(of,'state_push'): of.state_push() super(PatternGenerator, self).state_push()
python
{ "resource": "" }
q56543
PatternGenerator.state_pop
train
def state_pop(self): "Restore the state of the output functions saved by state_push." for of in self.output_fns: if hasattr(of,'state_pop'): of.state_pop() super(PatternGenerator, self).state_pop()
python
{ "resource": "" }
q56544
PatternGenerator.pil
train
def pil(self, **params_to_override): """Returns a PIL image for this pattern, overriding parameters if provided.""" from PIL.Image import fromarray nchans = self.num_channels() if nchans in [0, 1]: mode, arr = None, self(**params_to_override) arr = (255.0 / arr.m...
python
{ "resource": "" }
q56545
Composite.state_push
train
def state_push(self): """ Push the state of all generators """ super(Composite,self).state_push() for gen in self.generators: gen.state_push()
python
{ "resource": "" }
q56546
Composite.state_pop
train
def state_pop(self): """ Pop the state of all generators """ super(Composite,self).state_pop() for gen in self.generators: gen.state_pop()
python
{ "resource": "" }
q56547
Composite.function
train
def function(self,p): """Constructs combined pattern out of the individual ones.""" generators = self._advance_pattern_generators(p) assert hasattr(p.operator,'reduce'),repr(p.operator)+" does not support 'reduce'." # CEBALERT: mask gets applied by all PGs including the Composite itsel...
python
{ "resource": "" }
q56548
compile_column
train
def compile_column(name: str, data_type: str, nullable: bool) -> str: """Create column definition statement.""" null_str = 'NULL' if nullable else 'NOT NULL' return '{name} {data_type} {null},'.format(name=name, data_type=data_type, ...
python
{ "resource": "" }
q56549
MaterializedView.create
train
def create(self, no_data=False): """Declare materalized view.""" if self.query: ddl_statement = self.compile_create_as() else: ddl_statement = self.compile_create() if no_data: ddl_statement += '\nWITH NO DATA' return ddl_statement, self.que...
python
{ "resource": "" }
q56550
predicted_effects_for_variant
train
def predicted_effects_for_variant( variant, transcript_id_whitelist=None, only_coding_changes=True): """ For a given variant, return its set of predicted effects. Optionally filter to transcripts where this variant results in a non-synonymous change to the protein sequence. ...
python
{ "resource": "" }
q56551
reference_transcripts_for_variant
train
def reference_transcripts_for_variant( variant, transcript_id_whitelist=None, only_coding_changes=True): """ For a given variant, find all the transcripts which overlap the variant and for which it has a predictable effect on the amino acid sequence of the protein. """ pr...
python
{ "resource": "" }
q56552
pileup_reads_at_position
train
def pileup_reads_at_position(samfile, chromosome, base0_position): """ Returns a pileup column at the specified position. Unclear if a function like this is hiding somewhere in pysam API. """ # TODO: I want to pass truncate=True, stepper="all" # but for some reason I get this error: # ...
python
{ "resource": "" }
q56553
locus_read_generator
train
def locus_read_generator( samfile, chromosome, base1_position_before_variant, base1_position_after_variant, use_duplicate_reads=USE_DUPLICATE_READS, use_secondary_alignments=USE_SECONDARY_ALIGNMENTS, min_mapping_quality=MIN_READ_MAPPING_QUALITY): """ Gener...
python
{ "resource": "" }
q56554
locus_reads_dataframe
train
def locus_reads_dataframe(*args, **kwargs): """ Traverse a BAM file to find all the reads overlapping a specified locus. Parameters are the same as those for read_locus_generator. """ df_builder = DataFrameBuilder( LocusRead, variant_columns=False, converters={ "...
python
{ "resource": "" }
q56555
copy_from_csv_sql
train
def copy_from_csv_sql(qualified_name: str, delimiter=',', encoding='utf8', null_str='', header=True, escape_str='\\', quote_char='"', force_not_null=None, force_null=None): """Generate copy from csv statement.""" options = [] options.append("DELIMITER '%s'" % del...
python
{ "resource": "" }
q56556
sort_protein_sequences
train
def sort_protein_sequences(protein_sequences): """ Sort protein sequences in decreasing order of priority """ return list( sorted( protein_sequences, key=ProteinSequence.ascending_sort_key, reverse=True))
python
{ "resource": "" }
q56557
reads_generator_to_protein_sequences_generator
train
def reads_generator_to_protein_sequences_generator( variant_and_overlapping_reads_generator, transcript_id_whitelist=None, protein_sequence_length=PROTEIN_SEQUENCE_LENGTH, min_alt_rna_reads=MIN_ALT_RNA_READS, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE, mi...
python
{ "resource": "" }
q56558
ProteinSequence.from_translation_key
train
def from_translation_key( cls, translation_key, translations, overlapping_reads, ref_reads, alt_reads, alt_reads_supporting_protein_sequence, transcripts_overlapping_variant, transcripts_supporting_protein_sequen...
python
{ "resource": "" }
q56559
make_delete_table
train
def make_delete_table(table: Table, delete_prefix='delete_from__') -> Table: """Table referencing a delete from using primary key join.""" name = delete_prefix + table.name primary_key = table.primary_key key_names = set(primary_key.column_names) columns = [column for column in table.columns if col...
python
{ "resource": "" }
q56560
trim_variant_fields
train
def trim_variant_fields(location, ref, alt): """ Trims common prefixes from the ref and alt sequences Parameters ---------- location : int Position (starting from 1) on some chromosome ref : str Reference nucleotides alt : str Alternate (mutant) nucleotide Ret...
python
{ "resource": "" }
q56561
base0_interval_for_variant
train
def base0_interval_for_variant(variant): """ Inteval of interbase offsets of the affected reference positions for a particular variant. Parameters ---------- variant : varcode.Variant Returns triplet of (base1_location, ref, alt) """ base1_location, ref, alt = trim_variant(variant)...
python
{ "resource": "" }
q56562
interbase_range_affected_by_variant_on_transcript
train
def interbase_range_affected_by_variant_on_transcript(variant, transcript): """ Convert from a variant's position in global genomic coordinates on the forward strand to an interval of interbase offsets on a particular transcript's mRNA. Parameters ---------- variant : varcode.Variant t...
python
{ "resource": "" }
q56563
insert
train
def insert(conn, qualified_name: str, column_names, records): """Insert a collection of namedtuple records.""" query = create_insert_statement(qualified_name, column_names) with conn: with conn.cursor(cursor_factory=NamedTupleCursor) as cursor: for record in records: cu...
python
{ "resource": "" }
q56564
insert_many
train
def insert_many(conn, tablename, column_names, records, chunksize=2500): """Insert many records by chunking data into insert statements. Notes ----- records should be Iterable collection of namedtuples or tuples. """ groups = chunks(records, chunksize) column_str = ','.join(column_names) ...
python
{ "resource": "" }
q56565
upsert_records
train
def upsert_records(conn, records, upsert_statement): """Upsert records.""" with conn: with conn.cursor() as cursor: for record in records: cursor.execute(upsert_statement, record)
python
{ "resource": "" }
q56566
delete_joined_table_sql
train
def delete_joined_table_sql(qualified_name, removing_qualified_name, primary_key): """SQL statement for a joined delete from. Generate SQL statement for deleting the intersection of rows between both tables from table referenced by tablename. """ condition_template = 't.{}=d.{}' where_clause = ...
python
{ "resource": "" }
q56567
copy_from_csv
train
def copy_from_csv(conn, file, qualified_name: str, delimiter=',', encoding='utf8', null_str='', header=True, escape_str='\\', quote_char='"', force_not_null=None, force_null=None): """Copy file-like object to database table. Notes ----- Implementation defaults to pos...
python
{ "resource": "" }
q56568
get_user_tables
train
def get_user_tables(conn): """Retrieve all user tables.""" query_string = "select schemaname, relname from pg_stat_user_tables;" with conn.cursor() as cursor: cursor.execute(query_string) tables = cursor.fetchall() return tables
python
{ "resource": "" }
q56569
get_column_metadata
train
def get_column_metadata(conn, table: str, schema='public'): """Returns column data following db.Column parameter specification.""" query = """\ SELECT attname as name, format_type(atttypid, atttypmod) AS data_type, NOT attnotnull AS nullable FROM pg_catalog.pg_attribute WHERE attrelid=%s::regclass AND a...
python
{ "resource": "" }
q56570
reflect_table
train
def reflect_table(conn, table_name, schema='public'): """Reflect basic table attributes.""" column_meta = list(get_column_metadata(conn, table_name, schema=schema)) primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema)) columns = [Column(**column_data) for column_data in column_...
python
{ "resource": "" }
q56571
reset
train
def reset(db_name): """Reset database.""" conn = psycopg2.connect(database='postgres') db = Database(db_name) conn.autocommit = True with conn.cursor() as cursor: cursor.execute(db.drop_statement()) cursor.execute(db.create_statement()) conn.close()
python
{ "resource": "" }
q56572
install_extensions
train
def install_extensions(extensions, **connection_parameters): """Install Postgres extension if available. Notes ----- - superuser is generally required for installing extensions. - Currently does not support specific schema. """ from postpy.connections import connect conn = connect(**c...
python
{ "resource": "" }
q56573
ExecutorDriverProxy.update
train
def update(self, status): """Sends a status update to the framework scheduler. Retrying as necessary until an acknowledgement has been received or the executor is terminated (in which case, a TASK_LOST status update will be sent). See Scheduler.statusUpdate for more information ...
python
{ "resource": "" }
q56574
ExecutorDriverProxy.message
train
def message(self, data): """Sends a message to the framework scheduler. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion. """ logging.info('Driver sends framework message {}'.format(data)) return self.driver.se...
python
{ "resource": "" }
q56575
RailDriver.get_current_time
train
def get_current_time(self): """ Get current time :return: datetime.time """ hms = [int(self.get_current_controller_value(i)) for i in range(406, 409)] return datetime.time(*hms)
python
{ "resource": "" }
q56576
RailDriver.get_loco_name
train
def get_loco_name(self): """ Returns the Provider, Product and Engine name. :return list """ ret_str = self.dll.GetLocoName().decode() if not ret_str: return return ret_str.split('.:.')
python
{ "resource": "" }
q56577
RailDriver.set_controller_value
train
def set_controller_value(self, index_or_name, value): """ Sets controller value :param index_or_name integer index or string name :param value float """ if not isinstance(index_or_name, int): index = self.get_controller_index(index_or_name) else: ...
python
{ "resource": "" }
q56578
SchedulerDriverProxy.stop
train
def stop(self, failover=False): """Stops the scheduler driver. If the 'failover' flag is set to False then it is expected that this framework will never reconnect to Mesos and all of its executors and tasks can be terminated. Otherwise, all executors and tasks will remain runni...
python
{ "resource": "" }
q56579
SchedulerDriverProxy.request
train
def request(self, requests): """Requests resources from Mesos. (see mesos.proto for a description of Request and how, for example, to request resources from specific slaves.) Any resources available are offered to the framework via Scheduler.resourceOffers callback, asynchronou...
python
{ "resource": "" }
q56580
SchedulerDriverProxy.launch
train
def launch(self, offer_id, tasks, filters=Filters()): """Launches the given set of tasks. Any resources remaining (i.e., not used by the tasks or their executors) will be considered declined. The specified filters are applied on all unused resources (see mesos.proto for a descri...
python
{ "resource": "" }
q56581
SchedulerDriverProxy.kill
train
def kill(self, task_id): """Kills the specified task. Note that attempting to kill a task is currently not reliable. If, for example, a scheduler fails over while it was attempting to kill a task it will need to retry in the future. Likewise, if unregistered / disconnected, the ...
python
{ "resource": "" }
q56582
SchedulerDriverProxy.reconcile
train
def reconcile(self, statuses): """Allows the framework to query the status for non-terminal tasks. This causes the master to send back the latest task status for each task in 'statuses', if possible. Tasks that are no longer known will result in a TASK_LOST update. If statuses is empty,...
python
{ "resource": "" }
q56583
SchedulerDriverProxy.accept
train
def accept(self, offer_ids, operations, filters=Filters()): """Accepts the given offers and performs a sequence of operations on those accepted offers. See Offer.Operation in mesos.proto for the set of available operations. Available resources are aggregated when multiple offers are ...
python
{ "resource": "" }
q56584
SchedulerDriverProxy.acknowledge
train
def acknowledge(self, status): """Acknowledges the status update. This should only be called once the status update is processed durably by the scheduler. Not that explicit acknowledgements must be requested via the constructor argument, otherwise a call to this method will cau...
python
{ "resource": "" }
q56585
SchedulerDriverProxy.message
train
def message(self, executor_id, slave_id, message): """Sends a message from the framework to one of its executors. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion. """ logging.info('Sends message `{}` to executor `{}` ...
python
{ "resource": "" }
q56586
_connect_func
train
def _connect_func(builder, obj, signal_name, handler_name, connect_object, flags, cls): '''Handles GtkBuilder signal connect events''' if connect_object is None: extra = () else: extra = (connect_object,) # The handler name refers to an attribute on the template insta...
python
{ "resource": "" }
q56587
_register_template
train
def _register_template(cls, template_bytes): '''Registers the template for the widget and hooks init_template''' # This implementation won't work if there are nested templates, but # we can't do that anyways due to PyGObject limitations so it's ok if not hasattr(cls, 'set_template'): raise Typ...
python
{ "resource": "" }
q56588
_init_template
train
def _init_template(self, cls, base_init_template): '''This would be better as an override for Gtk.Widget''' # TODO: could disallow using a metaclass.. but this is good enough # .. if you disagree, feel free to fix it and issue a PR :) if self.__class__ is not cls: raise TypeError("Inheritance f...
python
{ "resource": "" }
q56589
extract_haml
train
def extract_haml(fileobj, keywords, comment_tags, options): """ babel translation token extract function for haml files """ import haml from mako import lexer, parsetree from mako.ext.babelplugin import extract_nodes encoding = options.get('input_encoding', options.get('encoding', None)) temp...
python
{ "resource": "" }
q56590
get_single_allele_from_reads
train
def get_single_allele_from_reads(allele_reads): """ Given a sequence of AlleleRead objects, which are expected to all have the same allele, return that allele. """ allele_reads = list(allele_reads) if len(allele_reads) == 0: raise ValueError("Expected non-empty list of AlleleRead object...
python
{ "resource": "" }
q56591
Base.iter_all_children
train
def iter_all_children(self): '''Return an iterator that yields every node which is a child of this one. This includes inline children, and control structure `else` clauses. ''' if self.inline_child: yield self.inline_child for x in self.children: ...
python
{ "resource": "" }
q56592
TransferFn.initialize
train
def initialize(self, **kwargs): """ Transfer functions may need additional information before the supplied numpy array can be modified in place. For instance, transfer functions may have state which needs to be allocated in memory with a certain size. In other cases, the transfe...
python
{ "resource": "" }
q56593
TransferFnWithState.override_plasticity_state
train
def override_plasticity_state(self, new_plasticity_state): """ Temporarily disable plasticity of internal state. This function should be implemented by all subclasses so that after a call, the output should always be the same for any given input pattern, and no call should have ...
python
{ "resource": "" }
q56594
register_host
train
def register_host(): """Register supported hosts""" pyblish.api.register_host("hython") pyblish.api.register_host("hpython") pyblish.api.register_host("houdini")
python
{ "resource": "" }
q56595
maintained_selection
train
def maintained_selection(): """Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored """ previous_selection = hou.selectedNodes() t...
python
{ "resource": "" }
q56596
execute_transaction
train
def execute_transaction(conn, statements: Iterable): """Execute several statements in single DB transaction.""" with conn: with conn.cursor() as cursor: for statement in statements: cursor.execute(statement) conn.commit()
python
{ "resource": "" }
q56597
execute_transactions
train
def execute_transactions(conn, statements: Iterable): """Execute several statements each as a single DB transaction.""" with conn.cursor() as cursor: for statement in statements: try: cursor.execute(statement) conn.commit() except psycopg2.Program...
python
{ "resource": "" }
q56598
execute_closing_transaction
train
def execute_closing_transaction(statements: Iterable): """Open a connection, commit a transaction, and close it.""" with closing(connect()) as conn: with conn.cursor() as cursor: for statement in statements: cursor.execute(statement)
python
{ "resource": "" }
q56599
select
train
def select(conn, query: str, params=None, name=None, itersize=5000): """Return a select statement's results as a namedtuple. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. i...
python
{ "resource": "" }