_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q49100
OsidForm._is_valid_duration
train
def _is_valid_duration(self, inpt, metadata): """Checks if input is a valid Duration""" # NEED TO ADD CHECKS FOR OTHER METADATA, LIKE MINIMUM, MAXIMUM, ETC. from dlkit.abstract_osid.calendaring.primitives import Duration as abc_duration if isinstance(inpt, abc_duration): retu...
python
{ "resource": "" }
q49101
OsidForm.set_locale
train
def set_locale(self, language_type, script_type): """Specifies a language and script type for ``DisplayText`` fields in this form. Setting a locale to something other than the default locale may affect the ``Metadata`` in this form. If multiple locales are available for managing transl...
python
{ "resource": "" }
q49102
OsidExtensibleForm._get_record
train
def _get_record(self, record_type): """This overrides _get_record in osid.Extensible. Perhaps we should leverage it somehow? """ if (not self.has_record_type(record_type) and record_type.get_identifier() not in self._record_type_data_sets): raise errors.Unsu...
python
{ "resource": "" }
q49103
OsidExtensibleForm._init_record
train
def _init_record(self, record_type_idstr): """Override this from osid.Extensible because Forms use a different attribute in record_type_data.""" record_type_data = self._record_type_data_sets[Id(record_type_idstr).get_identifier()] module = importlib.import_module(record_type_data['modul...
python
{ "resource": "" }
q49104
OsidContainableForm.set_sequestered
train
def set_sequestered(self, sequestered): """Sets the sequestered flag. arg: sequestered (boolean): the new sequestered flag raise: InvalidArgument - ``sequestered`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must ...
python
{ "resource": "" }
q49105
OsidContainableForm.clear_sequestered
train
def clear_sequestered(self): """Clears the sequestered flag. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_sequestered_metadata().is_read_only() ...
python
{ "resource": "" }
q49106
OsidSourceableForm.clear_provider
train
def clear_provider(self): """Removes the provider. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_provider_metadata().is_read_only() o...
python
{ "resource": "" }
q49107
OsidSourceableForm.clear_license
train
def clear_license(self): """Removes the license. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_license_metadata().is_read_only() or ...
python
{ "resource": "" }
q49108
OsidObjectForm._init_metadata
train
def _init_metadata(self, **kwargs): """Initialize metadata for form""" self._mdata.update(default_mdata.get_osid_object_mdata()) OsidForm._init_metadata(self) if 'default_display_name' in kwargs: self._mdata['display_name']['default_string_values'][0]['text'] = kwargs['defaul...
python
{ "resource": "" }
q49109
OsidObjectForm._init_map
train
def _init_map(self, record_types=None): """Initialize map for form""" OsidForm._init_map(self) self._my_map['displayName'] = dict(self._display_name_default) self._my_map['description'] = dict(self._description_default) self._my_map['genusTypeId'] = self._genus_type_default ...
python
{ "resource": "" }
q49110
OsidObjectForm.get_display_name_metadata
train
def get_display_name_metadata(self): """Gets the metadata for a display name. return: (osid.Metadata) - metadata for the display name *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._mdata['display_name']) metadata.update({'existing_...
python
{ "resource": "" }
q49111
OsidObjectForm.get_description_metadata
train
def get_description_metadata(self): """Gets the metadata for a description. return: (osid.Metadata) - metadata for the description *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._mdata['description']) metadata.update({'existing_stri...
python
{ "resource": "" }
q49112
OsidObjectForm.get_genus_type_metadata
train
def get_genus_type_metadata(self): """Gets the metadata for a genus type. return: (osid.Metadata) - metadata for the genus *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._mdata['genus_type']) metadata.update({'existing_string_values...
python
{ "resource": "" }
q49113
OsidObjectForm.clear_genus_type
train
def clear_genus_type(self): """Clears the genus type. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_genus_type_metadata().is_read_only() or ...
python
{ "resource": "" }
q49114
OsidList._get_next_n
train
def _get_next_n(self, object_class, number=None): """Gets the next set of "n" elements in this list. The specified amount must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Relationship`` elements requested which must be...
python
{ "resource": "" }
q49115
OsidList.skip
train
def skip(self, n): """Skip the specified number of elements in the list. If the number skipped is greater than the number of elements in the list, hasNext() becomes false and available() returns zero as there are no more elements to retrieve. arg: n (cardinal): the number of...
python
{ "resource": "" }
q49116
OsidNode.get_parent_ids
train
def get_parent_ids(self): """Gets the parents of this node. return: (osid.id.IdList) - the parents of this node *compliance: mandatory -- This method must be implemented.* """ id_list = [] from ..id.objects import IdList for parent_node in self._my_map['parentNo...
python
{ "resource": "" }
q49117
OsidNode.get_child_ids
train
def get_child_ids(self): """Gets the children of this node. return: (osid.id.IdList) - the children of this node *compliance: mandatory -- This method must be implemented.* """ id_list = [] from ..id.objects import IdList for child_node in self._my_map['childNod...
python
{ "resource": "" }
q49118
FamilyNode.get_family
train
def get_family(self): """Gets the ``Family`` at this node. return: (osid.relationship.Family) - the family represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_provider_ma...
python
{ "resource": "" }
q49119
FamilyNode.get_parent_family_nodes
train
def get_parent_family_nodes(self): """Gets the parents of this family. return: (osid.relationship.FamilyNodeList) - the parents of the ``id`` *compliance: mandatory -- This method must be implemented.* """ parent_family_nodes = [] for node in self._my_ma...
python
{ "resource": "" }
q49120
BasesConfig.set_display_config
train
def set_display_config(cls, config): # pragma: no cover """ Set configuration for superficial aspects of display. :param DisplayConfig config: a configuration object """ cls.DISPLAY_CONFIG = DisplayConfig( show_approx_str=config.show_approx_str, base_conf...
python
{ "resource": "" }
q49121
cache_key
train
def cache_key(model, pk): "Generates a cache key for a model instance." app = model._meta.app_label name = model._meta.module_name return 'api:{0}:{1}:{2}'.format(app, name, pk)
python
{ "resource": "" }
q49122
transcript_to_fake_psl_line
train
def transcript_to_fake_psl_line(self,ref): """Convert a mapping to a fake PSL line :param ref: reference genome dictionary :type ref: dict() :return: psl line :rtype: string """ self._initialize() e = self mylen = 0 matches = 0 qstartslist = [] for exon in self.exons: ...
python
{ "resource": "" }
q49123
SoapTransport.invoke
train
def invoke(self, ns, request_name, params, auth_token, simplify=False): """ Invokes zimbra soap request. """ ZimbraClientTransport.invoke(self, ns, request_name, params, ...
python
{ "resource": "" }
q49124
find_package_data
train
def find_package_data( where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories, only_in_packages=True, show_ignored=False, ): """ Return a dictionary suitable for use in ``package_data`` in a distutils ``setup.py`` file. The dictionary l...
python
{ "resource": "" }
q49125
DateDialog.buttons
train
def buttons(self, master): '''Add a standard button box. Override if you do not want the standard buttons ''' box = tk.Frame(master) ttk.Button( box, text="Next", width=10, command=self.next_day ).pack(side=tk.LEFT, padx=...
python
{ "resource": "" }
q49126
ErrorProfileFactory.close
train
def close(self): """Set some objects to None to hopefully free up some memory.""" self._target_context_errors = None self._query_context_errors = None self._general_errors = None for ae in self._alignment_errors: ae.close() self._alignment_errors = None
python
{ "resource": "" }
q49127
ErrorProfileFactory.add_alignment_errors
train
def add_alignment_errors(self,ae): """If you alread have thealignment errors, add them for profile construction.""" self._target_context_errors = None self._query_context_errors = None self._alignment_errors.append(ae) self._general_errors.add_alignment_errors(ae)
python
{ "resource": "" }
q49128
ErrorProfileFactory.add_alignment
train
def add_alignment(self,align): """Calculate alignment errors from the alignment and add it to the profile.""" self._target_context_errors = None self._query_context_errors = None ae = AlignmentErrors(align) self._alignment_errors.append(ae) self._general_errors.add_alignment_errors(ae)
python
{ "resource": "" }
q49129
ErrorProfileFactory.get_target_context_error_report
train
def get_target_context_error_report(self): """Get a report on context-specific errors relative to what is expected on the target strand. :returns: Object with a 'header' and a 'data' where data describes context: before,after ,reference, query. A total is kept for each reference base, and individual errors ar...
python
{ "resource": "" }
q49130
ErrorProfileFactory.get_min_context_count
train
def get_min_context_count(self,context_type): """Calculate out which context has the minum coverage thusfar. :param context_type: 'target' or 'query' :type context_type: string :returns: Minimum Coverage :rtype: int """ cnt = 10000000000 bases = ['A','C','G','T'] basesplus = ['A','...
python
{ "resource": "" }
q49131
ErrorProfileFactory.write_context_error_report
train
def write_context_error_report(self,file,context_type): """Write a context error report relative to the target or query into the specified filename :param file: The name of a file to write the report to :param context_type: They type of profile, target or query based :type file: string :type contex...
python
{ "resource": "" }
q49132
ErrorProfileFactory.get_query_context_error_report
train
def get_query_context_error_report(self): """Get a report on context-specific errors relative to what is expected on the query strand. :returns: Object with a 'header' and a 'data' where data describes context: before,after ,reference, query. A total is kept for each reference base, and individual errors are ...
python
{ "resource": "" }
q49133
ErrorProfileFactory.get_string
train
def get_string(self): """Make a string reprentation of the error stats. :returns: error profile :rtype: string """ ostr = '' ostr += str(len(self._alignment_errors))+" Alignments\n" ostr += 'Target: '+"\n" totbases = sum([len(x.get_target_sequence()) for x in self._alignment_errors]) ...
python
{ "resource": "" }
q49134
BaseError.get_error_probability
train
def get_error_probability(self): """This means for the base we are talking about how many errors between 0 and 1 do we attribute to it? For the 'unobserved' errors, these can only count when one is adjacent to base :returns: error probability p(error_observed)+(1-p_error_observed)*error_unobserved :...
python
{ "resource": "" }
q49135
BaseError.set_observable
train
def set_observable(self,tseq,qseq): """Set the observable sequence data :param tseq: target sequence (from the homopolymer) :param qseq: query sequence ( from the homopolymer) :type tseq: string :type qseq: string """ tnt = None qnt = None if len(tseq) > 0: tnt = tseq[0] if len...
python
{ "resource": "" }
q49136
BaseError.set_unobserved_before
train
def set_unobserved_before(self,tlen,qlen,nt,p): """Set the unobservable sequence data before this base :param tlen: target homopolymer length :param qlen: query homopolymer length :param nt: nucleotide :param p: p is the probability of attributing this base to the unobserved error :type tlen: i...
python
{ "resource": "" }
q49137
BaseError.set_unobserved_after
train
def set_unobserved_after(self,tlen,qlen,nt,p): """Set the unobservable sequence data after this base :param tlen: target homopolymer length :param qlen: query homopolymer length :param nt: nucleotide :param p: p is the probability of attributing this base to the unobserved error :type tlen: int...
python
{ "resource": "" }
q49138
BaseError.get_adjusted_error_count
train
def get_adjusted_error_count(self): """ Get the total error count associated with this single base. This would typically be one but sometimes it may be larger for instertions. :returns: error_count :rtype: float """ p1 = self._observable.get_attributable_length() p1 += self._unobservabl...
python
{ "resource": "" }
q49139
BaseError.get_base
train
def get_base(self): """ Get the single base at this position. :returns: base :rtype: char """ if self._type == 'query': return self._observable.get_query_base() return self._observable.get_target_base()
python
{ "resource": "" }
q49140
BaseError.get_string
train
def get_string(self): """ Get a string representation of this single base error. :returns: report :rtype: string """ ostr = '' ostr += 'BaseError for ['+self._type+'] base: '+self.get_base()+"\n" if self._observable.get_error_probability() > 0: ostr += ' Homopolymer set:'+"\n" ...
python
{ "resource": "" }
q49141
AlignmentErrors.get_query_errors
train
def get_query_errors(self): """ Return a list of base-wise error observations for the query :returns: list of base-wise errors :rtype: list of HPA groups """ if self._query_errors: return self._query_errors v = [] for i in range(len(self._query_hpas)): v.append(self.get_query_error(...
python
{ "resource": "" }
q49142
AlignmentErrors.get_query_error
train
def get_query_error(self,i): """Just get a single error characterization based on the index :param i: list index :type i: int :returns: base-wise error :rtype: HPA group description """ x = self._query_hpas[i] h = x['hpa'] pos = x['pos'] prob = 0 be = BaseError('query') ...
python
{ "resource": "" }
q49143
AlignmentErrors.analyze_quality
train
def analyze_quality(self): """Go through HPAGroups and store the distro of ordinal values of quality scores""" res = {} for h in self._hpas: if h.type() not in res: res[h.type()]={} for c in h.get_quality(): if c not in res[h.type()]: res[h.type()][c] = 0 res[h.type()][c]...
python
{ "resource": "" }
q49144
AlignmentErrors.get_quality_report_string
train
def get_quality_report_string(self): """get a report on quality score distribution. currently prints to stdout""" if not self._quality_distro: self.analyze_quality() ostr = "" for type in sorted(self._quality_distro.keys()): total = sum([ord(x)*self._quality_distro[type][x] for x in self._q...
python
{ "resource": "" }
q49145
AlignmentErrors._misalign_split
train
def _misalign_split(self,alns): """Requires alignment strings have been set so for each exon we have query, target and query_quality _has_quality will specify whether or not the quality is meaningful """ total = [] z = 0 for x in alns: z += 1 exon_num = z if self._ali...
python
{ "resource": "" }
q49146
GeneralErrorStats.get_string
train
def get_string(self): """make a string representation of the general error report""" ostr = '' errtotal = self.deletions['total']+self.insertions['total']+self.mismatches ostr += 'from '+str(self.alignment_length)+' bp of alignment'+"\n" ostr += ' '+str(float(errtotal)/float(self.alignment_length))...
python
{ "resource": "" }
q49147
GeneralErrorStats.get_stats
train
def get_stats(self): """Return a string describing the stats""" ostr = '' errtotal = self.deletions['total']+self.insertions['total']+self.mismatches ostr += "ALIGNMENT_COUNT\t"+str(self.alignment_count)+"\n" ostr += "ALIGNMENT_BASES\t"+str(self.alignment_length)+"\n" ostr += "ANY_ERROR\t"+str(e...
python
{ "resource": "" }
q49148
GeneralErrorStats.get_report
train
def get_report(self): """Another report, but not context based""" ostr = '' ostr += "target\tquery\tcnt\ttotal\n" poss = ['-','A','C','G','T'] for target in poss: for query in poss: ostr += target+ "\t"+query+"\t"+str(self.matrix[target][query])+"\t"+str(self.alignment_length)+"\n" ...
python
{ "resource": "" }
q49149
GeneralErrorStats.add_alignment_errors
train
def add_alignment_errors(self,ae): """Add alignment errors to the group :param ae: one set of alignment errors :param type: """ self.alignment_count += 1 for v in ae.get_HPAGroups(): self._add_HPAGroup(v)
python
{ "resource": "" }
q49150
CatalogingManager.use_comparative_catalog_view
train
def use_comparative_catalog_view(self): """Pass through to provider CatalogLookupSession.use_comparative_catalog_view""" self._catalog_view = COMPARATIVE # self._get_provider_session('catalog_lookup_session') # To make sure the session is tracked for session in self._get_provider_session...
python
{ "resource": "" }
q49151
CatalogingManager.use_plenary_catalog_view
train
def use_plenary_catalog_view(self): """Pass through to provider CatalogLookupSession.use_plenary_catalog_view""" self._catalog_view = PLENARY # self._get_provider_session('catalog_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): ...
python
{ "resource": "" }
q49152
CatalogingManager.get_catalogs_by_ids
train
def get_catalogs_by_ids(self, *args, **kwargs): """Pass through to provider CatalogLookupSession.get_catalogs_by_ids""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_by_ids catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs_...
python
{ "resource": "" }
q49153
CatalogingManager.get_catalogs
train
def get_catalogs(self): """Pass through to provider CatalogLookupSession.get_catalogs""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs() cat_list = [] ...
python
{ "resource": "" }
q49154
CatalogingManager.create_catalog
train
def create_catalog(self, *args, **kwargs): """Pass through to provider CatalogAdminSession.create_catalog""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.create_bin return Catalog( self._provider_manager, self._get_provider_session('ca...
python
{ "resource": "" }
q49155
CatalogingManager.get_catalog_form
train
def get_catalog_form(self, *args, **kwargs): """Pass through to provider CatalogAdminSession.get_catalog_form_for_update""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.get_bin_form_for_update_template # This method might be a bit sketchy. Time will tell. ...
python
{ "resource": "" }
q49156
CatalogingManager.save_catalog
train
def save_catalog(self, catalog_form, *args, **kwargs): """Pass through to provider CatalogAdminSession.update_catalog""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.update_bin if catalog_form.is_for_update(): return self.update_catalog(catalog_fo...
python
{ "resource": "" }
q49157
D3MDataset.get_data_modality
train
def get_data_modality(self): """Detect the data modality based on the resource_types. resource_types == ['table'] => 'single_table' resource_types == ['something_else'...] => 'something_else' # this is not likely resource_types == ['table', 'table'...] => 'multi_table' resourc...
python
{ "resource": "" }
q49158
D3MDataset._get_resources_by_type
train
def _get_resources_by_type(self, resource_type): """ Returns the list of resources that are of the indicated type """ resources = [] for res in self.dsDoc['dataResources']: if res['resType'] == resource_type: resources.append(res) return resou...
python
{ "resource": "" }
q49159
D3MDataset.get_text_path
train
def get_text_path(self): """ Returns the path of the directory containing text if they exist in this dataset. """ for res in self.dsDoc['dataResources']: resPath = res['resPath'] resType = res['resType'] isCollection = res['isCollection'] i...
python
{ "resource": "" }
q49160
Scope._get_scope_with_mangled
train
def _get_scope_with_mangled(self, name): """Return a scope containing passed mangled name.""" scope = self while True: parent = scope.get_enclosing_scope() if parent is None: return if name in parent.rev_mangled: return parent ...
python
{ "resource": "" }
q49161
Scope._get_scope_with_symbol
train
def _get_scope_with_symbol(self, name): """Return a scope containing passed name as a symbol name.""" scope = self while True: parent = scope.get_enclosing_scope() if parent is None: return if name in parent.symbols: return par...
python
{ "resource": "" }
q49162
Scope.get_next_mangled_name
train
def get_next_mangled_name(self): """ 1. Do not shadow a mangled name from a parent scope if we reference the original name from that scope in this scope or any sub-scope. 2. Do not shadow an original name from a parent scope if it's not mangled and we reference ...
python
{ "resource": "" }
q49163
InlineChoiceTextQuestionFormRecord.remove_choice
train
def remove_choice(self, choice_id, inline_region): """remove a choice, given the id""" if inline_region in self.my_osid_object_form._my_map['choices']: updated_choices = [] for choice in self.my_osid_object_form._my_map['choices'][inline_region]: if choice['id'] !...
python
{ "resource": "" }
q49164
parse_multiple
train
def parse_multiple(s, f, values=None): """Parse multiple comma-separated elements, each of which is parsed using function f.""" if values is None: values = [] values.append(f(s)) if s.pos < len(s) and s.cur == ',': s.pos += 1 return parse_multiple(s, f, values) else: r...
python
{ "resource": "" }
q49165
string_to_state
train
def string_to_state(s): """s is a string possibly preceded by > or @.""" s = lexer(s) attrs = {} while True: if s.cur == '>': attrs['start'] = True s.pos += 1 elif s.cur == '@': attrs['accept'] = True s.pos += 1 else: br...
python
{ "resource": "" }
q49166
string_to_config
train
def string_to_config(s): """s is a comma-separated list of stores.""" from .machines import Configuration s = lexer(s) x = parse_multiple(s, parse_store) parse_end(s) return Configuration(x)
python
{ "resource": "" }
q49167
string_to_transition
train
def string_to_transition(s): """s is a string of the form a,b or a,b->c,d""" from .machines import Transition s = lexer(s) lhs = parse_multiple(s, parse_store) if s.pos < len(s) and s.cur == "->": s.pos += 1 rhs = parse_multiple(s, parse_store) else: rhs = () parse_en...
python
{ "resource": "" }
q49168
hypercube
train
def hypercube(number_of_samples, variables): """ This implements Latin Hypercube Sampling. See https://mathieu.fenniak.net/latin-hypercube-sampling/ for intuitive explanation of what it is :param number_of_samples: number of segments/samples :param variables: initial parameters and conditions (lis...
python
{ "resource": "" }
q49169
Task.run
train
def run(self, collector, image, available_actions, tasks, **extras): """Run this task""" task_func = available_actions[self.action] configuration = collector.configuration.wrapped() if self.options: if image: configuration.update({"images": {image: self.optio...
python
{ "resource": "" }
q49170
Task.find_image
train
def find_image(self, image, configuration): """Complain if we don't have an image""" images = configuration["images"] available = list(images.keys()) if not image: info = {} if available: info["available"] = available raise BadOption("...
python
{ "resource": "" }
q49171
replicate_global_dbs
train
def replicate_global_dbs(cloud_url=None, local_url=None): """ Set up replication of the global databases from the cloud server to the local server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process of initializing t...
python
{ "resource": "" }
q49172
cancel_global_db_replication
train
def cancel_global_db_replication(): """ Cancel replication of the global databases from the cloud server to the local server. """ local_url = config["local_server"]["url"] server = Server(local_url) for db_name in global_dbs: server.cancel_replication(db_name)
python
{ "resource": "" }
q49173
replicate_per_farm_dbs
train
def replicate_per_farm_dbs(cloud_url=None, local_url=None, farm_name=None): """ Sete up replication of the per-farm databases from the local server to the cloud server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process ...
python
{ "resource": "" }
q49174
cancel_per_farm_db_replication
train
def cancel_per_farm_db_replication(): """ Cancel replication of the per-farm databases from the local server to the cloud server. """ cloud_url = config["cloud_server"]["url"] local_url = config["local_server"]["url"] server = Server(local_url) for db_name in per_farm_dbs: server...
python
{ "resource": "" }
q49175
CORS._register_options
train
def _register_options(self, api_interface): # type: (ApiInterfaceBase) -> None """ Register CORS options endpoints. """ op_paths = api_interface.op_paths(collate_methods=True) for path, operations in op_paths.items(): if api.Method.OPTIONS not in operations: ...
python
{ "resource": "" }
q49176
CORS.cors_options
train
def cors_options(self, request, **_): """ CORS options response method. Broken out if this needs to be customised. """ return create_response( request, headers=self.pre_flight_headers(request, request.supported_methods) )
python
{ "resource": "" }
q49177
CORS._options_operation
train
def _options_operation(self, api_interface, path, methods): # type: (ApiInterfaceBase, UrlPath, List[api.Method]) -> None """ Generate an options operation for the specified path """ # Trim off path prefix. if path.startswith(api_interface.path_prefix): path =...
python
{ "resource": "" }
q49178
CORS.allow_origin
train
def allow_origin(self, request): # type: (BaseHttpRequest) -> str """ Generate allow origin header """ origins = self.origins if origins is AnyOrigin: return '*' else: origin = request.origin return origin if origin in origins e...
python
{ "resource": "" }
q49179
CORS.pre_flight_headers
train
def pre_flight_headers(self, request, methods): # type: (BaseHttpRequest, Sequence[api.Method]) -> Dict[str, str] """ Generate pre-flight headers. """ methods = ', '.join(m.value for m in methods) headers = { 'Allow': methods, 'Cache-Control': 'no-...
python
{ "resource": "" }
q49180
CORS.request_headers
train
def request_headers(self, request): """ Generate standard request headers """ headers = {} allow_origin = self.allow_origin(request) if allow_origin: headers = dict_filter({ 'Access-Control-Allow-Origin': allow_origin, 'Access-...
python
{ "resource": "" }
q49181
CORS.post_request
train
def post_request(self, request, response): # type: (BaseHttpRequest, HttpResponse) -> HttpResponse """ Post-request hook to allow CORS headers to responses. """ if request.method != api.Method.OPTIONS: response.headers.update(self.request_headers(request)) ret...
python
{ "resource": "" }
q49182
_muck_w_date
train
def _muck_w_date(record): """muck with the date because EPW starts counting from 1 and goes to 24.""" # minute 60 is actually minute 0? temp_d = datetime.datetime(int(record['Year']), int(record['Month']), int(record['Day']), int(record['Hour']) % 24, ...
python
{ "resource": "" }
q49183
_station_info
train
def _station_info(station_code): """filename based meta data for a station code.""" url_file = open(env.SRC_PATH + '/eere.csv') for line in csv.DictReader(url_file): if line['station_code'] == station_code: return line raise KeyError('Station not found')
python
{ "resource": "" }
q49184
_basename
train
def _basename(station_code, fmt=None): """region, country, weather_station, station_code, data_format, url.""" info = _station_info(station_code) if not fmt: fmt = info['data_format'] basename = '%s.%s' % (info['url'].rsplit('/', 1)[1].rsplit('.', 1)[0], DATA_EXTENTIONS...
python
{ "resource": "" }
q49185
minimum
train
def minimum(station_code): """Extreme Minimum Design Temperature for a location. Degrees in Celcius Args: station_code (str): Weather Station Code Returns: float degrees Celcius """ temp = None fin = None try: fin = open('%s/%s' % (env.WEATHER_DATA_PATH, ...
python
{ "resource": "" }
q49186
EPWdata.next
train
def next(self): """Weather data record. Yields: dict """ record = self.epw_data.next() local_time = _muck_w_date(record) record['datetime'] = local_time # does this fix a specific data set or a general issue? if self.DST: localdt =...
python
{ "resource": "" }
q49187
ensure_string
train
def ensure_string(obj): """Return String and if Unicode convert to string. :param obj: ``str`` || ``unicode`` :return: ``str`` """ if sys.version_info < (3, 2, 0) and isinstance(obj, unicode): return str(obj.encode('utf8')) else: return obj
python
{ "resource": "" }
q49188
dict_update
train
def dict_update(base_dict, update_dict): """Return an updated dictionary. If ``update_dict`` is a dictionary it will be used to update the ` `base_dict`` which is then returned. :param request_kwargs: ``dict`` :param kwargs: ``dict`` :return: ``dict`` """ if isinstance(update_dict, dic...
python
{ "resource": "" }
q49189
ApiInterfaceBase.dispatch_operation
train
def dispatch_operation(self, operation, request, path_args): # type: (Operation, BaseHttpRequest, Dict[str, Any]) -> Tuple[Any, Optional[HTTPStatus], Optional[dict]] """ Dispatch and handle exceptions from operation. """ try: # path_args is passed by ref so changes ca...
python
{ "resource": "" }
q49190
ApiInterfaceBase._dispatch
train
def _dispatch(self, operation, request, path_args): """ Wrapped dispatch method, prepare request and generate a HTTP Response. """ # Determine the request and response types. Ensure API supports the requested types request_type = resolve_content_type(self.request_type_resolvers, ...
python
{ "resource": "" }
q49191
ApiInterfaceBase.dispatch
train
def dispatch(self, operation, request, **path_args): """ Dispatch incoming request and capture top level exceptions. """ # Add current operation to the request (for convenience in middleware methods) request.current_operation = operation try: for middleware i...
python
{ "resource": "" }
q49192
Entry.sector_size
train
def sector_size(self): """ Property with current sector size. CFB file can store normal sectors and smaller ones. """ header = self.source.header return header.mini_sector_size if self._is_mini else header.sector_size
python
{ "resource": "" }
q49193
Entry.left
train
def left(self): """ Entry is left sibling of current directory entry """ return self.source.directory[self.left_sibling_id] \ if self.left_sibling_id != NOSTREAM else None
python
{ "resource": "" }
q49194
Entry.right
train
def right(self): """ Entry is right sibling of current directory entry """ return self.source.directory[self.right_sibling_id] \ if self.right_sibling_id != NOSTREAM else None
python
{ "resource": "" }
q49195
Entry.read
train
def read(self, size=None): """ Reads `size` bytes from current directory entry. If `size` is empty, it'll read all data till entry's end. """ if self._is_mini: self.seek(self._position) else: self.source.seek(self._source_position) if not s...
python
{ "resource": "" }
q49196
Entry.seek
train
def seek(self, offset, whence=SEEK_SET): """ Seeks to specified `offset` position in current directory entry stream. `Whence` can be SEEK_SET - from entry's start, SEEK_CUR - from current position and SEEK_END - from entry's end. Constants are same with same stored `os` module. ...
python
{ "resource": "" }
q49197
RootEntry.child
train
def child(self): """ Root entry object has only one child entry and no siblings. """ return self.stream.directory[self.child_id] \ if self.child_id != NOSTREAM else None
python
{ "resource": "" }
q49198
apply_filter
train
def apply_filter(objs, selector, mode): '''Apply selector to transform each object in objs. This operates in-place on objs. Empty objects are removed from the list. Args: mode: either KEEP (to keep selected items & their ancestors) or DELETE (to delete selected items and their childr...
python
{ "resource": "" }
q49199
apply_selector
train
def apply_selector(objs, selector): '''Returns a list of objects which match the selector in any of objs.''' out = [] for obj in objs: timer.log('Applying selector: %s' % selector) out += list(jsonselect.match(selector, objs)) timer.log('done applying selector') return out
python
{ "resource": "" }