_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q45000
scoreatpercentile
train
def scoreatpercentile(inlist, percent): """ Returns the score at a given percentile relative to the distribution given by inlist. Usage: lscoreatpercentile(inlist,percent) """ if percent > 1: print("\nDividing percent>1 by 100 in lscoreatpercentile().\n") percent = percent / 100.0 targetc...
python
{ "resource": "" }
q45001
cumfreq
train
def cumfreq(inlist, numbins=10, defaultreallimits=None): """ Returns a cumulative frequency histogram, using the histogram function. Usage: lcumfreq(inlist,numbins=10,defaultreallimits=None) Returns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints """ h, l, b, e = histogram(inlist, numbins, ...
python
{ "resource": "" }
q45002
relfreq
train
def relfreq(inlist, numbins=10, defaultreallimits=None): """ Returns a relative frequency histogram, using the histogram function. Usage: lrelfreq(inlist,numbins=10,defaultreallimits=None) Returns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints """ h, l, b, e = histogram(inlist, numbins, de...
python
{ "resource": "" }
q45003
lincc
train
def lincc(x, y): """ Calculates Lin's concordance correlation coefficient. Usage: alincc(x,y) where x, y are equal-length arrays Returns: Lin's CC """ covar = cov(x, y) * (len(x) - 1) / float(len(x)) # correct denom to n xvar = var(x) * (len(x) - 1) / float(len(x)) # correct denom to n yvar = va...
python
{ "resource": "" }
q45004
wilcoxont
train
def wilcoxont(x, y): """ Calculates the Wilcoxon T-test for related samples and returns the result. A non-parametric T-test. Usage: lwilcoxont(x,y) Returns: a t-statistic, two-tail probability estimate """ if len(x) != len(y): raise ValueError('Unequal N in wilcoxont. Aborting.') d = [] for...
python
{ "resource": "" }
q45005
shellsort
train
def shellsort(inlist): """ Shellsort algorithm. Sorts a 1D-list. Usage: lshellsort(inlist) Returns: sorted-inlist, sorting-index-vector (for original list) """ n = len(inlist) svec = copy.deepcopy(inlist) ivec = range(n) gap = n / 2 # integer division needed while gap > 0: for i in...
python
{ "resource": "" }
q45006
rankdata
train
def rankdata(inlist): """ Ranks the data in inlist, dealing with ties appropritely. Assumes a 1D inlist. Adapted from Gary Perlman's |Stat ranksort. Usage: rankdata(inlist) Returns: a list of length equal to inlist, containing rank scores """ n = len(inlist) svec, ivec = shellsort(inlist) sumranks ...
python
{ "resource": "" }
q45007
AdminSite.register_model
train
def register_model(self, model, bundle): """ Registers a bundle as the main bundle for a model. Used when we need to lookup urls by a model. """ if model in self._model_registry: raise AlreadyRegistered('The model %s is already registered' \ ...
python
{ "resource": "" }
q45008
AdminSite.unregister_model
train
def unregister_model(self, model): """ Unregisters the given model. """ if model not in self._model_registry: raise NotRegistered('The model %s is not registered' % model) del self._model_registry[model]
python
{ "resource": "" }
q45009
AdminSite.register
train
def register(self, slug, bundle, order=1, title=None): """ Registers the bundle for a certain slug. If a slug is already registered, this will raise AlreadyRegistered. :param slug: The slug to register. :param bundle: The bundle instance being registered. :param order: ...
python
{ "resource": "" }
q45010
AdminSite.unregister
train
def unregister(self, slug): """ Unregisters the given url. If a slug isn't already registered, this will raise NotRegistered. """ if slug not in self._registry: raise NotRegistered('The slug %s is not registered' % slug) bundle = self._registry[slug] ...
python
{ "resource": "" }
q45011
AdminSite.password_change_done
train
def password_change_done(self, request, extra_context=None): """ Displays the "success" page after a password change. """ from django.contrib.auth.views import password_change_done defaults = { 'extra_context': extra_context or {}, 'template_name': 'cms/pa...
python
{ "resource": "" }
q45012
AdminSite.logout
train
def logout(self, request, extra_context=None): """ Logs out the user for the given HttpRequest. This should *not* assume the user is already logged in. """ from django.contrib.auth.views import logout defaults = { 'extra_context': extra_context or {}, ...
python
{ "resource": "" }
q45013
AdminSite._get_allowed_sections
train
def _get_allowed_sections(self, dashboard): """ Get the sections to display based on dashboard """ allowed_titles = [x[0] for x in dashboard] allowed_sections = [x[2] for x in dashboard] return tuple(allowed_sections), tuple(allowed_titles)
python
{ "resource": "" }
q45014
AdminSite.index
train
def index(self, request, extra_context=None): """ Displays the dashboard. Includes the main navigation that the user has permission for as well as the cms log for those sections. The log list can be filtered by those same sections and is paginated. """ da...
python
{ "resource": "" }
q45015
CacheGroup.register_models
train
def register_models(self, *models, **kwargs): """ Register multiple models with the same arguments. Calls register for each argument passed along with all keyword arguments. """ for model in models: self.register(model, **kwargs)
python
{ "resource": "" }
q45016
CacheGroup.register
train
def register(self, model, values=None, instance_values=None): """ Registers a model with this group. :param values: A list of values that should be incremented \ whenever invalidate_cache is called for a instance or class \ of this type. :param instance_values: A list o...
python
{ "resource": "" }
q45017
CacheGroup.get_version
train
def get_version(self, extra=None): """ This will return a string that can be used as a prefix for django's cache key. Something like key.1 or key.1.2 If a version was not found '1' will be stored and returned as the number for that key. If extra is given a version will ...
python
{ "resource": "" }
q45018
_ancestors
train
def _ancestors(collection): """Get the ancestors of the collection.""" for index, c in enumerate(collection.path_to_root()): if index > 0 and c.dbquery is not None: raise StopIteration yield c.name raise StopIteration
python
{ "resource": "" }
q45019
_build_cache
train
def _build_cache(): """Preprocess collection queries.""" query = current_app.config['COLLECTIONS_DELETED_RECORDS'] for collection in Collection.query.filter( Collection.dbquery.isnot(None)).all(): yield collection.name, dict( query=query.format(dbquery=collection.dbquery), ...
python
{ "resource": "" }
q45020
_find_matching_collections_internally
train
def _find_matching_collections_internally(collections, record): """Find matching collections with internal engine. :param collections: set of collections where search :param record: record to match """ for name, data in iteritems(collections): if _build_query(data['query']).match(record): ...
python
{ "resource": "" }
q45021
get_record_collections
train
def get_record_collections(record, matcher): """Return list of collections to which record belongs to. :param record: Record instance. :param matcher: Function used to check if a record belongs to a collection. :return: list of collection names. """ collections = current_collections.collections...
python
{ "resource": "" }
q45022
dfs
train
def dfs(graph, func, head, reverse=None): """ DEPTH FIRST SEARCH IF func RETURNS FALSE, THEN PATH IS NO LONGER TAKEN IT'S EXPECTED func TAKES 3 ARGUMENTS node - THE CURRENT NODE IN THE path - PATH FROM head TO node graph - THE WHOLE GRAPH """ todo = deque() todo.append(head) ...
python
{ "resource": "" }
q45023
bfs
train
def bfs(graph, func, head, reverse=None): """ BREADTH FIRST SEARCH IF func RETURNS FALSE, THEN NO MORE PATHS DOWN THE BRANCH ARE TAKEN IT'S EXPECTED func TAKES THESE ARGUMENTS: node - THE CURRENT NODE IN THE path - PATH FROM head TO node graph - THE WHOLE GRAPH todo - WHAT'S IN THE QUE...
python
{ "resource": "" }
q45024
dominator_tree
train
def dominator_tree(graph): """ RETURN DOMINATOR FOREST THERE ARE TWO TREES, "ROOTS" and "LOOPS" ROOTS HAVE NO PARENTS LOOPS ARE NODES THAT ARE A MEMBER OF A CYCLE THAT HAS NO EXTRNAL PARENT roots = dominator_tree(graph).get_children(ROOTS) """ todo = Queue() done = set() dominat...
python
{ "resource": "" }
q45025
get_schema_from_list
train
def get_schema_from_list(table_name, frum): """ SCAN THE LIST FOR COLUMN TYPES """ columns = UniqueIndex(keys=("name",)) _get_schema_from_list(frum, ".", parent=".", nested_path=ROOT_PATH, columns=columns) return Schema(table_name=table_name, columns=list(columns))
python
{ "resource": "" }
q45026
ColumnList.denormalized
train
def denormalized(self): """ THE INTERNAL STRUCTURE FOR THE COLUMN METADATA IS VERY DIFFERENT FROM THE DENORMALIZED PERSPECITVE. THIS PROVIDES THAT PERSPECTIVE FOR QUERIES """ with self.locker: self._update_meta() output = [ { ...
python
{ "resource": "" }
q45027
parse_tibiadata_datetime
train
def parse_tibiadata_datetime(date_dict) -> Optional[datetime.datetime]: """Parses time objects from the TibiaData API. Time objects are made of a dictionary with three keys: date: contains a string representation of the time timezone: a string representation of the timezone the date time is bas...
python
{ "resource": "" }
q45028
try_datetime
train
def try_datetime(obj) -> Optional[datetime.datetime]: """Attempts to convert an object into a datetime. If the date format is known, it's recommended to use the corresponding function This is meant to be used in constructors. Parameters ---------- obj: :class:`str`, :class:`dict`, :class:`date...
python
{ "resource": "" }
q45029
try_date
train
def try_date(obj) -> Optional[datetime.date]: """Attempts to convert an object into a date. If the date format is known, it's recommended to use the corresponding function This is meant to be used in constructors. Parameters ---------- obj: :class:`str`, :class:`datetime.datetime`, :class:`dat...
python
{ "resource": "" }
q45030
try_enum
train
def try_enum(cls: Type[T], val, default: D = None) -> Union[T, D]: """Attempts to convert a value into their enum value Parameters ---------- cls: :class:`Enum` The enum to convert to. val: The value to try to convert to Enum default: optional The value to return if no e...
python
{ "resource": "" }
q45031
parse_json
train
def parse_json(content): """Tries to parse a string into a json object. This also performs a trim of all values, recursively removing leading and trailing whitespace. Parameters ---------- content: A JSON format string. Returns ------- obj: The object represented by the json s...
python
{ "resource": "" }
q45032
get_social_share_link
train
def get_social_share_link(context, share_link, object_url, object_title): """ Construct the social share link for the request object. """ request = context['request'] url = unicode(object_url) if 'http' not in object_url.lower(): full_path = ''.join(('http', ('', 's')[request.is_secure...
python
{ "resource": "" }
q45033
NaiveGraph.get_family
train
def get_family(self, node): """ RETURN ALL ADJACENT NODES """ return set(p if c == node else c for p, c in self.get_edges(node))
python
{ "resource": "" }
q45034
ChoicesFieldListFilter.choices
train
def choices(self, cl): """ Take choices from field's 'choices' attribute for 'ChoicesField' and use 'flatchoices' as usual for other fields. """ #: Just tidy up standard implementation for the sake of DRY principle. def _choice_item(is_selected, query_string, title): ...
python
{ "resource": "" }
q45035
page_factory
train
def page_factory(request): """ Page factory. Config models example: .. code-block:: python models = { '': [WebPage, CatalogResource], 'catalogue': CatalogResource, 'news': NewsResource, } """ prefix = request.matchdict['prefix'] # /{prefix}/pag...
python
{ "resource": "" }
q45036
register_views
train
def register_views(*args): """ Registration view for each resource from config. """ config = args[0] settings = config.get_settings() pages_config = settings[CONFIG_MODELS] resources = resources_of_config(pages_config) for resource in resources: if hasattr(resource, '__table__')\ ...
python
{ "resource": "" }
q45037
Tracker.add_phase
train
def add_phase(self): """Context manager for when adding all the tokens""" # add stuff yield self # Make sure we output eveything self.finish_hanging() # Remove trailing indents and dedents while len(self.result) > 1 and self.result[-2][0] in (INDENT, ERRORTOKEN,...
python
{ "resource": "" }
q45038
Tracker.next_token
train
def next_token(self, tokenum, value, scol): """Determine what to do with the next token""" # Make self.current reflect these values self.current.set(tokenum, value, scol) # Determine indent_type based on this token if self.current.tokenum == INDENT and self.current.value: ...
python
{ "resource": "" }
q45039
Tracker.progress
train
def progress(self): """ Deal with next token Used to create, fillout and end groups and singles As well as just append everything else """ tokenum, value, scol = self.current.values() # Default to not appending anything just_append = False ...
python
{ "resource": "" }
q45040
Tracker.reset_indentation
train
def reset_indentation(self, amount): """Replace previous indentation with desired amount""" while self.result and self.result[-1][0] == INDENT: self.result.pop() self.result.append((INDENT, amount))
python
{ "resource": "" }
q45041
Tracker.ignore_token
train
def ignore_token(self): """Determine if we should ignore current token""" def get_next_ignore(remove=False): """Get next ignore from ignore_next and remove from ignore_next""" next_ignore = self.ignore_next # Just want to return it, don't want to remove yet ...
python
{ "resource": "" }
q45042
Tracker.make_describe_attrs
train
def make_describe_attrs(self): """Create tokens for setting is_noy_spec on describes""" lst = [] if self.all_groups: lst.append((NEWLINE, '\n')) lst.append((INDENT, '')) for group in self.all_groups: if group.name: lst.exte...
python
{ "resource": "" }
q45043
Tracker.forced_insert
train
def forced_insert(self): """ Insert tokens if self.insert_till hasn't been reached yet Will respect self.inserted_line and make sure token is inserted before it Returns True if it appends anything or if it reached the insert_till token """ # If we have any tok...
python
{ "resource": "" }
q45044
Tracker.add_tokens_for_pass
train
def add_tokens_for_pass(self): """Add tokens for a pass to result""" # Make sure pass not added to group again self.groups.empty = False # Remove existing newline/indentation while self.result[-1][0] in (INDENT, NEWLINE): self.result.pop() # Add pass and ind...
python
{ "resource": "" }
q45045
Tracker.add_tokens_for_group
train
def add_tokens_for_group(self, with_pass=False): """Add the tokens for the group signature""" kls = self.groups.super_kls name = self.groups.kls_name # Reset indentation to beginning and add signature self.reset_indentation('') self.result.extend(self.tokens.make_describ...
python
{ "resource": "" }
q45046
Tracker.add_tokens_for_single
train
def add_tokens_for_single(self, ignore=False): """Add the tokens for the single signature""" args = self.single.args name = self.single.python_name # Reset indentation to proper amount and add signature self.reset_indentation(self.indent_type * self.single.indent) self.r...
python
{ "resource": "" }
q45047
Tracker.finish_hanging
train
def finish_hanging(self): """Add tokens for hanging singature if any""" if self.groups.starting_signature: if self.groups.starting_group: self.add_tokens_for_group(with_pass=True) elif self.groups.starting_single: self.add_tokens_for_single(ignore...
python
{ "resource": "" }
q45048
Tracker.determine_indentation
train
def determine_indentation(self): """Reset indentation for current token and in self.result to be consistent and normalized""" # Ensuring NEWLINE tokens are actually specified as such if self.current.tokenum != NEWLINE and self.current.value == '\n': self.current.tokenum = NEWLINE ...
python
{ "resource": "" }
q45049
Tracker.convert_dedent
train
def convert_dedent(self): """Convert a dedent into an indent""" # Dedent means go back to last indentation if self.indent_amounts: self.indent_amounts.pop() # Change the token tokenum = INDENT # Get last indent amount last_indent = 0 if self....
python
{ "resource": "" }
q45050
lookupAll
train
def lookupAll(data, configFields, lookupType, db, histObj={}): """ Return a record after having cleaning rules of specified type applied to all fields in the config :param dict data: single record (dictionary) to which cleaning rules should be applied :param dict configFields: "fields" object from DWM ...
python
{ "resource": "" }
q45051
DeriveDataLookupAll
train
def DeriveDataLookupAll(data, configFields, db, histObj={}): """ Return a record after performing derive rules for all fields, based on config :param dict data: single record (dictionary) to which cleaning rules should be applied :param dict configFields: "fields" object from DWM config (see DataDictio...
python
{ "resource": "" }
q45052
Router._get_generators
train
def _get_generators(self): """Get installed banana plugins. :return: dictionary of installed generators name: distribution """ # on using entrypoints: # http://stackoverflow.com/questions/774824/explain-python-entry-points # TODO: make sure we do not have conflicting gen...
python
{ "resource": "" }
q45053
Router._get_generator
train
def _get_generator(self, name): """Load the generator plugin and execute its lifecycle. :param dist: distribution """ for ep in pkg_resources.iter_entry_points(self.group, name=None): if ep.name == name: generator = ep.load() return generator
python
{ "resource": "" }
q45054
Router.parse_args
train
def parse_args(self, doc, argv): """Parse ba arguments :param args: sys.argv[1:] :return: arguments """ # first a little sneak peak if we have a generator arguments = docopt(doc, argv=argv, help=False) if arguments.get('<generator>'): name = arguments...
python
{ "resource": "" }
q45055
Router.register_route
train
def register_route(self, name, route): """Register a route handler :param name: Name of the route :param route: Route handler """ try: self.routes[name] = route.handle except Exception as e: print('could not import handle, maybe something wrong ',...
python
{ "resource": "" }
q45056
Serializable.to_json
train
def to_json(self, *, indent=None, sort_keys = False): """Gets the object's JSON representation. Parameters ---------- indent: :class:`int`, optional Number of spaces used as indentation, ``None`` will return the shortest possible string. sort_keys: :class:`bool`, opt...
python
{ "resource": "" }
q45057
get_game
train
def get_game(site, description="", create=False): """ get the current game, if its still active, else creates a new game, if the current time is inside the GAME_START_TIMES interval and create=True @param create: create a game, if there is no active game @returns: None if the...
python
{ "resource": "" }
q45058
Game.words_with_votes
train
def words_with_votes(self, only_topics=True): """ returns a list with words ordered by the number of votes annotated with the number of votes in the "votes" property. """ result = Word.objects.filter( bingofield__board__game__id=self.id).exclude( t...
python
{ "resource": "" }
q45059
literals
train
def literals(choices, prefix="", suffix=""): """Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually. """ return "|".join(prefix + re.escape(c) + suffix for c in choices.split())
python
{ "resource": "" }
q45060
Lexer.lex
train
def lex(self, text, start=0): """Lexically analyze `text`. Yields pairs (`name`, `tokentext`). """ max = len(text) eaten = start s = self.state r = self.regexes toks = self.toks while eaten < max: for match in r[s].finditer(text, eate...
python
{ "resource": "" }
q45061
new_instance
train
def new_instance(settings): """ MAKE A PYTHON INSTANCE `settings` HAS ALL THE `kwargs`, PLUS `class` ATTRIBUTE TO INDICATE THE CLASS TO CREATE """ settings = set_default({}, settings) if not settings["class"]: Log.error("Expecting 'class' attribute with fully qualified class name") ...
python
{ "resource": "" }
q45062
normalize_fieldsets
train
def normalize_fieldsets(fieldsets): """ Make sure the keys in fieldset dictionaries are strings. Returns the normalized data. """ result = [] for name, options in fieldsets: result.append((name, normalize_dictionary(options))) return result
python
{ "resource": "" }
q45063
get_sort_field
train
def get_sort_field(attr, model): """ Get's the field to sort on for the given attr. Currently returns attr if it is a field on the given model. If the models has an attribute matching that name and that value has an attribute 'sort_field' than that value is used. TODO: Provide a w...
python
{ "resource": "" }
q45064
AdminList.labels
train
def labels(self): """ Get field label for fields """ if type(self.object_list) == type([]): model = self.formset.model else: model = self.object_list.model for field in self.visible_fields: name = None if self.formset: ...
python
{ "resource": "" }
q45065
password_change
train
def password_change(request, username, template_name='accounts/password_form.html', pass_form=PasswordChangeForm, success_url=None, extra_context=None): """ Change password of user. This view is almost a mirror of the view supplied in :func:`contr...
python
{ "resource": "" }
q45066
account_delete
train
def account_delete(request, username, template_name=accounts_settings.ACCOUNTS_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): """ Delete an account. """ user = get_object_or_404(get_user_model(), username__iexact=username) user.is_active = False ...
python
{ "resource": "" }
q45067
parse_properties
train
def parse_properties(parent_index_name, parent_name, nested_path, esProperties): """ RETURN THE COLUMN DEFINITIONS IN THE GIVEN esProperties OBJECT """ columns = FlatList() for name, property in esProperties.items(): index_name = parent_index_name column_name = concat_field(parent_na...
python
{ "resource": "" }
q45068
_merge_mapping
train
def _merge_mapping(a, b): """ MERGE TWO MAPPINGS, a TAKES PRECEDENCE """ for name, b_details in b.items(): a_details = a[literal_field(name)] if a_details.properties and not a_details.type: a_details.type = "object" if b_details.properties and not b_details.type: ...
python
{ "resource": "" }
q45069
Index.delete_all_but_self
train
def delete_all_but_self(self): """ DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name """ prefix = self.settings.alias name = self.settings.index if prefix == name: Log.note("{{index_name}} will not be deleted", index_name= prefix) for a in self.clust...
python
{ "resource": "" }
q45070
Index.is_proto
train
def is_proto(self, index): """ RETURN True IF THIS INDEX HAS NOT BEEN ASSIGNED ITS ALIAS """ for a in self.cluster.get_aliases(): if a.index == index and a.alias: return False return True
python
{ "resource": "" }
q45071
Cluster.get_index
train
def get_index(self, index, type, alias=None, typed=None, read_only=True, kwargs=None): """ TESTS THAT THE INDEX EXISTS BEFORE RETURNING A HANDLE """ if kwargs.tjson != None: Log.error("used `typed` parameter, not `tjson`") if read_only: # GET EXACT MATCH, ...
python
{ "resource": "" }
q45072
Cluster.get_prototype
train
def get_prototype(self, alias): """ RETURN ALL INDEXES THAT ARE INTENDED TO BE GIVEN alias, BUT HAVE NO ALIAS YET BECAUSE INCOMPLETE """ output = sort([ a.index for a in self.get_aliases() if re.match(re.escape(alias) + "\\d{8}_\\d{6}", a.index...
python
{ "resource": "" }
q45073
SQLBuilder.add_sql
train
def add_sql(self, value, clause): """ Add a WHERE clause to the state. :param value: The unknown to bind into the state. Uses SQLBuilder._map_value() to map this into an appropriate database compatible type. :param clause: A SQL fragment defining the ...
python
{ "resource": "" }
q45074
SQLBuilder.add_metadata_query_properties
train
def add_metadata_query_properties(self, meta_constraints, id_table, id_column): """ Construct WHERE clauses from a list of MetaConstraint objects, adding them to the query state. :param meta_constraints: A list of MetaConstraint objects, each of which defines a condition over metada...
python
{ "resource": "" }
q45075
SQLBuilder.get_select_sql
train
def get_select_sql(self, columns, order=None, limit=0, skip=0): """ Build a SELECT query based on the current state of the builder. :param columns: SQL fragment describing which columns to select i.e. 'e.obstoryID, s.statusID' :param order: Optional ordering cons...
python
{ "resource": "" }
q45076
SQLBuilder.get_count_sql
train
def get_count_sql(self): """ Build a SELECT query which returns the count of items for an unlimited SELECT :return: A SQL SELECT query which returns the count of items for an unlimited query based on this SQLBuilder """ sql = 'SELECT COUNT(*) FROM ' + self.tables ...
python
{ "resource": "" }
q45077
SinonBase.wrap2spy
train
def wrap2spy(self): """ Wrapping the inspector as a spy based on the type """ if self.args_type == "MODULE_FUNCTION": self.orig_func = deepcopy(getattr(self.obj, self.prop)) setattr(self.obj, self.prop, Wrapper.wrap_spy(getattr(self.obj, self.prop))) elif ...
python
{ "resource": "" }
q45078
SinonBase.unwrap
train
def unwrap(self): """ Unwrapping the inspector based on the type """ if self.args_type == "MODULE_FUNCTION": setattr(self.obj, self.prop, self.orig_func) elif self.args_type == "MODULE": delattr(self.obj, "__SINONLOCK__") elif self.args_type == "FU...
python
{ "resource": "" }
q45079
jx_type
train
def jx_type(column): """ return the jx_type for given column """ if column.es_column.endswith(EXISTS_TYPE): return EXISTS return es_type_to_json_type[column.es_type]
python
{ "resource": "" }
q45080
ElasticsearchMetadata.get_columns
train
def get_columns(self, table_name, column_name=None, after=None, timeout=None): """ RETURN METADATA COLUMNS :param table_name: TABLE WE WANT COLUMNS FOR :param column_name: OPTIONAL NAME, IF INTERESTED IN ONLY ONE COLUMN :param after: FORCE LOAD, WAITING FOR last_updated TO BE A...
python
{ "resource": "" }
q45081
Snowflake.query_paths
train
def query_paths(self): """ RETURN A LIST OF ALL NESTED COLUMNS """ output = self.namespace.alias_to_query_paths.get(self.name) if output: return output Log.error("Can not find index {{index|quote}}", index=self.name)
python
{ "resource": "" }
q45082
Snowflake.sorted_query_paths
train
def sorted_query_paths(self): """ RETURN A LIST OF ALL SCHEMA'S IN DEPTH-FIRST TOPOLOGICAL ORDER """ return list(reversed(sorted(p[0] for p in self.namespace.alias_to_query_paths.get(self.name))))
python
{ "resource": "" }
q45083
Schema.values
train
def values(self, column_name, exclude_type=STRUCT): """ RETURN ALL COLUMNS THAT column_name REFERS TO """ column_name = unnest_path(column_name) columns = self.columns output = [] for path in self.query_path: full_path = untype_path(concat_field(path, ...
python
{ "resource": "" }
q45084
get_decoders_by_path
train
def get_decoders_by_path(query): """ RETURN MAP FROM QUERY PATH TO LIST OF DECODER ARRAYS :param query: :return: """ schema = query.frum.schema output = Data() if query.edges: if query.sort and query.format != "cube": # REORDER EDGES/GROUPBY TO MATCH THE SORT ...
python
{ "resource": "" }
q45085
make_default
train
def make_default(spec): """Create an empty document that follows spec. Any field with a default will take that value, required or not. Required fields with no default will get a value of None. If your default value does not match your type or otherwise customized Field class, this can create a spec t...
python
{ "resource": "" }
q45086
validate
train
def validate(document, spec): """Validate that a document meets a specification. Returns True if validation was successful, but otherwise raises a ValueError.""" if not spec: return True missing = [] for key, field in spec.iteritems(): if field.required and key not in document: ...
python
{ "resource": "" }
q45087
Field.typecheck
train
def typecheck(self, t): """Create a typecheck from some value ``t``. This behaves differently depending on what ``t`` is. It should take a value and return True if the typecheck passes, or False otherwise. Override ``pre_validate`` in a child class to do type coercion. * If `...
python
{ "resource": "" }
q45088
Field.validate
train
def validate(self, value): """Validate a value for this field. If the field is invalid, this will raise a ValueError. Runs ``pre_validate`` hook prior to validation, and returns value if validation passes.""" value = self.pre_validate(value) if not self._typecheck(value): ...
python
{ "resource": "" }
q45089
TUIDService.init_db
train
def init_db(self): ''' Creates all the tables, and indexes needed for the service. :return: None ''' with self.conn.transaction() as t: t.execute(''' CREATE TABLE temporal ( tuid INTEGER, revision CHAR(12) NOT NULL, ...
python
{ "resource": "" }
q45090
TUIDService.get_tuids_from_revision
train
def get_tuids_from_revision(self, revision): """ Gets the TUIDs for the files modified by a revision. :param revision: revision to get files from :return: list of (file, list(tuids)) tuples """ result = [] URL_TO_FILES = self.hg_url / self.config.hg.branch / 'jso...
python
{ "resource": "" }
q45091
TUIDService._check_branch
train
def _check_branch(self, revision, branch): ''' Used to find out if the revision is in the given branch. :param revision: Revision to check. :param branch: Branch to check revision on. :return: True/False - Found it/Didn't find it ''' # Get a changelog cl...
python
{ "resource": "" }
q45092
TUIDService.get_tuids
train
def get_tuids(self, files, revision, commit=True, chunk=50, repo=None): ''' Wrapper for `_get_tuids` to limit the number of annotation calls to hg and separate the calls from DB transactions. Also used to simplify `_get_tuids`. :param files: :param revision: :param commi...
python
{ "resource": "" }
q45093
addSubparser
train
def addSubparser(subparsers, subcommand, description): """ Add a subparser with subcommand to the subparsers object """ parser = subparsers.add_parser( subcommand, description=description, help=description) return parser
python
{ "resource": "" }
q45094
createArgumentParser
train
def createArgumentParser(description): """ Create an argument parser """ parser = argparse.ArgumentParser( description=description, formatter_class=SortedHelpFormatter) return parser
python
{ "resource": "" }
q45095
SortedHelpFormatter.add_arguments
train
def add_arguments(self, actions): """ Sort the flags alphabetically """ actions = sorted( actions, key=operator.attrgetter('option_strings')) super(SortedHelpFormatter, self).add_arguments(actions)
python
{ "resource": "" }
q45096
SortedHelpFormatter._iter_indented_subactions
train
def _iter_indented_subactions(self, action): """ Sort the subcommands alphabetically """ try: get_subactions = action._get_subactions except AttributeError: pass else: self._indent() if isinstance(action, argparse._SubParser...
python
{ "resource": "" }
q45097
resource_of_node
train
def resource_of_node(resources, node): """ Returns resource of node. """ for resource in resources: model = getattr(resource, 'model', None) if type(node) == model: return resource return BasePageResource
python
{ "resource": "" }
q45098
resources_of_config
train
def resources_of_config(config): """ Returns all resources and models from config. """ return set( # unique values sum([ # join lists to flat list list(value) # if value is iter (ex: list of resources) if hasattr(value, '__iter__') el...
python
{ "resource": "" }
q45099
models_of_config
train
def models_of_config(config): """ Return list of models from all resources in config. """ resources = resources_of_config(config) models = [] for resource in resources: if not hasattr(resource, '__table__') and hasattr(resource, 'model'): models.append(resource.model) els...
python
{ "resource": "" }