_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q51200
VarianceDecomposition.getLaplaceCovar
train
def getLaplaceCovar(self): """ USES LAPLACE APPROXIMATION TO CALCULATE THE COVARIANCE MATRIX OF THE OPTIMIZED PARAMETERS """ assert self.init, 'GP not initialised' assert self.fast==False, 'Not supported for fast implementation' if self.cache['Sigma']==Non...
python
{ "resource": "" }
q51201
VarianceDecomposition.getEmpTraitCovar
train
def getEmpTraitCovar(self): """ Returns the empirical trait covariance matrix """ if self.P==1: out=self.Y[self.Iok].var() else: out=SP.cov(self.Y[self.Iok].T) return out
python
{ "resource": "" }
q51202
VarianceDecomposition.getEmpTraitCorrCoef
train
def getEmpTraitCorrCoef(self): """ Returns the empirical trait correlation matrix """ cov = self.getEmpTraitCovar() stds=SP.sqrt(cov.diagonal())[:,SP.newaxis] RV = cov/stds/stds.T return RV
python
{ "resource": "" }
q51203
VarianceDecomposition.estimateHeritabilities
train
def estimateHeritabilities(self, K, verbose=False): """ estimate variance components and fixed effects from a single trait model having only two terms """ # Fit single trait model varg = SP.zeros(self.P) varn = SP.zeros(self.P) fixed = SP.zeros(...
python
{ "resource": "" }
q51204
VarianceDecomposition.setKstar
train
def setKstar(self,term_i,Ks): """ Set the kernel for predictions Args: term_i: index of the term we are interested in Ks: (TODO: is this the covariance between train and test or the covariance between test points?) """ assert Ks.shape[0]==self...
python
{ "resource": "" }
q51205
callback
train
def callback(newstate): """Callback from modem, process based on new state""" print('callback: ', newstate) if newstate == modem.STATE_RING: if state == modem.STATE_IDLE: att = {"cid_time": modem.get_cidtime, "cid_number": modem.get_cidnumber, "cid_n...
python
{ "resource": "" }
q51206
main
train
def main(): global modem modem = bm(port='/dev/ttyACM0', incomingcallback=callback) if modem.state == modem.STATE_FAILED: print('Unable to initialize modem, exiting.') return """Print modem information.""" resp = modem.sendcmd('ATI3') for line in resp: if line: ...
python
{ "resource": "" }
q51207
safe_cd
train
def safe_cd(path): """ Changes to a directory, yields, and changes back. Additionally any error will also change the directory back. Usage: >>> with safe_cd('some/repo'): ... call('git status') """ starting_directory = os.getcwd() try: os.chdir(path) yield fi...
python
{ "resource": "" }
q51208
Command.parse_host_args
train
def parse_host_args(self, *args): """ Splits out the patch subcommand and returns a comma separated list of host_strings """ self.subcommand = None new_args = args try: sub = args[0] if sub in ['project','templates','static','media','wsgi','webconf...
python
{ "resource": "" }
q51209
url_for_s3
train
def url_for_s3(endpoint, bucket_name, bucket_domain=None, scheme='', url_style='host', cdn_domain=None, filename=None): """ Generates an S3 URL to the given endpoint, using the given bucket config. Example: url_for_s3('static', bucket_name='my-cool-foobar-bucket', sche...
python
{ "resource": "" }
q51210
_put_text
train
def _put_text(irods_path, text): """Put raw text into iRODS.""" with tempfile.NamedTemporaryFile() as fh: fpath = fh.name try: # Make Python2 compatible. text = unicode(text, "utf-8") except (NameError, TypeError): # NameError: We are running Python3 ...
python
{ "resource": "" }
q51211
_put_obj
train
def _put_obj(irods_path, obj): """Put python object into iRODS as JSON text.""" text = json.dumps(obj, indent=2) _put_text(irods_path, text)
python
{ "resource": "" }
q51212
IrodsStorageBroker.list_dataset_uris
train
def list_dataset_uris(cls, base_uri, config_path): """Return list containing URIs in base_uri.""" parsed_uri = generous_parse_uri(base_uri) irods_path = parsed_uri.path uri_list = [] logger.info("irods_path: '{}'".format(irods_path)) for dir_path in _ls_abspaths(irods_...
python
{ "resource": "" }
q51213
PonyWhoosh.create_index
train
def create_index(self, index): """Creates and opens index folder for given index. If the index already exists, it just opens it, otherwise it creates it first. """ index._path = os.path.join(self.indexes_path, index._name) if whoosh.index.exists_in(index._path): _whoosh = whoosh.index.open_d...
python
{ "resource": "" }
q51214
PonyWhoosh.search
train
def search(self, *arg, **kw): """A full search function. This allows you to search expression using the following arguments. Arg: query (str): The search string expression. Optional Args: - include_entity (bool): include in each result the entity values associated of the fields stored....
python
{ "resource": "" }
q51215
_sounds_re
train
def _sounds_re(include_erhua=False): """Sounds are syllables + tones""" tone = '[1-5]' optional_final_erhua = '|r\\b' if include_erhua else '' pattern = '({}{}{})'.format(_joined_syllables_re(), tone, optional_final_erhua) return re.compile(pattern, re.IGNORECASE)
python
{ "resource": "" }
q51216
bleach
train
def bleach(file): """ Sanitizes given python module. :param file: Python module file. :type file: unicode :return: Definition success. :rtype: bool """ LOGGER.info("{0} | Sanitizing '{1}' python module!".format(__name__, file)) source_file = File(file) content = source_file.re...
python
{ "resource": "" }
q51217
prep_message
train
def prep_message(msg): """ Add the size header """ if six.PY3: msg_out = msg.as_string().encode("utf-8") else: msg_out = msg.as_string() our_len = len(msg_out) + 4 size = struct.pack('>L', our_len) # why the hell is this "bytes" on python3? return size + msg_out
python
{ "resource": "" }
q51218
get_single_keywords
train
def get_single_keywords(skw_db, fulltext): """Find single keywords in the fulltext. :param skw_db: list of KeywordToken objects :param fulltext: string, which will be searched :return : dictionary of matches in a format { <keyword object>, [[position, position...], ], .. } """ ...
python
{ "resource": "" }
q51219
_get_ckw_span
train
def _get_ckw_span(fulltext, spans): """Return the span of the composite keyword if it is valid.""" _MAXIMUM_SEPARATOR_LENGTH = max( [len(_separator) for _separator in current_app.config["CLASSIFIER_VALID_SEPARATORS"]] ) if spans[0] < spans[1]: words = (spans[0], spans[1...
python
{ "resource": "" }
q51220
_contains_span
train
def _contains_span(span0, span1): """Return true if span0 contains span1, False otherwise.""" if (span0 == span1 or span0[0] > span1[0] or span0[1] < span1[1]): return False return True
python
{ "resource": "" }
q51221
Channel.has_privs
train
def has_privs(self, user, lowest_mode='o'): """Return True if user has the given mode or higher.""" if isinstance(user, User): user = user.nick user_prefixes = self.prefixes.get(user, None) if not user_prefixes: return False mode_dict = self.s.features....
python
{ "resource": "" }
q51222
Channel.add_user
train
def add_user(self, nick, prefixes=None): """Add a user to our internal list of nicks.""" if nick not in self._user_nicks: self._user_nicks.append(nick) self.prefixes[nick] = prefixes
python
{ "resource": "" }
q51223
is_packet_trace
train
def is_packet_trace(path): """Determine if a file is a packet trace that is supported by this module. Args: path (str): path to the trace file. Returns: bool: True if the file is a valid packet trace. """ path = os.path.abspath(path) if not os.path.isfile(path): return ...
python
{ "resource": "" }
q51224
chains
train
def chains(xs, labels=None, truths=None, truth_color=u"#4682b4", burn=None, alpha=0.5, fig=None): """ Create a plot showing the walker values for each parameter at every step. :param xs: The samples. This should be a 3D :class:`numpy.ndarray` of size (``n_walkers``, ``n_steps``, ``n_pa...
python
{ "resource": "" }
q51225
acceptance_fractions
train
def acceptance_fractions(mean_acceptance_fractions, burn=None, ax=None): """ Plot the meana cceptance fractions for each MCMC step. :param mean_acceptance_fractions: The acceptance fractions at each MCMC step. :type mean_acceptance_fractions: :class:`numpy.array` :param burn: [opt...
python
{ "resource": "" }
q51226
normalised_autocorrelation_function
train
def normalised_autocorrelation_function(chain, index=0, burn=None, limit=None, fig=None, figsize=None): """ Plot the autocorrelation function for each parameter of a sampler chain. :param chain: The sampled parameter values. :type chain: :class:`numpy.ndarray` :param index: [...
python
{ "resource": "" }
q51227
get_a
train
def get_a(html, find=''): """Finds all the 'a' tags with find in their href""" links = [] for a in html.find_all('a'): if a.get('href').find(find) != -1: links.append(a) return links
python
{ "resource": "" }
q51228
episode_list
train
def episode_list(a): """List of all episodes of a season""" html = get_html(ROOT + a.get('href')) div = html.find('div', {'class': "list detail eplist"}) links = [] for tag in div.find_all('a', {'itemprop': "name"}): links.append(tag) return links
python
{ "resource": "" }
q51229
parse_episode
train
def parse_episode(a): """Collects data related to an episode""" d = {} html = get_html(ROOT + a.get('href')) d['rating'] = get_rating(html) d['episode-name'], d['date'] = get_name_date(html) season, d['episode-num'] = get_season_epi_num(html) return season, d
python
{ "resource": "" }
q51230
parse
train
def parse(link): """Parses a Tv Series returns the dataset as a dictionary """ html = get_html(link) data = {'rating': get_rating(html), 'name': get_name_date(html)[0]} div = html.find(id="title-episode-widget") season_tags = get_a(div, find="season=") episodes = {} for...
python
{ "resource": "" }
q51231
classification
train
def classification(request): """ Adds classification context to views. """ ctx = { 'classification_text': getattr(settings, 'CLASSIFICATION_TEXT', 'UNCLASSIFIED'), 'classification_text_color': getattr(settings, 'CLASSIFICATION_TEXT_COLOR', 'white'), 'classification_background_co...
python
{ "resource": "" }
q51232
Zones.import_locations
train
def import_locations(self, zone_file): """Parse zoneinfo zone description data files. ``import_locations()`` returns a list of :class:`Zone` objects. It expects data files in one of the following formats:: AN +1211-06900 America/Curacao AO -0848+01314 Africa/Luanda ...
python
{ "resource": "" }
q51233
Zones.dump_zone_file
train
def dump_zone_file(self): """Generate a zoneinfo compatible zone description table. Returns: list: zoneinfo descriptions """ data = [] for zone in sorted(self, key=attrgetter('country')): text = ['%s %s %s' % (zone.country, ...
python
{ "resource": "" }
q51234
Stations.import_locations
train
def import_locations(self, data, index='WMO'): """Parse NOAA weather station data files. ``import_locations()`` returns a dictionary with keys containing either the WMO or ICAO identifier, and values that are ``Station`` objects that describes the large variety of data exported by NOAA_...
python
{ "resource": "" }
q51235
Bbox.reboot
train
def reboot(self): """ Reboot the device Useful when trying to get xDSL sync """ token = self.get_token() self.bbox_auth.set_access(BboxConstant.AUTHENTICATION_LEVEL_PRIVATE, BboxConstant.AUTHENTICATION_LEVEL_PRIVATE) url_suffix = "reboot?btoken={}".format(token) ...
python
{ "resource": "" }
q51236
ErrorResponse.from_binary_string
train
def from_binary_string(self, stream): """Unpack the error response from a stream.""" command, code, identifier = struct.unpack(self.FORMAT, stream) if command != self.COMMAND: raise ErrorResponseInvalidCommandError() if code not in self.CODES: raise ErrorRespons...
python
{ "resource": "" }
q51237
ErrorResponse.to_binary_string
train
def to_binary_string(self, code, identifier): """Pack the error response to binary string and return it.""" return struct.pack(self.FORMAT, self.COMMAND, code, identifier)
python
{ "resource": "" }
q51238
hash
train
def hash(hash_type, input_text): '''Hash input_text with the algorithm choice''' hash_funcs = {'MD5' : hashlib.md5, 'SHA1' : hashlib.sha1, 'SHA224' : hashlib.sha224, 'SHA256' : hashlib.sha256, 'SHA384' : hashlib.sha384, 'S...
python
{ "resource": "" }
q51239
dedupe_list_of_dicts
train
def dedupe_list_of_dicts(ld): """Remove duplicates from a list of dictionaries preserving the order. We can't use the generic list helper because a dictionary isn't hashable. Adapted from http://stackoverflow.com/a/9427216/374865. """ def _freeze(o): """Recursively freezes a dict into an ha...
python
{ "resource": "" }
q51240
destination
train
def destination(globs, locator, distance, bearing): """Calculate destination from locations.""" globs.locations.destination(distance, bearing, locator)
python
{ "resource": "" }
q51241
read_locations
train
def read_locations(filename): """Pull locations from a user's config file. Args: filename (str): Config file to parse Returns: dict: List of locations from config file """ data = ConfigParser() if filename == '-': data.read_file(sys.stdin) else: data.read(fi...
python
{ "resource": "" }
q51242
read_csv
train
def read_csv(filename): """Pull locations from a user's CSV file. Read gpsbabel_'s CSV output format .. _gpsbabel: http://www.gpsbabel.org/ Args: filename (str): CSV file to parse Returns: tuple of dict and list: List of locations as ``str`` objects """ field_names = ('la...
python
{ "resource": "" }
q51243
main
train
def main(): """Main script handler. Returns: int: 0 for success, >1 error code """ logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s') try: cli() return 0 except LocationsError as error: print(error) return 2 except RuntimeError as er...
python
{ "resource": "" }
q51244
make_urldispatch_application
train
def make_urldispatch_application(_, **settings): """ paste.app_factory interface for URLDispatcher""" patterns = [p.split("=", 1) for p in settings['patterns'].split('\n') if p] application = URLDispatcher() for pattern, app in patterns: pattern = pattern.strip()...
python
{ "resource": "" }
q51245
union
train
def union(dict1, dict2): """ Deep merge of dict2 into dict1. May be dictionaries or dictobj's. Values in dict2 will replace values in dict1 where they vary but have the same key. When lists are encountered, the dict2 list will replace the dict1 list. This will alter the first dictionary. The...
python
{ "resource": "" }
q51246
_union_copy
train
def _union_copy(dict1, dict2): """ Internal wrapper to keep one level of copying out of play, for efficiency. Only copies data on dict2, but will alter dict1. """ for key, value in dict2.items(): if key in dict1 and isinstance(value, dict): dict1[key] = _union_copy(dict1[key], ...
python
{ "resource": "" }
q51247
get_attribute_references
train
def get_attribute_references(instring): """ Return a list of attribute references in the condition expression. attribute_reference ::= relation_name "." attribute_name | attribute_name :param instring: a condition expression. :return: a list of attribute references. """ parsed = ConditionG...
python
{ "resource": "" }
q51248
main
train
def main(): '''Main entry point for the bioinfo CLI.''' args = docopt(__doc__, version=__version__) if 'bam_coverage' in args: bam_coverage(args['<reference>'], args['<alignments>'], int(args['<minmatch>']), min_mapq=int(args['--mapq'])...
python
{ "resource": "" }
q51249
MiuraJenkinsJob.upsert
train
def upsert(self): """ create or update the jenkins job """ if not self.jenkins_host.has_job(self.name): LOGGER.info("creating {0}...".format(self.name)) self.jenkins_host.create_job(self.name, self.config_xml) else: jenkins_job = self.jenkins_host[self.name] ...
python
{ "resource": "" }
q51250
MiuraJenkinsJob.delete
train
def delete(self): """ delete the jenkins job, if it exists """ if self.jenkins_host.has_job(self.name): LOGGER.info("deleting {0}...".format(self.name)) self.jenkins_host.delete_job(self.name)
python
{ "resource": "" }
q51251
MiuraJenkinsJob.dry_run
train
def dry_run(self): """ print information about the jenkins job """ LOGGER.info("Job Info: {name} -> {host}".format( name=self.name, host=self.jenkins_host.baseurl ))
python
{ "resource": "" }
q51252
ElementTreeFactory._find
train
def _find(self, root, tagname, id=None): """Returns the first element with the specified tagname and id""" if id is None: result = root.find('.//%s' % tagname) if result is None: raise LookupError('Cannot find any %s elements' % tagname) else: ...
python
{ "resource": "" }
q51253
responds
train
def responds(status=status.HTTP_200_OK, meaning='Undocumented status code', schema=None, schema_name=None, **kwargs): """Documents the status code per handled case. Additional parameters may make it into the OpenAPI documentation per view. Examples of tho...
python
{ "resource": "" }
q51254
text_input
train
def text_input(*args, **kwargs): ''' Get multi-line text input as a strong from a textarea form element. ''' text_input = wtforms.TextAreaField(*args, **kwargs) text_input.input_type = 'text' return text_input
python
{ "resource": "" }
q51255
list_input
train
def list_input(*args, **kwargs): ''' Get a list parsed from newline-delimited entries from a textarea ''' list_input = wtforms.TextAreaField(*args, **kwargs) list_input.input_type = 'list' return list_input
python
{ "resource": "" }
q51256
line_input
train
def line_input(*args, **kwargs): ''' Get a single line of input as a string from a textfield ''' line_input = wtforms.TextField(*args, **kwargs) line_input.input_type = 'line' return line_input
python
{ "resource": "" }
q51257
submit_button
train
def submit_button(*args, **kwargs): ''' Create a submit button ''' submit_button = wtforms.SubmitField(*args, **kwargs) submit_button.input_type = 'submit_button' return submit_button
python
{ "resource": "" }
q51258
StreamRequestMixin.proxy_protocol
train
def proxy_protocol(self, error='raise', default=None, limit=None, authenticate=False): """ Parses, and optionally authenticates, proxy protocol information from request. Note that ``self.request`` is wrapped by ``SocketBuffer``. :param error: How read (``exc.ReadError``) and...
python
{ "resource": "" }
q51259
Model.create_table
train
def create_table(cls, read_throughput=5, write_throughput=5): """Create the table as the schema definition.""" table_name = cls.get_table_name() raw_throughput = { 'ReadCapacityUnits': read_throughput, 'WriteCapacityUnits': write_throughput } table_schem...
python
{ "resource": "" }
q51260
Model.get_item
train
def get_item(cls, hash_key, range_key=None): """ Get item from the table.""" key = cls._encode_key(hash_key, range_key) raw_data = cls._get_connection().get_item(cls.get_table_name(), key) if 'Item' not in raw_data: raise ItemNotFoundException return cls.from_raw_data...
python
{ "resource": "" }
q51261
Model.update_item
train
def update_item(cls, hash_key, range_key=None, attributes_to_set=None, attributes_to_add=None): """Update item attributes. Currently SET and ADD actions are supported.""" primary_key = cls._encode_key(hash_key, range_key) value_names = {} encoded_values = {} dynamizer = Dynamize...
python
{ "resource": "" }
q51262
Model.query
train
def query(cls, index_name=None, filter_builder=None, scan_index_forward=None, limit=None, **key_conditions): """High level query API. :param key_filter: key conditions of the query. :type key_filter: :class:`collections.Mapping` :param filter_builder: filter expression bui...
python
{ "resource": "" }
q51263
Model.scan
train
def scan(cls, filter_builder=None, **scan_filter): """High level scan API. :param filter_builder: filter expression builder. :type filter_builder: :class:`~bynamodb.filterexps.Operator` """ scan_kwargs = {'scan_filter': build_condition(scan_filter)} if filter_builder: ...
python
{ "resource": "" }
q51264
Model.from_raw_data
train
def from_raw_data(cls, item_raw): """Translate the raw item data from the DynamoDBConnection to the item object. """ deserialized = {} for name, value in item_raw.items(): attr = getattr(cls, name, None) if attr is None: continue ...
python
{ "resource": "" }
q51265
new_regid_custom_field
train
def new_regid_custom_field(uwregid): """ Return a BridgeCustomField object for REGID to be used in a POST, PATCH request """ return BridgeCustomField( field_id=get_regid_field_id(), name=BridgeCustomField.REGID_NAME, value=uwregid )
python
{ "resource": "" }
q51266
Spectrum1D.copy
train
def copy(self): """ Creates a copy of the object """ variance = self.variance.copy() if self.variance is not None else None headers = self.headers.copy() if self.headers is not None else None return self.__class__(self.disp.copy(), self.flux.copy(), variance=variance, headers...
python
{ "resource": "" }
q51267
Spectrum1D.cross_correlate
train
def cross_correlate(self, templates, **kwargs): """ Cross correlate the spectrum against a set of templates. """ # templates can be: # - a single Spectrum1D object # - (template_dispersion, template_fluxes) # templates can be a single spectrum or a tuple of (dis...
python
{ "resource": "" }
q51268
StreamEditor.process_column
train
def process_column(self, idx, value): "Process a single column." if value is not None: value = str(value).decode(self.encoding) return value
python
{ "resource": "" }
q51269
StreamEditor.process_line
train
def process_line(self, line): "Process a single complete line." cleaned = [] columns = line.split(self.indel) # Populate indices if not defined if not self.indices: self.indices = range(len(columns)) for i in self.indices: # Support turning an in c...
python
{ "resource": "" }
q51270
StreamEditor.read
train
def read(self, size=-1): "Reads up to size bytes, but always completes the last line." buf = self.fin.read(size) if not buf: return '' lines = buf.splitlines() # Read the rest of the last line if necessary if not buf.endswith('\n'): last = lines.po...
python
{ "resource": "" }
q51271
StreamEditor.readline
train
def readline(self, size=-1): "The size is ignored since a complete line must be read." line = self.fin.readline() if not line: return '' return self.process_line(line.rstrip('\n'))
python
{ "resource": "" }
q51272
VCFStreamEditor.process_line
train
def process_line(self, record): "Process a single record. This assumes only a single sample output." cleaned = [] for key in self.vcf_fields: out = self.process_column(key, getattr(record, key)) if isinstance(out, (list, tuple)): cleaned.extend(out) ...
python
{ "resource": "" }
q51273
VCFStreamEditor.read
train
def read(self, size=-1): """Read `size` bytes from the reader relative to the parsed output. This is generally acceptable in practice since VCF lines are condensed, but if the output line <<< record, this means the actual memory used will be much greater than `size`. """ ...
python
{ "resource": "" }
q51274
lexically_parse_tweet
train
def lexically_parse_tweet(tweet, phrase_tree): """ Returns list of LexicalTokens found in tweet. The list contains all the words in original tweet, but are optimally grouped up to form largest matching n-grams from lexicon. If no match is found, token is added as singleton. @param tweet Tweet ...
python
{ "resource": "" }
q51275
Schema.to_dict
train
def to_dict(self): """Return the schema as a dict ready to be serialized. """ schema = super(Schema, self).to_dict() schema['$schema'] = "http://json-schema.org/draft-04/schema#" if self._id: schema['id'] = self._id if self._desc: schema['descript...
python
{ "resource": "" }
q51276
Schema.define
train
def define(self, id, schema): """Add a schema to the list of definition :param id: id of the schema. :param schema: the schema as a dict or a :class:schemabuilder.primitives.Generic :return: reference to schema. :rtype: :class:`schemabuilder.schema.Ref` ...
python
{ "resource": "" }
q51277
Ref.validate
train
def validate(self, data): """Validate the data against the schema. """ validator = self._schema.validator(self._id) validator.validate(data)
python
{ "resource": "" }
q51278
MerRunner.meraculous_runner
train
def meraculous_runner(self): """ Check to make sure that the allAssembliesDir has been created, if not, make it. This will only execute for the first time an assembly has been run in this directory. Run the directory from allAssembliesDir. The self.callString instance at...
python
{ "resource": "" }
q51279
ThrottleMixin.throttle_check
train
def throttle_check(self): """ Check for throttling. """ throttle = self._meta.throttle() wait = throttle.should_be_throttled(self) if wait: raise HttpError( "Throttled, wait {0} seconds.".format(wait), status=status.HTTP_503_SERVICE_UNAVAILABLE...
python
{ "resource": "" }
q51280
load_variants
train
def load_variants(manifest_path, database, **kwargs): "Variant loading requires only a VCF file and will never load a duplicate." manifest = ManifestReader(manifest_path) vcf_info = manifest.section('vcf') # No data regarding VCF if 'file' not in vcf_info: return cursor = connections[...
python
{ "resource": "" }
q51281
LoadCommand.drop_table
train
def drop_table(self, cursor, target, options): "Drops the target table." sql = 'DROP TABLE IF EXISTS {0}' cursor.execute(sql.format(self.qualified_names[target]))
python
{ "resource": "" }
q51282
LoadCommand.create_table
train
def create_table(self, cursor, target, options): "Creates the target table." cursor.execute( self.create_sql[target].format(self.qualified_names[target]))
python
{ "resource": "" }
q51283
LoadCommand.load_files
train
def load_files(self, cursor, target, files, options): "Loads multiple files into the target table." for fname in files: self.load_file(cursor, target, fname, options)
python
{ "resource": "" }
q51284
LoadCommand.load_file
train
def load_file(self, cursor, target, fname, options): "Parses and loads a single file into the target table." with open(fname) as fin: log.debug("opening {0} in {1} load_file".format(fname, __name__)) encoding = options.get('encoding', 'utf-8') if target in self.proces...
python
{ "resource": "" }
q51285
Cells.import_locations
train
def import_locations(self, cells_file): """Parse OpenCellID.org data files. ``import_locations()`` returns a dictionary with keys containing the OpenCellID.org_ database identifier, and values consisting of a ``Cell`` objects. It expects cell files in the following format:: ...
python
{ "resource": "" }
q51286
op_symbol
train
def op_symbol(op_node): """Get the GLSL symbol for a Python operator.""" ops = { # TODO(nicholasbishop): other unary ops ast.UAdd: '+', ast.USub: '-', # TODO(nicholasbishop): FloorDiv, Pow, LShift, RShift, # BitOr, BitXor, BitAnd ast.Add: '+', ast.Sub: '-...
python
{ "resource": "" }
q51287
py_to_glsl
train
def py_to_glsl(root): """Translate Python AST into GLSL code. root: an ast.FunctionDef object Return a list of strings, where each string is a line of GLSL code. """ atg = AstToGlsl() code = atg.visit(root) return code.lines
python
{ "resource": "" }
q51288
filedet
train
def filedet(name, fobj=None, suffix=None): """ Detect file type by filename. :param name: file name :param fobj: file object :param suffix: file suffix like ``py``, ``.py`` :return: file type full name, such as ``python``, ``bash`` """ name = name or (fobj and fobj.name) or suffix s...
python
{ "resource": "" }
q51289
unique_preserved_list
train
def unique_preserved_list(original_list): """ Return the unique items of a list in their original order. :param original_list: A list of items that may have duplicate entries. :type original_list: list :returns: A list with unique entries with the original order preserved....
python
{ "resource": "" }
q51290
human_readable_digit
train
def human_readable_digit(number): """ Return a digit in a human-readable string form. :param number: The obfuscated number. :type number: float :returns: A more human-readable version of the input number. :rtype: str """ if 0 >= number: return...
python
{ "resource": "" }
q51291
estimate_tau_exp
train
def estimate_tau_exp(chains, **kwargs): """ Estimate the exponential auto-correlation time for all parameters in a chain. """ # Calculate the normalised autocorrelation function in each parameter. rho = np.nan * np.ones(chains.shape[1:]) for i in range(chains.shape[2]): try: ...
python
{ "resource": "" }
q51292
estimate_tau_int
train
def estimate_tau_int(chains, **kwargs): """ Estimate the integrated auto-correlation time for all parameters in a chain. """ return autocorr.integrated_time(np.mean(chains, axis=0), **kwargs)
python
{ "resource": "" }
q51293
Component.asignTopUnit
train
def asignTopUnit(self, top, topName): """ Set hwt unit as template for component """ self._top = top self.name = topName pack = self._packager self.model.addDefaultViews(topName, pack.iterParams(top)) for intf in pack.iterInterfaces(self._top): ...
python
{ "resource": "" }
q51294
DictDoc.setdefault
train
def setdefault(self, name, value): ''' if the ``name`` is set, return its value. Otherwse set ``name`` to ``value`` and return ``value``''' if name in self: return self[name] self[name] = value return self[name]
python
{ "resource": "" }
q51295
Index.unique
train
def unique(self, drop_dups=False): ''' Make this index unique, optionally dropping duplicate entries. :param drop_dups: Drop duplicate objects while creating the unique \ index? Default to ``False`` ''' self.__unique = True if drop_dups and pymongo.version_t...
python
{ "resource": "" }
q51296
Index.ensure
train
def ensure(self, collection): ''' Call the pymongo method ``ensure_index`` on the passed collection. :param collection: the ``pymongo`` collection to ensure this index \ is on ''' components = [] for c in self.components: if isinstance(c[0], F...
python
{ "resource": "" }
q51297
EncryptedProxyField._bypass_non_decrypted_field_exception
train
def _bypass_non_decrypted_field_exception(self): """Bypass exception if some field was not decrypted.""" if getattr(settings, 'PGPFIELDS_BYPASS_NON_DECRYPTED_FIELD_EXCEPTION', False): return True if getattr(settings, 'PGPFIELDS_BYPASS_FIELD_EXCEPTION_IN_MIGRATIONS', False): ...
python
{ "resource": "" }
q51298
CrawlerJob.create
train
def create(cls, job_id, spider, workflow, results=None, logs=None, status=JobStatus.PENDING): """Create a new entry for a scheduled crawler job.""" obj = cls( job_id=job_id, spider=spider, workflow=workflow, results=results, logs...
python
{ "resource": "" }
q51299
CrawlerJob.get_by_job
train
def get_by_job(cls, job_id): """Get a row by Job UUID.""" try: return cls.query.filter_by( job_id=job_id ).one() except NoResultFound: raise CrawlerJobNotExistError(job_id)
python
{ "resource": "" }