repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.set_domain
def set_domain(clz, dag): """ Sets the domain. Should only be called once per class instantiation. """ logging.info("Setting domain for poset %s" % clz.__name__) if nx.number_of_nodes(dag) == 0: raise CellConstructionFailure("Empty DAG structure.") if not nx.is_...
python
def set_domain(clz, dag): """ Sets the domain. Should only be called once per class instantiation. """ logging.info("Setting domain for poset %s" % clz.__name__) if nx.number_of_nodes(dag) == 0: raise CellConstructionFailure("Empty DAG structure.") if not nx.is_...
[ "def", "set_domain", "(", "clz", ",", "dag", ")", ":", "logging", ".", "info", "(", "\"Setting domain for poset %s\"", "%", "clz", ".", "__name__", ")", "if", "nx", ".", "number_of_nodes", "(", "dag", ")", "==", "0", ":", "raise", "CellConstructionFailure", ...
Sets the domain. Should only be called once per class instantiation.
[ "Sets", "the", "domain", ".", "Should", "only", "be", "called", "once", "per", "class", "instantiation", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L67-L78
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.get_boundaries
def get_boundaries(self): """ Returns just the upper and lower boundaries [upper, lower] representing the most general positive boundaries and the most specific lower boundaries """ if not self.__values_computed: self.__compute_values() return set(self...
python
def get_boundaries(self): """ Returns just the upper and lower boundaries [upper, lower] representing the most general positive boundaries and the most specific lower boundaries """ if not self.__values_computed: self.__compute_values() return set(self...
[ "def", "get_boundaries", "(", "self", ")", ":", "if", "not", "self", ".", "__values_computed", ":", "self", ".", "__compute_values", "(", ")", "return", "set", "(", "self", ".", "upper", ")", ",", "set", "(", "self", ".", "lower", ")" ]
Returns just the upper and lower boundaries [upper, lower] representing the most general positive boundaries and the most specific lower boundaries
[ "Returns", "just", "the", "upper", "and", "lower", "boundaries", "[", "upper", "lower", "]", "representing", "the", "most", "general", "positive", "boundaries", "and", "the", "most", "specific", "lower", "boundaries" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L98-L106
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.compute_upper_bound
def compute_upper_bound(self): """ We have to compute the new upper boundary (nub) starting from the root nodes. If a path exists between a root node and another entry in `self.upper` we can ignore the root node because it has been specialized by one of its successors. "...
python
def compute_upper_bound(self): """ We have to compute the new upper boundary (nub) starting from the root nodes. If a path exists between a root node and another entry in `self.upper` we can ignore the root node because it has been specialized by one of its successors. "...
[ "def", "compute_upper_bound", "(", "self", ")", ":", "nub", "=", "set", "(", ")", "for", "root", "in", "self", ".", "roots", "-", "self", ".", "upper", ":", "found", "=", "False", "for", "up", "in", "self", ".", "upper", "-", "self", ".", "roots", ...
We have to compute the new upper boundary (nub) starting from the root nodes. If a path exists between a root node and another entry in `self.upper` we can ignore the root node because it has been specialized by one of its successors.
[ "We", "have", "to", "compute", "the", "new", "upper", "boundary", "(", "nub", ")", "starting", "from", "the", "root", "nodes", ".", "If", "a", "path", "exists", "between", "a", "root", "node", "and", "another", "entry", "in", "self", ".", "upper", "we"...
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L108-L125
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.is_domain_equal
def is_domain_equal(self, other): """ Computes whether two Partial Orderings have the same generalization structure. """ domain = self.get_domain() other_domain = other.get_domain() # if they share the same instance of memory for the domain if domain == ot...
python
def is_domain_equal(self, other): """ Computes whether two Partial Orderings have the same generalization structure. """ domain = self.get_domain() other_domain = other.get_domain() # if they share the same instance of memory for the domain if domain == ot...
[ "def", "is_domain_equal", "(", "self", ",", "other", ")", ":", "domain", "=", "self", ".", "get_domain", "(", ")", "other_domain", "=", "other", ".", "get_domain", "(", ")", "# if they share the same instance of memory for the domain", "if", "domain", "==", "other...
Computes whether two Partial Orderings have the same generalization structure.
[ "Computes", "whether", "two", "Partial", "Orderings", "have", "the", "same", "generalization", "structure", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L145-L156
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.is_equal
def is_equal(self, other): """ Computes whether two Partial Orderings contain the same information """ if not (hasattr(other, 'get_domain') or hasattr(other, 'upper') or hasattr(other, 'lower')): other = self.coerce(other) if self.is_domain_equal(other) \ ...
python
def is_equal(self, other): """ Computes whether two Partial Orderings contain the same information """ if not (hasattr(other, 'get_domain') or hasattr(other, 'upper') or hasattr(other, 'lower')): other = self.coerce(other) if self.is_domain_equal(other) \ ...
[ "def", "is_equal", "(", "self", ",", "other", ")", ":", "if", "not", "(", "hasattr", "(", "other", ",", "'get_domain'", ")", "or", "hasattr", "(", "other", ",", "'upper'", ")", "or", "hasattr", "(", "other", ",", "'lower'", ")", ")", ":", "other", ...
Computes whether two Partial Orderings contain the same information
[ "Computes", "whether", "two", "Partial", "Orderings", "contain", "the", "same", "information" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L161-L171
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.is_entailed_by
def is_entailed_by(self, other): """ Returns True iff Other (a) has the same domain, (b) the same or more specific 'upper' bound; and (c) the same or more general 'lower' bound. Approach: Looks for ways to rule out entailment. If none are found, retu...
python
def is_entailed_by(self, other): """ Returns True iff Other (a) has the same domain, (b) the same or more specific 'upper' bound; and (c) the same or more general 'lower' bound. Approach: Looks for ways to rule out entailment. If none are found, retu...
[ "def", "is_entailed_by", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_domain_equal", "(", "other", ")", ":", "return", "False", "\"\"\" \n First we compare the similarity between upper bounds, \n (1) if Self's upper bound is empty, Ot...
Returns True iff Other (a) has the same domain, (b) the same or more specific 'upper' bound; and (c) the same or more general 'lower' bound. Approach: Looks for ways to rule out entailment. If none are found, returns True
[ "Returns", "True", "iff", "Other", "(", "a", ")", "has", "the", "same", "domain", "(", "b", ")", "the", "same", "or", "more", "specific", "upper", "bound", ";", "and", "(", "c", ")", "the", "same", "or", "more", "general", "lower", "bound", ".", "A...
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L179-L249
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.is_contradictory
def is_contradictory(self, other): """ Does the merge yield the empty set? """ if not self.is_domain_equal(other): return True # what would happen if the two were combined? test_lower = self.lower.union(other.lower) test_upper = self.upper.union(othe...
python
def is_contradictory(self, other): """ Does the merge yield the empty set? """ if not self.is_domain_equal(other): return True # what would happen if the two were combined? test_lower = self.lower.union(other.lower) test_upper = self.upper.union(othe...
[ "def", "is_contradictory", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_domain_equal", "(", "other", ")", ":", "return", "True", "# what would happen if the two were combined? ", "test_lower", "=", "self", ".", "lower", ".", "union", "(", ...
Does the merge yield the empty set?
[ "Does", "the", "merge", "yield", "the", "empty", "set?" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L252-L271
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.coerce
def coerce(self, other, is_positive=True): """ Only copies a pointer to the new domain's cell """ if hasattr(other, 'get_domain') and hasattr(other, 'lower') and hasattr(other, 'upper'): if self.is_domain_equal(other): return other else: ...
python
def coerce(self, other, is_positive=True): """ Only copies a pointer to the new domain's cell """ if hasattr(other, 'get_domain') and hasattr(other, 'lower') and hasattr(other, 'upper'): if self.is_domain_equal(other): return other else: ...
[ "def", "coerce", "(", "self", ",", "other", ",", "is_positive", "=", "True", ")", ":", "if", "hasattr", "(", "other", ",", "'get_domain'", ")", "and", "hasattr", "(", "other", ",", "'lower'", ")", "and", "hasattr", "(", "other", ",", "'upper'", ")", ...
Only copies a pointer to the new domain's cell
[ "Only", "copies", "a", "pointer", "to", "the", "new", "domain", "s", "cell" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L273-L301
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.merge
def merge(self, other, is_positive=True): """ Combines the partial order with either (1) a value in the partial order's domain, or (2) another partial order with the same domain. When combining with a value, an optional `is_positive` parameter can be set to False, meaning that the merg...
python
def merge(self, other, is_positive=True): """ Combines the partial order with either (1) a value in the partial order's domain, or (2) another partial order with the same domain. When combining with a value, an optional `is_positive` parameter can be set to False, meaning that the merg...
[ "def", "merge", "(", "self", ",", "other", ",", "is_positive", "=", "True", ")", ":", "other", "=", "self", ".", "coerce", "(", "other", ",", "is_positive", ")", "# the above coercion forces equal domains, and raises an ", "# exception otherwise", "if", "self", "....
Combines the partial order with either (1) a value in the partial order's domain, or (2) another partial order with the same domain. When combining with a value, an optional `is_positive` parameter can be set to False, meaning that the merged value should be excluded.
[ "Combines", "the", "partial", "order", "with", "either", "(", "1", ")", "a", "value", "in", "the", "partial", "order", "s", "domain", "or", "(", "2", ")", "another", "partial", "order", "with", "the", "same", "domain", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L303-L351
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.get_refinement_options
def get_refinement_options(self): """ Returns possible specializations for the upper values in the taxonomy """ domain = self.get_domain() for upper_value in self.upper: for suc in domain.successors(upper_value): yield suc
python
def get_refinement_options(self): """ Returns possible specializations for the upper values in the taxonomy """ domain = self.get_domain() for upper_value in self.upper: for suc in domain.successors(upper_value): yield suc
[ "def", "get_refinement_options", "(", "self", ")", ":", "domain", "=", "self", ".", "get_domain", "(", ")", "for", "upper_value", "in", "self", ".", "upper", ":", "for", "suc", "in", "domain", ".", "successors", "(", "upper_value", ")", ":", "yield", "su...
Returns possible specializations for the upper values in the taxonomy
[ "Returns", "possible", "specializations", "for", "the", "upper", "values", "in", "the", "taxonomy" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L385-L390
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.get_relaxation_options
def get_relaxation_options(self): """ Returns possible generalizations for the upper values in the taxonomy """ domain = self.get_domain() for upper_value in self.upper: for suc in domain.predecessors(upper_value): yield suc
python
def get_relaxation_options(self): """ Returns possible generalizations for the upper values in the taxonomy """ domain = self.get_domain() for upper_value in self.upper: for suc in domain.predecessors(upper_value): yield suc
[ "def", "get_relaxation_options", "(", "self", ")", ":", "domain", "=", "self", ".", "get_domain", "(", ")", "for", "upper_value", "in", "self", ".", "upper", ":", "for", "suc", "in", "domain", ".", "predecessors", "(", "upper_value", ")", ":", "yield", "...
Returns possible generalizations for the upper values in the taxonomy
[ "Returns", "possible", "generalizations", "for", "the", "upper", "values", "in", "the", "taxonomy" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L392-L397
EventTeam/beliefs
src/beliefs/cells/posets.py
PartialOrderedCell.to_dotfile
def to_dotfile(self): """ Writes a DOT graphviz file of the domain structure, and returns the filename""" domain = self.get_domain() filename = "%s.dot" % (self.__class__.__name__) nx.write_dot(domain, filename) return filename
python
def to_dotfile(self): """ Writes a DOT graphviz file of the domain structure, and returns the filename""" domain = self.get_domain() filename = "%s.dot" % (self.__class__.__name__) nx.write_dot(domain, filename) return filename
[ "def", "to_dotfile", "(", "self", ")", ":", "domain", "=", "self", ".", "get_domain", "(", ")", "filename", "=", "\"%s.dot\"", "%", "(", "self", ".", "__class__", ".", "__name__", ")", "nx", ".", "write_dot", "(", "domain", ",", "filename", ")", "retur...
Writes a DOT graphviz file of the domain structure, and returns the filename
[ "Writes", "a", "DOT", "graphviz", "file", "of", "the", "domain", "structure", "and", "returns", "the", "filename" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L406-L411
alexhayes/django-toolkit
django_toolkit/views.py
error_handler_404
def error_handler_404(request): """ 500 error handler which includes ``request`` in the context. Templates: `500.html` Context: None """ from django.template import Context, loader from django.http import HttpResponseServerError t = loader.get_template('404.html') return HttpRespon...
python
def error_handler_404(request): """ 500 error handler which includes ``request`` in the context. Templates: `500.html` Context: None """ from django.template import Context, loader from django.http import HttpResponseServerError t = loader.get_template('404.html') return HttpRespon...
[ "def", "error_handler_404", "(", "request", ")", ":", "from", "django", ".", "template", "import", "Context", ",", "loader", "from", "django", ".", "http", "import", "HttpResponseServerError", "t", "=", "loader", ".", "get_template", "(", "'404.html'", ")", "r...
500 error handler which includes ``request`` in the context. Templates: `500.html` Context: None
[ "500", "error", "handler", "which", "includes", "request", "in", "the", "context", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/views.py#L32-L46
alexhayes/django-toolkit
django_toolkit/views.py
RedirectNextOrBackView.get_redirect_url
def get_redirect_url(self, **kwargs): """ Redirect to request parameter 'next' or to referrer if url is not defined. """ if self.request.REQUEST.has_key('next'): return self.request.REQUEST.get('next') url = RedirectView.get_redirect_url(self, **kwargs) if u...
python
def get_redirect_url(self, **kwargs): """ Redirect to request parameter 'next' or to referrer if url is not defined. """ if self.request.REQUEST.has_key('next'): return self.request.REQUEST.get('next') url = RedirectView.get_redirect_url(self, **kwargs) if u...
[ "def", "get_redirect_url", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "request", ".", "REQUEST", ".", "has_key", "(", "'next'", ")", ":", "return", "self", ".", "request", ".", "REQUEST", ".", "get", "(", "'next'", ")", "url",...
Redirect to request parameter 'next' or to referrer if url is not defined.
[ "Redirect", "to", "request", "parameter", "next", "or", "to", "referrer", "if", "url", "is", "not", "defined", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/views.py#L96-L105
alexhayes/django-toolkit
django_toolkit/views.py
FileDownloadView.render_to_response
def render_to_response(self, context=False): """Send file to client.""" f = self.openfile() wrapper = FileWrapper(f) response = HttpResponse(wrapper, content_type=self.content_type()) self.headers(response) return response
python
def render_to_response(self, context=False): """Send file to client.""" f = self.openfile() wrapper = FileWrapper(f) response = HttpResponse(wrapper, content_type=self.content_type()) self.headers(response) return response
[ "def", "render_to_response", "(", "self", ",", "context", "=", "False", ")", ":", "f", "=", "self", ".", "openfile", "(", ")", "wrapper", "=", "FileWrapper", "(", "f", ")", "response", "=", "HttpResponse", "(", "wrapper", ",", "content_type", "=", "self"...
Send file to client.
[ "Send", "file", "to", "client", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/views.py#L147-L153
alexhayes/django-toolkit
django_toolkit/views.py
FormAcceptsRequestMixin.get_form_kwargs
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = super(FormAcceptsRequestMixin, self).get_form_kwargs() if self.form_accepts_request: kwargs.update({'request': self.request}) return kwargs
python
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = super(FormAcceptsRequestMixin, self).get_form_kwargs() if self.form_accepts_request: kwargs.update({'request': self.request}) return kwargs
[ "def", "get_form_kwargs", "(", "self", ")", ":", "kwargs", "=", "super", "(", "FormAcceptsRequestMixin", ",", "self", ")", ".", "get_form_kwargs", "(", ")", "if", "self", ".", "form_accepts_request", ":", "kwargs", ".", "update", "(", "{", "'request'", ":", ...
Returns the keyword arguments for instantiating the form.
[ "Returns", "the", "keyword", "arguments", "for", "instantiating", "the", "form", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/views.py#L169-L176
alexhayes/django-toolkit
django_toolkit/views.py
AjaxMixin.render_to_response
def render_to_response(self, context, **response_kwargs): """ Returns a response, using the `response_class` for this view, with a template rendered with the given context. If any keyword arguments are provided, they will be passed to the constructor of the response class. ...
python
def render_to_response(self, context, **response_kwargs): """ Returns a response, using the `response_class` for this view, with a template rendered with the given context. If any keyword arguments are provided, they will be passed to the constructor of the response class. ...
[ "def", "render_to_response", "(", "self", ",", "context", ",", "*", "*", "response_kwargs", ")", ":", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "context", ",", "cls", "=", "JSON_ENCODER", ")", ",", "content_type", "=", "'application/json'", "...
Returns a response, using the `response_class` for this view, with a template rendered with the given context. If any keyword arguments are provided, they will be passed to the constructor of the response class.
[ "Returns", "a", "response", "using", "the", "response_class", "for", "this", "view", "with", "a", "template", "rendered", "with", "the", "given", "context", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/views.py#L246-L256
alexhayes/django-toolkit
django_toolkit/views.py
BaseDayView.get_date
def get_date(self): """ Return (date_list, items, extra_context) for this request. """ year = self.get_year() month = self.get_month() day = self.get_day() return _date_from_string(year, self.get_year_format(), month, self.get_mon...
python
def get_date(self): """ Return (date_list, items, extra_context) for this request. """ year = self.get_year() month = self.get_month() day = self.get_day() return _date_from_string(year, self.get_year_format(), month, self.get_mon...
[ "def", "get_date", "(", "self", ")", ":", "year", "=", "self", ".", "get_year", "(", ")", "month", "=", "self", ".", "get_month", "(", ")", "day", "=", "self", ".", "get_day", "(", ")", "return", "_date_from_string", "(", "year", ",", "self", ".", ...
Return (date_list, items, extra_context) for this request.
[ "Return", "(", "date_list", "items", "extra_context", ")", "for", "this", "request", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/views.py#L343-L353
openpermissions/perch
perch/user.py
User.clean
def clean(self): """Verified value is derived from whether user has a verification hash""" result = super(User, self).clean() result['verified'] = 'verification_hash' not in self._resource return result
python
def clean(self): """Verified value is derived from whether user has a verification hash""" result = super(User, self).clean() result['verified'] = 'verification_hash' not in self._resource return result
[ "def", "clean", "(", "self", ")", ":", "result", "=", "super", "(", "User", ",", "self", ")", ".", "clean", "(", ")", "result", "[", "'verified'", "]", "=", "'verification_hash'", "not", "in", "self", ".", "_resource", "return", "result" ]
Verified value is derived from whether user has a verification hash
[ "Verified", "value", "is", "derived", "from", "whether", "user", "has", "a", "verification", "hash" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L94-L98
openpermissions/perch
perch/user.py
User.check_unique
def check_unique(self): """Check the user's email is unique""" emails = yield self.view.values(key=self.email) user_id = getattr(self, 'id', None) users = {x for x in emails if x != user_id and x} if users: raise exceptions.ValidationError( "User with...
python
def check_unique(self): """Check the user's email is unique""" emails = yield self.view.values(key=self.email) user_id = getattr(self, 'id', None) users = {x for x in emails if x != user_id and x} if users: raise exceptions.ValidationError( "User with...
[ "def", "check_unique", "(", "self", ")", ":", "emails", "=", "yield", "self", ".", "view", ".", "values", "(", "key", "=", "self", ".", "email", ")", "user_id", "=", "getattr", "(", "self", ",", "'id'", ",", "None", ")", "users", "=", "{", "x", "...
Check the user's email is unique
[ "Check", "the", "user", "s", "email", "is", "unique" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L118-L126
openpermissions/perch
perch/user.py
User.create_admin
def create_admin(cls, email, password, **kwargs): """ Create an approved 'global' administrator :param email: the user's email address :param password: the user's plain text password :returns: a User """ data = { 'email': email, 'password'...
python
def create_admin(cls, email, password, **kwargs): """ Create an approved 'global' administrator :param email: the user's email address :param password: the user's plain text password :returns: a User """ data = { 'email': email, 'password'...
[ "def", "create_admin", "(", "cls", ",", "email", ",", "password", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'email'", ":", "email", ",", "'password'", ":", "cls", ".", "hash_password", "(", "password", ")", ",", "'has_agreed_to_terms'", ":", ...
Create an approved 'global' administrator :param email: the user's email address :param password: the user's plain text password :returns: a User
[ "Create", "an", "approved", "global", "administrator" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L141-L162
openpermissions/perch
perch/user.py
User.hash_password
def hash_password(plain_text): """Hash a plain text password""" # NOTE: despite the name this is a one-way hash not a reversible cypher hashed = pbkdf2_sha256.encrypt(plain_text, rounds=8000, salt_size=10) return unicode(hashed)
python
def hash_password(plain_text): """Hash a plain text password""" # NOTE: despite the name this is a one-way hash not a reversible cypher hashed = pbkdf2_sha256.encrypt(plain_text, rounds=8000, salt_size=10) return unicode(hashed)
[ "def", "hash_password", "(", "plain_text", ")", ":", "# NOTE: despite the name this is a one-way hash not a reversible cypher", "hashed", "=", "pbkdf2_sha256", ".", "encrypt", "(", "plain_text", ",", "rounds", "=", "8000", ",", "salt_size", "=", "10", ")", "return", "...
Hash a plain text password
[ "Hash", "a", "plain", "text", "password" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L165-L169
openpermissions/perch
perch/user.py
User.change_password
def change_password(self, previous, new_password): """ Change the user's password and save to the database :param previous: plain text previous password :param new_password: plain text new password :raises: ValidationError """ if not self.verify_password(previous...
python
def change_password(self, previous, new_password): """ Change the user's password and save to the database :param previous: plain text previous password :param new_password: plain text new password :raises: ValidationError """ if not self.verify_password(previous...
[ "def", "change_password", "(", "self", ",", "previous", ",", "new_password", ")", ":", "if", "not", "self", ".", "verify_password", "(", "previous", ")", ":", "raise", "exceptions", ".", "Unauthorized", "(", "'Incorrect password'", ")", "if", "len", "(", "ne...
Change the user's password and save to the database :param previous: plain text previous password :param new_password: plain text new password :raises: ValidationError
[ "Change", "the", "user", "s", "password", "and", "save", "to", "the", "database" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L176-L198
openpermissions/perch
perch/user.py
User.login
def login(cls, email, password): """ Log in a user :param email: the user's email address :param password: the user's password :returns: (User, token) :raises: SocketError, CouchException """ try: doc = yield cls.view.first(key=email, include_...
python
def login(cls, email, password): """ Log in a user :param email: the user's email address :param password: the user's password :returns: (User, token) :raises: SocketError, CouchException """ try: doc = yield cls.view.first(key=email, include_...
[ "def", "login", "(", "cls", ",", "email", ",", "password", ")", ":", "try", ":", "doc", "=", "yield", "cls", ".", "view", ".", "first", "(", "key", "=", "email", ",", "include_docs", "=", "True", ")", "except", "couch", ".", "NotFound", ":", "raise...
Log in a user :param email: the user's email address :param password: the user's password :returns: (User, token) :raises: SocketError, CouchException
[ "Log", "in", "a", "user" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L202-L223
openpermissions/perch
perch/user.py
User.verify
def verify(cls, user_id, verification_hash): """ Verify a user using the verification hash The verification hash is removed from the user once verified :param user_id: the user ID :param verification_hash: the verification hash :returns: a User instance """ ...
python
def verify(cls, user_id, verification_hash): """ Verify a user using the verification hash The verification hash is removed from the user once verified :param user_id: the user ID :param verification_hash: the verification hash :returns: a User instance """ ...
[ "def", "verify", "(", "cls", ",", "user_id", ",", "verification_hash", ")", ":", "user", "=", "yield", "cls", ".", "get", "(", "user_id", ")", "# If user does not have verification hash then this means they have already been verified", "if", "'verification_hash'", "not", ...
Verify a user using the verification hash The verification hash is removed from the user once verified :param user_id: the user ID :param verification_hash: the verification hash :returns: a User instance
[ "Verify", "a", "user", "using", "the", "verification", "hash" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L227-L249
openpermissions/perch
perch/user.py
User.is_admin
def is_admin(self): """Is the user a system administrator""" return self.role == self.roles.administrator.value and self.state == State.approved
python
def is_admin(self): """Is the user a system administrator""" return self.role == self.roles.administrator.value and self.state == State.approved
[ "def", "is_admin", "(", "self", ")", ":", "return", "self", ".", "role", "==", "self", ".", "roles", ".", "administrator", ".", "value", "and", "self", ".", "state", "==", "State", ".", "approved" ]
Is the user a system administrator
[ "Is", "the", "user", "a", "system", "administrator" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L251-L253
openpermissions/perch
perch/user.py
User.is_reseller
def is_reseller(self): """is the user a reseller""" return self.role == self.roles.reseller.value and self.state == State.approved
python
def is_reseller(self): """is the user a reseller""" return self.role == self.roles.reseller.value and self.state == State.approved
[ "def", "is_reseller", "(", "self", ")", ":", "return", "self", ".", "role", "==", "self", ".", "roles", ".", "reseller", ".", "value", "and", "self", ".", "state", "==", "State", ".", "approved" ]
is the user a reseller
[ "is", "the", "user", "a", "reseller" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L255-L257
openpermissions/perch
perch/user.py
User.is_org_admin
def is_org_admin(self, organisation_id): """Is the user authorized to administrate the organisation""" return (self._has_role(organisation_id, self.roles.administrator) or self.is_admin())
python
def is_org_admin(self, organisation_id): """Is the user authorized to administrate the organisation""" return (self._has_role(organisation_id, self.roles.administrator) or self.is_admin())
[ "def", "is_org_admin", "(", "self", ",", "organisation_id", ")", ":", "return", "(", "self", ".", "_has_role", "(", "organisation_id", ",", "self", ".", "roles", ".", "administrator", ")", "or", "self", ".", "is_admin", "(", ")", ")" ]
Is the user authorized to administrate the organisation
[ "Is", "the", "user", "authorized", "to", "administrate", "the", "organisation" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L259-L262
openpermissions/perch
perch/user.py
User.is_user
def is_user(self, organisation_id): """Is the user valid and approved in this organisation""" return (self._has_role(organisation_id, self.roles.user) or self.is_org_admin(organisation_id))
python
def is_user(self, organisation_id): """Is the user valid and approved in this organisation""" return (self._has_role(organisation_id, self.roles.user) or self.is_org_admin(organisation_id))
[ "def", "is_user", "(", "self", ",", "organisation_id", ")", ":", "return", "(", "self", ".", "_has_role", "(", "organisation_id", ",", "self", ".", "roles", ".", "user", ")", "or", "self", ".", "is_org_admin", "(", "organisation_id", ")", ")" ]
Is the user valid and approved in this organisation
[ "Is", "the", "user", "valid", "and", "approved", "in", "this", "organisation" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L264-L267
openpermissions/perch
perch/user.py
User._has_role
def _has_role(self, organisation_id, role): """Check the user's role for the organisation""" if organisation_id is None: return False try: org = self.organisations.get(organisation_id, {}) user_role = org.get('role') state = org.get('state') ...
python
def _has_role(self, organisation_id, role): """Check the user's role for the organisation""" if organisation_id is None: return False try: org = self.organisations.get(organisation_id, {}) user_role = org.get('role') state = org.get('state') ...
[ "def", "_has_role", "(", "self", ",", "organisation_id", ",", "role", ")", ":", "if", "organisation_id", "is", "None", ":", "return", "False", "try", ":", "org", "=", "self", ".", "organisations", ".", "get", "(", "organisation_id", ",", "{", "}", ")", ...
Check the user's role for the organisation
[ "Check", "the", "user", "s", "role", "for", "the", "organisation" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L269-L281
openpermissions/perch
perch/user.py
User.remove_organisation_from_all
def remove_organisation_from_all(cls, organisation_id): """Remove an organisation from all users""" users = yield views.organisation_members.get(key=organisation_id, include_docs=True) users = [x['doc'] for x in users['rows']] for user...
python
def remove_organisation_from_all(cls, organisation_id): """Remove an organisation from all users""" users = yield views.organisation_members.get(key=organisation_id, include_docs=True) users = [x['doc'] for x in users['rows']] for user...
[ "def", "remove_organisation_from_all", "(", "cls", ",", "organisation_id", ")", ":", "users", "=", "yield", "views", ".", "organisation_members", ".", "get", "(", "key", "=", "organisation_id", ",", "include_docs", "=", "True", ")", "users", "=", "[", "x", "...
Remove an organisation from all users
[ "Remove", "an", "organisation", "from", "all", "users" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L285-L294
openpermissions/perch
perch/user.py
Token.valid
def valid(cls, token, **kwargs): """ Check if a token exists and has not expired :param token: the token :return: bool """ try: token = yield cls.get(token) except couch.NotFound: raise Return(False) raise Return(token.ttl >= date...
python
def valid(cls, token, **kwargs): """ Check if a token exists and has not expired :param token: the token :return: bool """ try: token = yield cls.get(token) except couch.NotFound: raise Return(False) raise Return(token.ttl >= date...
[ "def", "valid", "(", "cls", ",", "token", ",", "*", "*", "kwargs", ")", ":", "try", ":", "token", "=", "yield", "cls", ".", "get", "(", "token", ")", "except", "couch", ".", "NotFound", ":", "raise", "Return", "(", "False", ")", "raise", "Return", ...
Check if a token exists and has not expired :param token: the token :return: bool
[ "Check", "if", "a", "token", "exists", "and", "has", "not", "expired" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L320-L332
openpermissions/perch
perch/user.py
UserOrganisation.can_approve
def can_approve(self, user, **data): """ Only org admins can approve joining an organisation :param user: a User :param data: data that the user wants to update """ is_org_admin = user.is_org_admin(self.organisation_id) is_reseller_preverifying = user.is_reseller...
python
def can_approve(self, user, **data): """ Only org admins can approve joining an organisation :param user: a User :param data: data that the user wants to update """ is_org_admin = user.is_org_admin(self.organisation_id) is_reseller_preverifying = user.is_reseller...
[ "def", "can_approve", "(", "self", ",", "user", ",", "*", "*", "data", ")", ":", "is_org_admin", "=", "user", ".", "is_org_admin", "(", "self", ".", "organisation_id", ")", "is_reseller_preverifying", "=", "user", ".", "is_reseller", "(", ")", "and", "data...
Only org admins can approve joining an organisation :param user: a User :param data: data that the user wants to update
[ "Only", "org", "admins", "can", "approve", "joining", "an", "organisation", ":", "param", "user", ":", "a", "User", ":", "param", "data", ":", "data", "that", "the", "user", "wants", "to", "update" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/user.py#L357-L367
stevepeak/inquiry
inquiry/garden.py
Garden.plant
def plant(self, *seeds, **arguments): """Applys seeds and arguments to the garden for use during the harvest """ map(self._clean, seeds) self.network_kwargs.update(arguments)
python
def plant(self, *seeds, **arguments): """Applys seeds and arguments to the garden for use during the harvest """ map(self._clean, seeds) self.network_kwargs.update(arguments)
[ "def", "plant", "(", "self", ",", "*", "seeds", ",", "*", "*", "arguments", ")", ":", "map", "(", "self", ".", "_clean", ",", "seeds", ")", "self", ".", "network_kwargs", ".", "update", "(", "arguments", ")" ]
Applys seeds and arguments to the garden for use during the harvest
[ "Applys", "seeds", "and", "arguments", "to", "the", "garden", "for", "use", "during", "the", "harvest" ]
train
https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/garden.py#L85-L90
stevepeak/inquiry
inquiry/garden.py
Garden._harvest_validate
def _harvest_validate(self, userkwargs): """Validate and Plant user provided arguments - Go through and plants the seedlings for any user arguments provided. - Validate the arguments, cleaning and adapting (valideer wise) - Extract negatives "!" arguments """ # ...
python
def _harvest_validate(self, userkwargs): """Validate and Plant user provided arguments - Go through and plants the seedlings for any user arguments provided. - Validate the arguments, cleaning and adapting (valideer wise) - Extract negatives "!" arguments """ # ...
[ "def", "_harvest_validate", "(", "self", ",", "userkwargs", ")", ":", "# the valideer to parse the", "# user arguemnts when watering", "parser", "=", "{", "}", "userkwargs", ".", "update", "(", "self", ".", "network_kwargs", ")", "# a simple set of original provided argum...
Validate and Plant user provided arguments - Go through and plants the seedlings for any user arguments provided. - Validate the arguments, cleaning and adapting (valideer wise) - Extract negatives "!" arguments
[ "Validate", "and", "Plant", "user", "provided", "arguments", "-", "Go", "through", "and", "plants", "the", "seedlings", "for", "any", "user", "arguments", "provided", ".", "-", "Validate", "the", "arguments", "cleaning", "and", "adapting", "(", "valideer", "wi...
train
https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/garden.py#L98-L256
stevepeak/inquiry
inquiry/garden.py
Garden._clean
def _clean(self, seed): """Takes a seed and applies it to the garden """ seed = deepcopy(seed) # inherit any other figures self._inherit(*array(get(seed, 'inherit', []))) # merge the seed arguments if '&arguments' in seed: self.arguments = merge(self.a...
python
def _clean(self, seed): """Takes a seed and applies it to the garden """ seed = deepcopy(seed) # inherit any other figures self._inherit(*array(get(seed, 'inherit', []))) # merge the seed arguments if '&arguments' in seed: self.arguments = merge(self.a...
[ "def", "_clean", "(", "self", ",", "seed", ")", ":", "seed", "=", "deepcopy", "(", "seed", ")", "# inherit any other figures", "self", ".", "_inherit", "(", "*", "array", "(", "get", "(", "seed", ",", "'inherit'", ",", "[", "]", ")", ")", ")", "# mer...
Takes a seed and applies it to the garden
[ "Takes", "a", "seed", "and", "applies", "it", "to", "the", "garden" ]
train
https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/garden.py#L524-L537
udoprog/mimeprovider
mimeprovider/__init__.py
MimeProvider._generate_base_mimetypes
def _generate_base_mimetypes(self): """ Generate the base mimetypes as described by non customized document types. """ for t in self.type_instances: if t.custom_mime: continue yield t.mime, (t, None, None)
python
def _generate_base_mimetypes(self): """ Generate the base mimetypes as described by non customized document types. """ for t in self.type_instances: if t.custom_mime: continue yield t.mime, (t, None, None)
[ "def", "_generate_base_mimetypes", "(", "self", ")", ":", "for", "t", "in", "self", ".", "type_instances", ":", "if", "t", ".", "custom_mime", ":", "continue", "yield", "t", ".", "mime", ",", "(", "t", ",", "None", ",", "None", ")" ]
Generate the base mimetypes as described by non customized document types.
[ "Generate", "the", "base", "mimetypes", "as", "described", "by", "non", "customized", "document", "types", "." ]
train
https://github.com/udoprog/mimeprovider/blob/5acd61eb0ef813b4a2eb6bbe75d07af1e11847a4/mimeprovider/__init__.py#L80-L89
ulf1/oxyba
oxyba/crossvalidation_stats.py
crossvalidation_stats
def crossvalidation_stats(errors1, errors2): """Paired difference test of the CV errors of two models Parameters: ----------- errors1 : ndarray The CV errors model 1 errors2 : ndarray The CV errors model 2 Returns: -------- pvalue : float Two-sided P-value ...
python
def crossvalidation_stats(errors1, errors2): """Paired difference test of the CV errors of two models Parameters: ----------- errors1 : ndarray The CV errors model 1 errors2 : ndarray The CV errors model 2 Returns: -------- pvalue : float Two-sided P-value ...
[ "def", "crossvalidation_stats", "(", "errors1", ",", "errors2", ")", ":", "# load modules", "import", "numpy", "as", "np", "import", "scipy", ".", "stats", "import", "warnings", "# Number of blocks", "K", "=", "errors1", ".", "shape", "[", "0", "]", "# display...
Paired difference test of the CV errors of two models Parameters: ----------- errors1 : ndarray The CV errors model 1 errors2 : ndarray The CV errors model 2 Returns: -------- pvalue : float Two-sided P-value if the differences between err1 and err2 are...
[ "Paired", "difference", "test", "of", "the", "CV", "errors", "of", "two", "models" ]
train
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/crossvalidation_stats.py#L2-L62
ulf1/oxyba
oxyba/crossvalidation_stats.py
crossvalidation_error
def crossvalidation_error(errors): """Crossvalidation Errors""" import numpy as np return np.mean(errors), np.std(errors)
python
def crossvalidation_error(errors): """Crossvalidation Errors""" import numpy as np return np.mean(errors), np.std(errors)
[ "def", "crossvalidation_error", "(", "errors", ")", ":", "import", "numpy", "as", "np", "return", "np", ".", "mean", "(", "errors", ")", ",", "np", ".", "std", "(", "errors", ")" ]
Crossvalidation Errors
[ "Crossvalidation", "Errors" ]
train
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/crossvalidation_stats.py#L65-L68
jmgilman/Neolib
neolib/pyamf/remoting/gateway/wsgi.py
WSGIGateway.badRequestMethod
def badRequestMethod(self, environ, start_response): """ Return HTTP 400 Bad Request. """ response = "400 Bad Request\n\nTo access this PyAMF gateway you " \ "must use POST requests (%s received)" % environ['REQUEST_METHOD'] start_response('400 Bad Request', [ ...
python
def badRequestMethod(self, environ, start_response): """ Return HTTP 400 Bad Request. """ response = "400 Bad Request\n\nTo access this PyAMF gateway you " \ "must use POST requests (%s received)" % environ['REQUEST_METHOD'] start_response('400 Bad Request', [ ...
[ "def", "badRequestMethod", "(", "self", ",", "environ", ",", "start_response", ")", ":", "response", "=", "\"400 Bad Request\\n\\nTo access this PyAMF gateway you \"", "\"must use POST requests (%s received)\"", "%", "environ", "[", "'REQUEST_METHOD'", "]", "start_response", ...
Return HTTP 400 Bad Request.
[ "Return", "HTTP", "400", "Bad", "Request", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/gateway/wsgi.py#L55-L68
dcolish/Refugee
refugee/manager.py
MigrationManager.collect
def collect(self): """ Walks self.migration_home and load all potential migration modules """ for root, dirname, files in walk(self.migration_home): for file_name in file_filter(files, "*.py"): file_name = file_name.replace('.py', '') file = No...
python
def collect(self): """ Walks self.migration_home and load all potential migration modules """ for root, dirname, files in walk(self.migration_home): for file_name in file_filter(files, "*.py"): file_name = file_name.replace('.py', '') file = No...
[ "def", "collect", "(", "self", ")", ":", "for", "root", ",", "dirname", ",", "files", "in", "walk", "(", "self", ".", "migration_home", ")", ":", "for", "file_name", "in", "file_filter", "(", "files", ",", "\"*.py\"", ")", ":", "file_name", "=", "file_...
Walks self.migration_home and load all potential migration modules
[ "Walks", "self", ".", "migration_home", "and", "load", "all", "potential", "migration", "modules" ]
train
https://github.com/dcolish/Refugee/blob/b98391cb3127d09b15b59c7c25dab07a968062fa/refugee/manager.py#L55-L71
dcolish/Refugee
refugee/manager.py
MigrationManager.new
def new(self, name): """ Build a stub migration with name + auto-id in config['migration_home'] There is no guarantee this id will be unique for all remote migration configurations. Conflicts will require manual management. """ #XXX:dc: assert that the name is somewhat s...
python
def new(self, name): """ Build a stub migration with name + auto-id in config['migration_home'] There is no guarantee this id will be unique for all remote migration configurations. Conflicts will require manual management. """ #XXX:dc: assert that the name is somewhat s...
[ "def", "new", "(", "self", ",", "name", ")", ":", "#XXX:dc: assert that the name is somewhat sane and follows python", "# naming conventions", "next_id", "=", "0", "cls_name", "=", "'_'", ".", "join", "(", "(", "name", ",", "next_id", ")", ")", "with", "open", "...
Build a stub migration with name + auto-id in config['migration_home'] There is no guarantee this id will be unique for all remote migration configurations. Conflicts will require manual management.
[ "Build", "a", "stub", "migration", "with", "name", "+", "auto", "-", "id", "in", "config", "[", "migration_home", "]" ]
train
https://github.com/dcolish/Refugee/blob/b98391cb3127d09b15b59c7c25dab07a968062fa/refugee/manager.py#L78-L91
dcolish/Refugee
refugee/manager.py
MigrationManager.init
def init(self, directory): """ Drops the essential goods for running migrations into a given directory. Really any directory and config file could be used. For now the default layout will be:: directory/ __init__.py refugee.ini ...
python
def init(self, directory): """ Drops the essential goods for running migrations into a given directory. Really any directory and config file could be used. For now the default layout will be:: directory/ __init__.py refugee.ini ...
[ "def", "init", "(", "self", ",", "directory", ")", ":", "#XXX:dc: are these good defaults?", "path", "=", "pjoin", "(", "directory", ",", "'migrations'", ")", "makedirs", "(", "path", ")", "with", "open", "(", "pjoin", "(", "directory", ",", "'refugee.ini'", ...
Drops the essential goods for running migrations into a given directory. Really any directory and config file could be used. For now the default layout will be:: directory/ __init__.py refugee.ini migrations/ __init__.py ...
[ "Drops", "the", "essential", "goods", "for", "running", "migrations", "into", "a", "given", "directory", ".", "Really", "any", "directory", "and", "config", "file", "could", "be", "used", ".", "For", "now", "the", "default", "layout", "will", "be", "::" ]
train
https://github.com/dcolish/Refugee/blob/b98391cb3127d09b15b59c7c25dab07a968062fa/refugee/manager.py#L93-L112
dcolish/Refugee
refugee/manager.py
MigrationManager.run_all
def run_all(self, direction): """ Runs all registered migrations :param direction: Can be on of two values, UP or DOWN """ for key in sorted(migration_registry.keys): self.run(key, direction)
python
def run_all(self, direction): """ Runs all registered migrations :param direction: Can be on of two values, UP or DOWN """ for key in sorted(migration_registry.keys): self.run(key, direction)
[ "def", "run_all", "(", "self", ",", "direction", ")", ":", "for", "key", "in", "sorted", "(", "migration_registry", ".", "keys", ")", ":", "self", ".", "run", "(", "key", ",", "direction", ")" ]
Runs all registered migrations :param direction: Can be on of two values, UP or DOWN
[ "Runs", "all", "registered", "migrations" ]
train
https://github.com/dcolish/Refugee/blob/b98391cb3127d09b15b59c7c25dab07a968062fa/refugee/manager.py#L120-L127
dcolish/Refugee
refugee/manager.py
MigrationManager.run
def run(self, migration_name, direction): """ Asserts an engine is configured and runs the registered migration in the given direction :param migration_name: key to a registered class in the `migration_registry` :param direction: Can be on of two ...
python
def run(self, migration_name, direction): """ Asserts an engine is configured and runs the registered migration in the given direction :param migration_name: key to a registered class in the `migration_registry` :param direction: Can be on of two ...
[ "def", "run", "(", "self", ",", "migration_name", ",", "direction", ")", ":", "if", "not", "self", ".", "engine", ":", "raise", "AttributeError", "(", "\"No engine configured for MigrationManager\"", ")", "connection", "=", "self", ".", "engine", ".", "connect",...
Asserts an engine is configured and runs the registered migration in the given direction :param migration_name: key to a registered class in the `migration_registry` :param direction: Can be on of two values, UP or DOWN
[ "Asserts", "an", "engine", "is", "configured", "and", "runs", "the", "registered", "migration", "in", "the", "given", "direction" ]
train
https://github.com/dcolish/Refugee/blob/b98391cb3127d09b15b59c7c25dab07a968062fa/refugee/manager.py#L129-L163
nivardus/kclboot
kclboot/maven_jar.py
MavenJar.maven_url
def maven_url(self): ''' Download-URL from Maven ''' return '{prefix}/{path}/{artifact}/{version}/{filename}'.format( prefix = MAVEN_PREFIX, path = '/'.join(self.group.split('.')), artifact = self.artifact, version = self.version, ...
python
def maven_url(self): ''' Download-URL from Maven ''' return '{prefix}/{path}/{artifact}/{version}/{filename}'.format( prefix = MAVEN_PREFIX, path = '/'.join(self.group.split('.')), artifact = self.artifact, version = self.version, ...
[ "def", "maven_url", "(", "self", ")", ":", "return", "'{prefix}/{path}/{artifact}/{version}/{filename}'", ".", "format", "(", "prefix", "=", "MAVEN_PREFIX", ",", "path", "=", "'/'", ".", "join", "(", "self", ".", "group", ".", "split", "(", "'.'", ")", ")", ...
Download-URL from Maven
[ "Download", "-", "URL", "from", "Maven" ]
train
https://github.com/nivardus/kclboot/blob/aee054d9186938bec51f19e9ed8deed6ac6fe492/kclboot/maven_jar.py#L28-L37
nivardus/kclboot
kclboot/maven_jar.py
MavenJar.download_to
def download_to(self, folder): ''' Download into a folder ''' urlretrieve(self.maven_url, os.path.join(folder, self.filename))
python
def download_to(self, folder): ''' Download into a folder ''' urlretrieve(self.maven_url, os.path.join(folder, self.filename))
[ "def", "download_to", "(", "self", ",", "folder", ")", ":", "urlretrieve", "(", "self", ".", "maven_url", ",", "os", ".", "path", ".", "join", "(", "folder", ",", "self", ".", "filename", ")", ")" ]
Download into a folder
[ "Download", "into", "a", "folder" ]
train
https://github.com/nivardus/kclboot/blob/aee054d9186938bec51f19e9ed8deed6ac6fe492/kclboot/maven_jar.py#L39-L43
insilicolife/micti
MICTI/radarPlot.py
radar_factory
def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surr...
python
def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surr...
[ "def", "radar_factory", "(", "num_vars", ",", "frame", "=", "'circle'", ")", ":", "# calculate evenly-spaced axis angles", "theta", "=", "np", ".", "linspace", "(", "0", ",", "2", "*", "np", ".", "pi", ",", "num_vars", ",", "endpoint", "=", "False", ")", ...
Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surrounding axes.
[ "Create", "a", "radar", "chart", "with", "num_vars", "axes", "." ]
train
https://github.com/insilicolife/micti/blob/f12f46724295b57c4859e6acf7eab580fc355eb1/MICTI/radarPlot.py#L9-L90
insilicolife/micti
MICTI/radarPlot.py
unit_poly_verts
def unit_poly_verts(theta): """Return vertices of polygon for subplot axes. This polygon is circumscribed by a unit circle centered at (0.5, 0.5) """ x0, y0, r = [0.5] * 3 verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] return verts
python
def unit_poly_verts(theta): """Return vertices of polygon for subplot axes. This polygon is circumscribed by a unit circle centered at (0.5, 0.5) """ x0, y0, r = [0.5] * 3 verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] return verts
[ "def", "unit_poly_verts", "(", "theta", ")", ":", "x0", ",", "y0", ",", "r", "=", "[", "0.5", "]", "*", "3", "verts", "=", "[", "(", "r", "*", "np", ".", "cos", "(", "t", ")", "+", "x0", ",", "r", "*", "np", ".", "sin", "(", "t", ")", "...
Return vertices of polygon for subplot axes. This polygon is circumscribed by a unit circle centered at (0.5, 0.5)
[ "Return", "vertices", "of", "polygon", "for", "subplot", "axes", "." ]
train
https://github.com/insilicolife/micti/blob/f12f46724295b57c4859e6acf7eab580fc355eb1/MICTI/radarPlot.py#L93-L100
alfred82santa/dirty-loader
dirty_loader/factories.py
register_logging_factories
def register_logging_factories(loader): """ Registers default factories for logging standard package. :param loader: Loader where you want register default logging factories """ loader.register_factory(logging.Logger, LoggerFactory) loader.register_factory(logging.Handler, LoggingHandlerFactory...
python
def register_logging_factories(loader): """ Registers default factories for logging standard package. :param loader: Loader where you want register default logging factories """ loader.register_factory(logging.Logger, LoggerFactory) loader.register_factory(logging.Handler, LoggingHandlerFactory...
[ "def", "register_logging_factories", "(", "loader", ")", ":", "loader", ".", "register_factory", "(", "logging", ".", "Logger", ",", "LoggerFactory", ")", "loader", ".", "register_factory", "(", "logging", ".", "Handler", ",", "LoggingHandlerFactory", ")" ]
Registers default factories for logging standard package. :param loader: Loader where you want register default logging factories
[ "Registers", "default", "factories", "for", "logging", "standard", "package", "." ]
train
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/factories.py#L91-L98
lehins/python-wepay
wepay/calls/preapproval.py
Preapproval.__create
def __create(self, short_description, period, **kwargs): """Call documentation: `/preapproval/create <https://www.wepay.com/developer/reference/preapproval#create>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``...
python
def __create(self, short_description, period, **kwargs): """Call documentation: `/preapproval/create <https://www.wepay.com/developer/reference/preapproval#create>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``...
[ "def", "__create", "(", "self", ",", "short_description", ",", "period", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'short_description'", ":", "short_description", ",", "'period'", ":", "period", "}", "return", "self", ".", "make_call", "(", "...
Call documentation: `/preapproval/create <https://www.wepay.com/developer/reference/preapproval#create>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` param...
[ "Call", "documentation", ":", "/", "preapproval", "/", "create", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "preapproval#create", ">", "_", "plus", "extra", "keyword", "parameters", ":" ]
train
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/preapproval.py#L61-L84
lehins/python-wepay
wepay/calls/preapproval.py
Preapproval.__cancel
def __cancel(self, preapproval_id, **kwargs): """Call documentation: `/preapproval/cancel <https://www.wepay.com/developer/reference/preapproval#cancel>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``ba...
python
def __cancel(self, preapproval_id, **kwargs): """Call documentation: `/preapproval/cancel <https://www.wepay.com/developer/reference/preapproval#cancel>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``ba...
[ "def", "__cancel", "(", "self", ",", "preapproval_id", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'preapproval_id'", ":", "preapproval_id", "}", "return", "self", ".", "make_call", "(", "self", ".", "__cancel", ",", "params", ",", "kwargs", ...
Call documentation: `/preapproval/cancel <https://www.wepay.com/developer/reference/preapproval#cancel>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` param...
[ "Call", "documentation", ":", "/", "preapproval", "/", "cancel", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "preapproval#cancel", ">", "_", "plus", "extra", "keyword", "parameters", ":" ]
train
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/preapproval.py#L99-L121
lehins/python-wepay
wepay/calls/preapproval.py
Preapproval.__modify
def __modify(self, preapproval_id, **kwargs): """Call documentation: `/preapproval/modify <https://www.wepay.com/developer/reference/preapproval#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``ba...
python
def __modify(self, preapproval_id, **kwargs): """Call documentation: `/preapproval/modify <https://www.wepay.com/developer/reference/preapproval#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``ba...
[ "def", "__modify", "(", "self", ",", "preapproval_id", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'preapproval_id'", ":", "preapproval_id", "}", "return", "self", ".", "make_call", "(", "self", ".", "__modify", ",", "params", ",", "kwargs", ...
Call documentation: `/preapproval/modify <https://www.wepay.com/developer/reference/preapproval#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` param...
[ "Call", "documentation", ":", "/", "preapproval", "/", "modify", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "preapproval#modify", ">", "_", "plus", "extra", "keyword", "parameters", ":" ]
train
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/preapproval.py#L125-L147
w1ll1am23/pubnubsub-handler
pubnubsubhandler.py
PubNubSubscriptionHandler.add_subscription
def add_subscription(self, channel, callback_function): """ Add a channel to subscribe to and a callback function to run when the channel receives an update. If channel already exists, create a new "subscription" and append another callback function. Args: ch...
python
def add_subscription(self, channel, callback_function): """ Add a channel to subscribe to and a callback function to run when the channel receives an update. If channel already exists, create a new "subscription" and append another callback function. Args: ch...
[ "def", "add_subscription", "(", "self", ",", "channel", ",", "callback_function", ")", ":", "if", "channel", "not", "in", "CHANNELS", ":", "CHANNELS", ".", "append", "(", "channel", ")", "SUBSCRIPTIONS", "[", "channel", "]", "=", "[", "callback_function", "]...
Add a channel to subscribe to and a callback function to run when the channel receives an update. If channel already exists, create a new "subscription" and append another callback function. Args: channel (str): The channel to add a subscription too. callback_fun...
[ "Add", "a", "channel", "to", "subscribe", "to", "and", "a", "callback", "function", "to", "run", "when", "the", "channel", "receives", "an", "update", ".", "If", "channel", "already", "exists", "create", "a", "new", "subscription", "and", "append", "another"...
train
https://github.com/w1ll1am23/pubnubsub-handler/blob/0283c191d6042727f55a748f69a485d751f4cacb/pubnubsubhandler.py#L56-L77
w1ll1am23/pubnubsub-handler
pubnubsubhandler.py
PubNubSubscriptionHandler._run_keep_alive
def _run_keep_alive(self): """ Start a new thread timer to keep the keep_alive_function running every keep_alive seconds. """ threading.Timer(self._keep_alive, self._run_keep_alive).start() _LOGGER.info("Polling the API") # This may or may not return something ...
python
def _run_keep_alive(self): """ Start a new thread timer to keep the keep_alive_function running every keep_alive seconds. """ threading.Timer(self._keep_alive, self._run_keep_alive).start() _LOGGER.info("Polling the API") # This may or may not return something ...
[ "def", "_run_keep_alive", "(", "self", ")", ":", "threading", ".", "Timer", "(", "self", ".", "_keep_alive", ",", "self", ".", "_run_keep_alive", ")", ".", "start", "(", ")", "_LOGGER", ".", "info", "(", "\"Polling the API\"", ")", "# This may or may not retur...
Start a new thread timer to keep the keep_alive_function running every keep_alive seconds.
[ "Start", "a", "new", "thread", "timer", "to", "keep", "the", "keep_alive_function", "running", "every", "keep_alive", "seconds", "." ]
train
https://github.com/w1ll1am23/pubnubsub-handler/blob/0283c191d6042727f55a748f69a485d751f4cacb/pubnubsubhandler.py#L87-L95
w1ll1am23/pubnubsub-handler
pubnubsubhandler.py
PubNubSubscriptionHandler.unsubscribe
def unsubscribe(self): """ Completly stop all pubnub operations. """ _LOGGER.info("PubNub unsubscribing") self._pubnub.unsubscribe_all() self._pubnub.stop() self._pubnub = None
python
def unsubscribe(self): """ Completly stop all pubnub operations. """ _LOGGER.info("PubNub unsubscribing") self._pubnub.unsubscribe_all() self._pubnub.stop() self._pubnub = None
[ "def", "unsubscribe", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"PubNub unsubscribing\"", ")", "self", ".", "_pubnub", ".", "unsubscribe_all", "(", ")", "self", ".", "_pubnub", ".", "stop", "(", ")", "self", ".", "_pubnub", "=", "None" ]
Completly stop all pubnub operations.
[ "Completly", "stop", "all", "pubnub", "operations", "." ]
train
https://github.com/w1ll1am23/pubnubsub-handler/blob/0283c191d6042727f55a748f69a485d751f4cacb/pubnubsubhandler.py#L97-L104
w1ll1am23/pubnubsub-handler
pubnubsubhandler.py
PubNubSubscriptionHandler._subscribe
def _subscribe(self): """ Start the subscription to the channel list. If self._keep_alive_function isn't None start timer thread to run self._keep_alive_function every self._keep_alive amount of seconds. """ _LOGGER.info("PubNub subscribing") self._pubnub.subscrib...
python
def _subscribe(self): """ Start the subscription to the channel list. If self._keep_alive_function isn't None start timer thread to run self._keep_alive_function every self._keep_alive amount of seconds. """ _LOGGER.info("PubNub subscribing") self._pubnub.subscrib...
[ "def", "_subscribe", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"PubNub subscribing\"", ")", "self", ".", "_pubnub", ".", "subscribe", "(", ")", ".", "channels", "(", "CHANNELS", ")", ".", "execute", "(", ")", "if", "self", ".", "_keep_alive_f...
Start the subscription to the channel list. If self._keep_alive_function isn't None start timer thread to run self._keep_alive_function every self._keep_alive amount of seconds.
[ "Start", "the", "subscription", "to", "the", "channel", "list", ".", "If", "self", ".", "_keep_alive_function", "isn", "t", "None", "start", "timer", "thread", "to", "run", "self", ".", "_keep_alive_function", "every", "self", ".", "_keep_alive", "amount", "of...
train
https://github.com/w1ll1am23/pubnubsub-handler/blob/0283c191d6042727f55a748f69a485d751f4cacb/pubnubsubhandler.py#L106-L116
w1ll1am23/pubnubsub-handler
pubnubsubhandler.py
PubNubSubCallback.status
def status(self, pubnub, status): """ Things to do on different status updates. """ if status.operation == PNOperationType.PNSubscribeOperation \ or status.operation == PNOperationType.PNUnsubscribeOperation: if status.category == PNStatusCategory.PNConnectedCateg...
python
def status(self, pubnub, status): """ Things to do on different status updates. """ if status.operation == PNOperationType.PNSubscribeOperation \ or status.operation == PNOperationType.PNUnsubscribeOperation: if status.category == PNStatusCategory.PNConnectedCateg...
[ "def", "status", "(", "self", ",", "pubnub", ",", "status", ")", ":", "if", "status", ".", "operation", "==", "PNOperationType", ".", "PNSubscribeOperation", "or", "status", ".", "operation", "==", "PNOperationType", ".", "PNUnsubscribeOperation", ":", "if", "...
Things to do on different status updates.
[ "Things", "to", "do", "on", "different", "status", "updates", "." ]
train
https://github.com/w1ll1am23/pubnubsub-handler/blob/0283c191d6042727f55a748f69a485d751f4cacb/pubnubsubhandler.py#L124-L160
w1ll1am23/pubnubsub-handler
pubnubsubhandler.py
PubNubSubCallback.message
def message(self, pubnub, message): """ Called when a new message is recevied on one of the subscribed to channels. Proccess the message and call the channels callback function(s). """ try: json_data = json.dumps(message.message.get('data')) except Att...
python
def message(self, pubnub, message): """ Called when a new message is recevied on one of the subscribed to channels. Proccess the message and call the channels callback function(s). """ try: json_data = json.dumps(message.message.get('data')) except Att...
[ "def", "message", "(", "self", ",", "pubnub", ",", "message", ")", ":", "try", ":", "json_data", "=", "json", ".", "dumps", "(", "message", ".", "message", ".", "get", "(", "'data'", ")", ")", "except", "AttributeError", ":", "json_data", "=", "message...
Called when a new message is recevied on one of the subscribed to channels. Proccess the message and call the channels callback function(s).
[ "Called", "when", "a", "new", "message", "is", "recevied", "on", "one", "of", "the", "subscribed", "to", "channels", ".", "Proccess", "the", "message", "and", "call", "the", "channels", "callback", "function", "(", "s", ")", "." ]
train
https://github.com/w1ll1am23/pubnubsub-handler/blob/0283c191d6042727f55a748f69a485d751f4cacb/pubnubsubhandler.py#L168-L185
dstufft/crust
crust/query.py
Query.clone
def clone(self, klass=None, memo=None, **kwargs): """ Creates a copy of the current instance. The 'kwargs' parameter can be used by clients to update attributes after copying has taken place. """ obj = Empty() obj.__class__ = klass or self.__class__ obj.resource ...
python
def clone(self, klass=None, memo=None, **kwargs): """ Creates a copy of the current instance. The 'kwargs' parameter can be used by clients to update attributes after copying has taken place. """ obj = Empty() obj.__class__ = klass or self.__class__ obj.resource ...
[ "def", "clone", "(", "self", ",", "klass", "=", "None", ",", "memo", "=", "None", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "Empty", "(", ")", "obj", ".", "__class__", "=", "klass", "or", "self", ".", "__class__", "obj", ".", "resource", "="...
Creates a copy of the current instance. The 'kwargs' parameter can be used by clients to update attributes after copying has taken place.
[ "Creates", "a", "copy", "of", "the", "current", "instance", ".", "The", "kwargs", "parameter", "can", "be", "used", "by", "clients", "to", "update", "attributes", "after", "copying", "has", "taken", "place", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L35-L53
dstufft/crust
crust/query.py
Query.set_limits
def set_limits(self, low=None, high=None): """ Adjusts the limits on the rows retrieved. We use low/high to set these, as it makes it more Pythonic to read and write. When the API query is created, they are converted to the appropriate offset and limit values. Any limits passed ...
python
def set_limits(self, low=None, high=None): """ Adjusts the limits on the rows retrieved. We use low/high to set these, as it makes it more Pythonic to read and write. When the API query is created, they are converted to the appropriate offset and limit values. Any limits passed ...
[ "def", "set_limits", "(", "self", ",", "low", "=", "None", ",", "high", "=", "None", ")", ":", "if", "high", "is", "not", "None", ":", "if", "self", ".", "high_mark", "is", "not", "None", ":", "self", ".", "high_mark", "=", "min", "(", "self", "....
Adjusts the limits on the rows retrieved. We use low/high to set these, as it makes it more Pythonic to read and write. When the API query is created, they are converted to the appropriate offset and limit values. Any limits passed in here are applied relative to the existing constraint...
[ "Adjusts", "the", "limits", "on", "the", "rows", "retrieved", ".", "We", "use", "low", "/", "high", "to", "set", "these", "as", "it", "makes", "it", "more", "Pythonic", "to", "read", "and", "write", ".", "When", "the", "API", "query", "is", "created", ...
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L80-L99
dstufft/crust
crust/query.py
Query.results
def results(self, limit=100): """ Yields the results from the API, efficiently handling the pagination and properly passing all paramaters. """ limited = True if self.high_mark is not None else False rmax = self.high_mark - self.low_mark if limited else None rnum ...
python
def results(self, limit=100): """ Yields the results from the API, efficiently handling the pagination and properly passing all paramaters. """ limited = True if self.high_mark is not None else False rmax = self.high_mark - self.low_mark if limited else None rnum ...
[ "def", "results", "(", "self", ",", "limit", "=", "100", ")", ":", "limited", "=", "True", "if", "self", ".", "high_mark", "is", "not", "None", "else", "False", "rmax", "=", "self", ".", "high_mark", "-", "self", ".", "low_mark", "if", "limited", "el...
Yields the results from the API, efficiently handling the pagination and properly passing all paramaters.
[ "Yields", "the", "results", "from", "the", "API", "efficiently", "handling", "the", "pagination", "and", "properly", "passing", "all", "paramaters", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L101-L132
dstufft/crust
crust/query.py
Query.delete
def delete(self): """ Deletes the results of this query, it first fetches all the items to be deletes and then issues a PATCH against the list uri of the resource. """ uris = [obj["resource_uri"] for obj in self.results()] data = self.resource._meta.api.resource_serialize...
python
def delete(self): """ Deletes the results of this query, it first fetches all the items to be deletes and then issues a PATCH against the list uri of the resource. """ uris = [obj["resource_uri"] for obj in self.results()] data = self.resource._meta.api.resource_serialize...
[ "def", "delete", "(", "self", ")", ":", "uris", "=", "[", "obj", "[", "\"resource_uri\"", "]", "for", "obj", "in", "self", ".", "results", "(", ")", "]", "data", "=", "self", ".", "resource", ".", "_meta", ".", "api", ".", "resource_serialize", "(", ...
Deletes the results of this query, it first fetches all the items to be deletes and then issues a PATCH against the list uri of the resource.
[ "Deletes", "the", "results", "of", "this", "query", "it", "first", "fetches", "all", "the", "items", "to", "be", "deletes", "and", "then", "issues", "a", "PATCH", "against", "the", "list", "uri", "of", "the", "resource", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L134-L143
dstufft/crust
crust/query.py
Query.get_count
def get_count(self): """ Gets the total_count using the current filter constraints. """ params = self.get_params() params["offset"] = self.low_mark params["limit"] = 1 r = self.resource._meta.api.http_resource("GET", self.resource._meta.resource_name, params=para...
python
def get_count(self): """ Gets the total_count using the current filter constraints. """ params = self.get_params() params["offset"] = self.low_mark params["limit"] = 1 r = self.resource._meta.api.http_resource("GET", self.resource._meta.resource_name, params=para...
[ "def", "get_count", "(", "self", ")", ":", "params", "=", "self", ".", "get_params", "(", ")", "params", "[", "\"offset\"", "]", "=", "self", ".", "low_mark", "params", "[", "\"limit\"", "]", "=", "1", "r", "=", "self", ".", "resource", ".", "_meta",...
Gets the total_count using the current filter constraints.
[ "Gets", "the", "total_count", "using", "the", "current", "filter", "constraints", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L157-L176
dstufft/crust
crust/query.py
QuerySet.iterator
def iterator(self): """ An iterator over the results from applying this QuerySet to the api. """ for item in self.query.results(): obj = self.resource(**item) yield obj
python
def iterator(self): """ An iterator over the results from applying this QuerySet to the api. """ for item in self.query.results(): obj = self.resource(**item) yield obj
[ "def", "iterator", "(", "self", ")", ":", "for", "item", "in", "self", ".", "query", ".", "results", "(", ")", ":", "obj", "=", "self", ".", "resource", "(", "*", "*", "item", ")", "yield", "obj" ]
An iterator over the results from applying this QuerySet to the api.
[ "An", "iterator", "over", "the", "results", "from", "applying", "this", "QuerySet", "to", "the", "api", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L335-L343
dstufft/crust
crust/query.py
QuerySet.count
def count(self): """ Returns the number of records as an integer. If the QuerySet is already fully cached this simply returns the length of the cached results set to avoid an api call. """ if self._result_cache is not None and not self._iter: return len(self....
python
def count(self): """ Returns the number of records as an integer. If the QuerySet is already fully cached this simply returns the length of the cached results set to avoid an api call. """ if self._result_cache is not None and not self._iter: return len(self....
[ "def", "count", "(", "self", ")", ":", "if", "self", ".", "_result_cache", "is", "not", "None", "and", "not", "self", ".", "_iter", ":", "return", "len", "(", "self", ".", "_result_cache", ")", "return", "self", ".", "query", ".", "get_count", "(", "...
Returns the number of records as an integer. If the QuerySet is already fully cached this simply returns the length of the cached results set to avoid an api call.
[ "Returns", "the", "number", "of", "records", "as", "an", "integer", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L345-L355
dstufft/crust
crust/query.py
QuerySet.get
def get(self, *args, **kwargs): """ Performs the query and returns a single object matching the given keyword arguments. """ clone = self.filter(*args, **kwargs) if self.query.can_filter(): clone = clone.order_by() num = len(clone) if num ==...
python
def get(self, *args, **kwargs): """ Performs the query and returns a single object matching the given keyword arguments. """ clone = self.filter(*args, **kwargs) if self.query.can_filter(): clone = clone.order_by() num = len(clone) if num ==...
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "clone", "=", "self", ".", "filter", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "self", ".", "query", ".", "can_filter", "(", ")", ":", "clone", "=", "...
Performs the query and returns a single object matching the given keyword arguments.
[ "Performs", "the", "query", "and", "returns", "a", "single", "object", "matching", "the", "given", "keyword", "arguments", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L357-L380
dstufft/crust
crust/query.py
QuerySet.create
def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the api and returning the created object. """ obj = self.resource(**kwargs) obj.save(force_insert=True) return obj
python
def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the api and returning the created object. """ obj = self.resource(**kwargs) obj.save(force_insert=True) return obj
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "self", ".", "resource", "(", "*", "*", "kwargs", ")", "obj", ".", "save", "(", "force_insert", "=", "True", ")", "return", "obj" ]
Creates a new object with the given kwargs, saving it to the api and returning the created object.
[ "Creates", "a", "new", "object", "with", "the", "given", "kwargs", "saving", "it", "to", "the", "api", "and", "returning", "the", "created", "object", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L382-L389
dstufft/crust
crust/query.py
QuerySet.get_or_create
def get_or_create(self, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ assert kwargs, "get_or_create() must be passed at lea...
python
def get_or_create(self, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ assert kwargs, "get_or_create() must be passed at lea...
[ "def", "get_or_create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "assert", "kwargs", ",", "\"get_or_create() must be passed at least one keyword argument\"", "defaults", "=", "kwargs", ".", "pop", "(", "\"defaults\"", ",", "{", "}", ")", "lookup", "=", "k...
Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created.
[ "Looks", "up", "an", "object", "with", "the", "given", "kwargs", "creating", "one", "if", "necessary", ".", "Returns", "a", "tuple", "of", "(", "object", "created", ")", "where", "created", "is", "a", "boolean", "specifying", "whether", "an", "object", "wa...
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L391-L409
dstufft/crust
crust/query.py
QuerySet.delete
def delete(self): """ Deletes the records in the current QuerySet. """ assert self.query.can_filter(), "Cannot use 'limit' or 'offset' with delete." del_query = self._clone() # Disable non-supported fields. del_query.query.clear_ordering() return del_qu...
python
def delete(self): """ Deletes the records in the current QuerySet. """ assert self.query.can_filter(), "Cannot use 'limit' or 'offset' with delete." del_query = self._clone() # Disable non-supported fields. del_query.query.clear_ordering() return del_qu...
[ "def", "delete", "(", "self", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot use 'limit' or 'offset' with delete.\"", "del_query", "=", "self", ".", "_clone", "(", ")", "# Disable non-supported fields.", "del_query", ".", "qu...
Deletes the records in the current QuerySet.
[ "Deletes", "the", "records", "in", "the", "current", "QuerySet", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L411-L422
dstufft/crust
crust/query.py
QuerySet.filter
def filter(self, **kwargs): """ Returns a new QuerySet instance with the args ANDed to the existing set. """ if kwargs: assert self.query.can_filter(), "Cannot filter a query once a slice has been taken." clone = self._clone() clone.query.add_filters(...
python
def filter(self, **kwargs): """ Returns a new QuerySet instance with the args ANDed to the existing set. """ if kwargs: assert self.query.can_filter(), "Cannot filter a query once a slice has been taken." clone = self._clone() clone.query.add_filters(...
[ "def", "filter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot filter a query once a slice has been taken.\"", "clone", "=", "self", ".", "_clone", "(", ")", ...
Returns a new QuerySet instance with the args ANDed to the existing set.
[ "Returns", "a", "new", "QuerySet", "instance", "with", "the", "args", "ANDed", "to", "the", "existing", "set", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L439-L450
dstufft/crust
crust/query.py
QuerySet.order_by
def order_by(self, field_name=None): """ Returns a new QuerySet instance with the ordering changed. """ assert self.query.can_filter(), "Cannot reorder a query once a slice has been taken." clone = self._clone() clone.query.clear_ordering() if field_name is not ...
python
def order_by(self, field_name=None): """ Returns a new QuerySet instance with the ordering changed. """ assert self.query.can_filter(), "Cannot reorder a query once a slice has been taken." clone = self._clone() clone.query.clear_ordering() if field_name is not ...
[ "def", "order_by", "(", "self", ",", "field_name", "=", "None", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot reorder a query once a slice has been taken.\"", "clone", "=", "self", ".", "_clone", "(", ")", "clone", ".", ...
Returns a new QuerySet instance with the ordering changed.
[ "Returns", "a", "new", "QuerySet", "instance", "with", "the", "ordering", "changed", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L452-L464
dstufft/crust
crust/query.py
QuerySet._fill_cache
def _fill_cache(self, num=None): """ Fills the result cache with 'num' more entries (or until the results iterator is exhausted). """ if self._iter: try: for i in range(num or ITER_CHUNK_SIZE): self._result_cache.append(next(self._i...
python
def _fill_cache(self, num=None): """ Fills the result cache with 'num' more entries (or until the results iterator is exhausted). """ if self._iter: try: for i in range(num or ITER_CHUNK_SIZE): self._result_cache.append(next(self._i...
[ "def", "_fill_cache", "(", "self", ",", "num", "=", "None", ")", ":", "if", "self", ".", "_iter", ":", "try", ":", "for", "i", "in", "range", "(", "num", "or", "ITER_CHUNK_SIZE", ")", ":", "self", ".", "_result_cache", ".", "append", "(", "next", "...
Fills the result cache with 'num' more entries (or until the results iterator is exhausted).
[ "Fills", "the", "result", "cache", "with", "num", "more", "entries", "(", "or", "until", "the", "results", "iterator", "is", "exhausted", ")", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L501-L511
treycucco/bidon
bidon/util/__init__.py
exclude
def exclude(source, keys, *, transform=None): """Returns a dictionary excluding keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a predicate function that accepting a key :transform: a function that transforms the values """ check = keys if callable(keys) else lambda key: key i...
python
def exclude(source, keys, *, transform=None): """Returns a dictionary excluding keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a predicate function that accepting a key :transform: a function that transforms the values """ check = keys if callable(keys) else lambda key: key i...
[ "def", "exclude", "(", "source", ",", "keys", ",", "*", ",", "transform", "=", "None", ")", ":", "check", "=", "keys", "if", "callable", "(", "keys", ")", "else", "lambda", "key", ":", "key", "in", "keys", "return", "{", "key", ":", "transform", "(...
Returns a dictionary excluding keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a predicate function that accepting a key :transform: a function that transforms the values
[ "Returns", "a", "dictionary", "excluding", "keys", "from", "a", "source", "dictionary", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L32-L41
treycucco/bidon
bidon/util/__init__.py
pick
def pick(source, keys, *, transform=None): """Returns a dictionary including only specified keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a predicate function that accepting a key :transform: a function that transforms the values """ check = keys if callable(keys) else lambd...
python
def pick(source, keys, *, transform=None): """Returns a dictionary including only specified keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a predicate function that accepting a key :transform: a function that transforms the values """ check = keys if callable(keys) else lambd...
[ "def", "pick", "(", "source", ",", "keys", ",", "*", ",", "transform", "=", "None", ")", ":", "check", "=", "keys", "if", "callable", "(", "keys", ")", "else", "lambda", "key", ":", "key", "in", "keys", "return", "{", "key", ":", "transform", "(", ...
Returns a dictionary including only specified keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a predicate function that accepting a key :transform: a function that transforms the values
[ "Returns", "a", "dictionary", "including", "only", "specified", "keys", "from", "a", "source", "dictionary", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L44-L53
treycucco/bidon
bidon/util/__init__.py
json_default
def json_default(obj): """Convert an object to JSON, via the defaults set with register_json_default. :obj: the object to convert """ for default in _JSON_DEFAULTS: if default[0](obj): return default[1](obj) raise TypeError(repr(obj) + " is not JSON serializable")
python
def json_default(obj): """Convert an object to JSON, via the defaults set with register_json_default. :obj: the object to convert """ for default in _JSON_DEFAULTS: if default[0](obj): return default[1](obj) raise TypeError(repr(obj) + " is not JSON serializable")
[ "def", "json_default", "(", "obj", ")", ":", "for", "default", "in", "_JSON_DEFAULTS", ":", "if", "default", "[", "0", "]", "(", "obj", ")", ":", "return", "default", "[", "1", "]", "(", "obj", ")", "raise", "TypeError", "(", "repr", "(", "obj", ")...
Convert an object to JSON, via the defaults set with register_json_default. :obj: the object to convert
[ "Convert", "an", "object", "to", "JSON", "via", "the", "defaults", "set", "with", "register_json_default", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L67-L75
treycucco/bidon
bidon/util/__init__.py
to_json
def to_json(obj, pretty=False): """Converts an object to JSON, using the defaults specified in register_json_default. :obj: the object to convert to JSON :pretty: if True, extra whitespace is added to make the output easier to read """ sort_keys = False indent = None separators = (",", ":") if isinsta...
python
def to_json(obj, pretty=False): """Converts an object to JSON, using the defaults specified in register_json_default. :obj: the object to convert to JSON :pretty: if True, extra whitespace is added to make the output easier to read """ sort_keys = False indent = None separators = (",", ":") if isinsta...
[ "def", "to_json", "(", "obj", ",", "pretty", "=", "False", ")", ":", "sort_keys", "=", "False", "indent", "=", "None", "separators", "=", "(", "\",\"", ",", "\":\"", ")", "if", "isinstance", "(", "pretty", ",", "tuple", ")", ":", "sort_keys", ",", "i...
Converts an object to JSON, using the defaults specified in register_json_default. :obj: the object to convert to JSON :pretty: if True, extra whitespace is added to make the output easier to read
[ "Converts", "an", "object", "to", "JSON", "using", "the", "defaults", "specified", "in", "register_json_default", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L78-L96
treycucco/bidon
bidon/util/__init__.py
has_value
def has_value(obj, name): """A flexible method for getting values from objects by name. returns: - obj is None: (False, None) - obj is dict: (name in obj, obj.get(name)) - obj hasattr(name): (True, getattr(obj, name)) - else: (False, None) :obj: the object to pull values from :name: the name to use wh...
python
def has_value(obj, name): """A flexible method for getting values from objects by name. returns: - obj is None: (False, None) - obj is dict: (name in obj, obj.get(name)) - obj hasattr(name): (True, getattr(obj, name)) - else: (False, None) :obj: the object to pull values from :name: the name to use wh...
[ "def", "has_value", "(", "obj", ",", "name", ")", ":", "if", "obj", "is", "None", ":", "return", "(", "False", ",", "None", ")", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "(", "name", "in", "obj", ",", "obj", ".", "get", ...
A flexible method for getting values from objects by name. returns: - obj is None: (False, None) - obj is dict: (name in obj, obj.get(name)) - obj hasattr(name): (True, getattr(obj, name)) - else: (False, None) :obj: the object to pull values from :name: the name to use when getting the value
[ "A", "flexible", "method", "for", "getting", "values", "from", "objects", "by", "name", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L99-L120
treycucco/bidon
bidon/util/__init__.py
get_value
def get_value(obj, name, fallback=None): """Calls through to has_value. If has_value[0] is True, return has_value[1] otherwise returns fallback() if fallback is callable, else just fallback. :obj: the object to pull values from :name: the name to use when getting the value :fallback: the value to return when...
python
def get_value(obj, name, fallback=None): """Calls through to has_value. If has_value[0] is True, return has_value[1] otherwise returns fallback() if fallback is callable, else just fallback. :obj: the object to pull values from :name: the name to use when getting the value :fallback: the value to return when...
[ "def", "get_value", "(", "obj", ",", "name", ",", "fallback", "=", "None", ")", ":", "present", ",", "value", "=", "has_value", "(", "obj", ",", "name", ")", "if", "present", ":", "return", "value", "else", ":", "if", "callable", "(", "fallback", ")"...
Calls through to has_value. If has_value[0] is True, return has_value[1] otherwise returns fallback() if fallback is callable, else just fallback. :obj: the object to pull values from :name: the name to use when getting the value :fallback: the value to return when has_value(:obj:, :name:) returns False
[ "Calls", "through", "to", "has_value", ".", "If", "has_value", "[", "0", "]", "is", "True", "return", "has_value", "[", "1", "]", "otherwise", "returns", "fallback", "()", "if", "fallback", "is", "callable", "else", "just", "fallback", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L123-L138
treycucco/bidon
bidon/util/__init__.py
set_value
def set_value(obj, name, value): """A flexible method for setting a value on an object. If the object implements __setitem__ (such as a dict) performs obj[name] = value, else performs setattr(obj, name, value). :obj: the object to set the value on :name: the name to assign the value to :value: the value t...
python
def set_value(obj, name, value): """A flexible method for setting a value on an object. If the object implements __setitem__ (such as a dict) performs obj[name] = value, else performs setattr(obj, name, value). :obj: the object to set the value on :name: the name to assign the value to :value: the value t...
[ "def", "set_value", "(", "obj", ",", "name", ",", "value", ")", ":", "if", "hasattr", "(", "obj", ",", "\"__setitem__\"", ")", ":", "obj", "[", "name", "]", "=", "value", "else", ":", "setattr", "(", "obj", ",", "name", ",", "value", ")" ]
A flexible method for setting a value on an object. If the object implements __setitem__ (such as a dict) performs obj[name] = value, else performs setattr(obj, name, value). :obj: the object to set the value on :name: the name to assign the value to :value: the value to assign
[ "A", "flexible", "method", "for", "setting", "a", "value", "on", "an", "object", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L141-L154
treycucco/bidon
bidon/util/__init__.py
with_defaults
def with_defaults(method, nparams, defaults=None): """Call method with nparams positional parameters, all non-specified defaults are passed None. :method: the method to call :nparams: the number of parameters the function expects :defaults: the default values to pass in for the last len(defaults) params """ ...
python
def with_defaults(method, nparams, defaults=None): """Call method with nparams positional parameters, all non-specified defaults are passed None. :method: the method to call :nparams: the number of parameters the function expects :defaults: the default values to pass in for the last len(defaults) params """ ...
[ "def", "with_defaults", "(", "method", ",", "nparams", ",", "defaults", "=", "None", ")", ":", "args", "=", "[", "None", "]", "*", "nparams", "if", "not", "defaults", "else", "defaults", "+", "max", "(", "nparams", "-", "len", "(", "defaults", ")", "...
Call method with nparams positional parameters, all non-specified defaults are passed None. :method: the method to call :nparams: the number of parameters the function expects :defaults: the default values to pass in for the last len(defaults) params
[ "Call", "method", "with", "nparams", "positional", "parameters", "all", "non", "-", "specified", "defaults", "are", "passed", "None", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L157-L165
treycucco/bidon
bidon/util/__init__.py
delegate
def delegate(from_owner, to_owner, methods): """Creates methods on from_owner to call through to methods on to_owner. :from_owner: the object to delegate to :to_owner: the owner on which to delegate from :methods: a list of methods to delegate """ for method in methods: _delegate(from_owner, to_owner, ...
python
def delegate(from_owner, to_owner, methods): """Creates methods on from_owner to call through to methods on to_owner. :from_owner: the object to delegate to :to_owner: the owner on which to delegate from :methods: a list of methods to delegate """ for method in methods: _delegate(from_owner, to_owner, ...
[ "def", "delegate", "(", "from_owner", ",", "to_owner", ",", "methods", ")", ":", "for", "method", "in", "methods", ":", "_delegate", "(", "from_owner", ",", "to_owner", ",", "method", ")" ]
Creates methods on from_owner to call through to methods on to_owner. :from_owner: the object to delegate to :to_owner: the owner on which to delegate from :methods: a list of methods to delegate
[ "Creates", "methods", "on", "from_owner", "to", "call", "through", "to", "methods", "on", "to_owner", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L177-L185
treycucco/bidon
bidon/util/__init__.py
_delegate
def _delegate(from_owner, to_owner, method): """Creates a method on from_owner to calls through to the same method on to_owner. :from_owner: the object to delegate to :to_owner: the owner on which to delegate from :methods: the method to delegate """ dgate = lambda self, *args, **kwargs: getattr(getattr(se...
python
def _delegate(from_owner, to_owner, method): """Creates a method on from_owner to calls through to the same method on to_owner. :from_owner: the object to delegate to :to_owner: the owner on which to delegate from :methods: the method to delegate """ dgate = lambda self, *args, **kwargs: getattr(getattr(se...
[ "def", "_delegate", "(", "from_owner", ",", "to_owner", ",", "method", ")", ":", "dgate", "=", "lambda", "self", ",", "*", "args", ",", "*", "*", "kwargs", ":", "getattr", "(", "getattr", "(", "self", ",", "to_owner", ")", ",", "method", ")", "(", ...
Creates a method on from_owner to calls through to the same method on to_owner. :from_owner: the object to delegate to :to_owner: the owner on which to delegate from :methods: the method to delegate
[ "Creates", "a", "method", "on", "from_owner", "to", "calls", "through", "to", "the", "same", "method", "on", "to_owner", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L188-L198
treycucco/bidon
bidon/util/__init__.py
flatten_dict
def flatten_dict(source, ancestors=None): """Flattens a dictionary into (key, value) tuples. Where key is a tuple of ancestor keys. :source: the root dictionary :ancestors: the tuple of ancestors for every key in :source:""" if not ancestors: ancestors = () for key in source: if isinstance(source[key...
python
def flatten_dict(source, ancestors=None): """Flattens a dictionary into (key, value) tuples. Where key is a tuple of ancestor keys. :source: the root dictionary :ancestors: the tuple of ancestors for every key in :source:""" if not ancestors: ancestors = () for key in source: if isinstance(source[key...
[ "def", "flatten_dict", "(", "source", ",", "ancestors", "=", "None", ")", ":", "if", "not", "ancestors", ":", "ancestors", "=", "(", ")", "for", "key", "in", "source", ":", "if", "isinstance", "(", "source", "[", "key", "]", ",", "dict", ")", ":", ...
Flattens a dictionary into (key, value) tuples. Where key is a tuple of ancestor keys. :source: the root dictionary :ancestors: the tuple of ancestors for every key in :source:
[ "Flattens", "a", "dictionary", "into", "(", "key", "value", ")", "tuples", ".", "Where", "key", "is", "a", "tuple", "of", "ancestor", "keys", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L201-L212
treycucco/bidon
bidon/util/__init__.py
get_file_object
def get_file_object(filename, mode="r"): """Context manager for a file object. If filename is present, this is the same as with open(filename, mode): ... If filename is not present, then the file object returned is either sys.stdin or sys.stdout depending on the mode. :filename: the name of the file, or Non...
python
def get_file_object(filename, mode="r"): """Context manager for a file object. If filename is present, this is the same as with open(filename, mode): ... If filename is not present, then the file object returned is either sys.stdin or sys.stdout depending on the mode. :filename: the name of the file, or Non...
[ "def", "get_file_object", "(", "filename", ",", "mode", "=", "\"r\"", ")", ":", "if", "filename", "is", "None", ":", "if", "mode", ".", "startswith", "(", "\"r\"", ")", ":", "yield", "sys", ".", "stdin", "else", ":", "yield", "sys", ".", "stdout", "e...
Context manager for a file object. If filename is present, this is the same as with open(filename, mode): ... If filename is not present, then the file object returned is either sys.stdin or sys.stdout depending on the mode. :filename: the name of the file, or None for STDIN :mode: the mode to open the file...
[ "Context", "manager", "for", "a", "file", "object", ".", "If", "filename", "is", "present", "this", "is", "the", "same", "as", "with", "open", "(", "filename", "mode", ")", ":", "..." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L250-L267
opinkerfi/nago
nago/extensions/__init__.py
get_methods
def get_methods(extension_name): """ Return all methods in extension that have nago_access set """ extension = get_extension(extension_name) methods = {} for name, i in inspect.getmembers(extension): if hasattr(i, 'nago_access'): api_name = i.nago_name methods[api_name] =...
python
def get_methods(extension_name): """ Return all methods in extension that have nago_access set """ extension = get_extension(extension_name) methods = {} for name, i in inspect.getmembers(extension): if hasattr(i, 'nago_access'): api_name = i.nago_name methods[api_name] =...
[ "def", "get_methods", "(", "extension_name", ")", ":", "extension", "=", "get_extension", "(", "extension_name", ")", "methods", "=", "{", "}", "for", "name", ",", "i", "in", "inspect", ".", "getmembers", "(", "extension", ")", ":", "if", "hasattr", "(", ...
Return all methods in extension that have nago_access set
[ "Return", "all", "methods", "in", "extension", "that", "have", "nago_access", "set" ]
train
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/__init__.py#L51-L59
asphalt-framework/asphalt-templating
asphalt/templating/utils.py
package_to_directory
def package_to_directory(package_path: str) -> str: """ Translate a package/path specification into a real file system pathname. :param package_path: a package name or a package/path specification like ``package.subpackage/directory/subdirectory`` :return: the translated path name :raises I...
python
def package_to_directory(package_path: str) -> str: """ Translate a package/path specification into a real file system pathname. :param package_path: a package name or a package/path specification like ``package.subpackage/directory/subdirectory`` :return: the translated path name :raises I...
[ "def", "package_to_directory", "(", "package_path", ":", "str", ")", "->", "str", ":", "if", "'/'", "in", "package_path", ":", "pkgname", ",", "subpath", "=", "package_path", ".", "split", "(", "'/'", ",", "1", ")", "else", ":", "pkgname", ",", "subpath"...
Translate a package/path specification into a real file system pathname. :param package_path: a package name or a package/path specification like ``package.subpackage/directory/subdirectory`` :return: the translated path name :raises ImportError: if the package cannot be imported :raises Lookup...
[ "Translate", "a", "package", "/", "path", "specification", "into", "a", "real", "file", "system", "pathname", "." ]
train
https://github.com/asphalt-framework/asphalt-templating/blob/e5f836290820aa295b048b17b96d3896d5f1eeac/asphalt/templating/utils.py#L5-L29
bramwelt/field
field/__init__.py
column_converter
def column_converter(string): """ Converts column arguments to integers. - Accepts columns in form of INT, or the range INT-INT. - Returns a list of one or more integers. """ column = string.strip(',') if '-' in column: column_range = map(int, column.split('-')) # For decrea...
python
def column_converter(string): """ Converts column arguments to integers. - Accepts columns in form of INT, or the range INT-INT. - Returns a list of one or more integers. """ column = string.strip(',') if '-' in column: column_range = map(int, column.split('-')) # For decrea...
[ "def", "column_converter", "(", "string", ")", ":", "column", "=", "string", ".", "strip", "(", "','", ")", "if", "'-'", "in", "column", ":", "column_range", "=", "map", "(", "int", ",", "column", ".", "split", "(", "'-'", ")", ")", "# For decreasing r...
Converts column arguments to integers. - Accepts columns in form of INT, or the range INT-INT. - Returns a list of one or more integers.
[ "Converts", "column", "arguments", "to", "integers", "." ]
train
https://github.com/bramwelt/field/blob/05f38170d080fb48e76aa984bf4aa6b3d05ea6dc/field/__init__.py#L49-L71
bramwelt/field
field/__init__.py
check_columns
def check_columns(column, line, columns): """ Make sure the column is the minimum between the largest column asked for and the max column available in the line. """ return column <= min(len(line), max(columns))
python
def check_columns(column, line, columns): """ Make sure the column is the minimum between the largest column asked for and the max column available in the line. """ return column <= min(len(line), max(columns))
[ "def", "check_columns", "(", "column", ",", "line", ",", "columns", ")", ":", "return", "column", "<=", "min", "(", "len", "(", "line", ")", ",", "max", "(", "columns", ")", ")" ]
Make sure the column is the minimum between the largest column asked for and the max column available in the line.
[ "Make", "sure", "the", "column", "is", "the", "minimum", "between", "the", "largest", "column", "asked", "for", "and", "the", "max", "column", "available", "in", "the", "line", "." ]
train
https://github.com/bramwelt/field/blob/05f38170d080fb48e76aa984bf4aa6b3d05ea6dc/field/__init__.py#L92-L97
bramwelt/field
field/__init__.py
main
def main(): """ Main Entry Point """ args = parser.parse_args() filehandle = args.filename delim = args.delimiter columns = args.columns[0] if not columns: for line in filehandle: print line, exit(0) cs = list(chain.from_iterable(columns)) fields = (...
python
def main(): """ Main Entry Point """ args = parser.parse_args() filehandle = args.filename delim = args.delimiter columns = args.columns[0] if not columns: for line in filehandle: print line, exit(0) cs = list(chain.from_iterable(columns)) fields = (...
[ "def", "main", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "filehandle", "=", "args", ".", "filename", "delim", "=", "args", ".", "delimiter", "columns", "=", "args", ".", "columns", "[", "0", "]", "if", "not", "columns", ":", ...
Main Entry Point
[ "Main", "Entry", "Point" ]
train
https://github.com/bramwelt/field/blob/05f38170d080fb48e76aa984bf4aa6b3d05ea6dc/field/__init__.py#L99-L119
priendeau/UnderscoreX
setup.py
Kargs2Attr
def Kargs2Attr( ): """ This Decorator Will: Read **kwargs key and add it to current Object-class ClassTinyDecl under current name readed from **kwargs key name. """ def decorator( func ): def inner( **kwargs ): for ItemName in kwargs.keys(): set...
python
def Kargs2Attr( ): """ This Decorator Will: Read **kwargs key and add it to current Object-class ClassTinyDecl under current name readed from **kwargs key name. """ def decorator( func ): def inner( **kwargs ): for ItemName in kwargs.keys(): set...
[ "def", "Kargs2Attr", "(", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "inner", "(", "*", "*", "kwargs", ")", ":", "for", "ItemName", "in", "kwargs", ".", "keys", "(", ")", ":", "setattr", "(", "__builtins__", ",", "ItemName", ",", "...
This Decorator Will: Read **kwargs key and add it to current Object-class ClassTinyDecl under current name readed from **kwargs key name.
[ "This", "Decorator", "Will", ":", "Read", "**", "kwargs", "key", "and", "add", "it", "to", "current", "Object", "-", "class", "ClassTinyDecl", "under", "current", "name", "readed", "from", "**", "kwargs", "key", "name", "." ]
train
https://github.com/priendeau/UnderscoreX/blob/ac83e13627cfa009dc5731a1fb31f9c6145d983a/setup.py#L68-L82
jmgilman/Neolib
neolib/pyamf/remoting/amf3.py
generate_error
def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. """ import traceback if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = ...
python
def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. """ import traceback if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = ...
[ "def", "generate_error", "(", "request", ",", "cls", ",", "e", ",", "tb", ",", "include_traceback", "=", "False", ")", ":", "import", "traceback", "if", "hasattr", "(", "cls", ",", "'_amf_code'", ")", ":", "code", "=", "cls", ".", "_amf_code", "else", ...
Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent.
[ "Builds", "an", "L", "{", "ErrorMessage<pyamf", ".", "flex", ".", "messaging", ".", "ErrorMessage", ">", "}", "based", "on", "the", "last", "traceback", "and", "the", "request", "that", "was", "sent", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/amf3.py#L53-L93
jmgilman/Neolib
neolib/pyamf/remoting/amf3.py
RequestProcessor.buildErrorResponse
def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>} """ if error is not N...
python
def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>} """ if error is not N...
[ "def", "buildErrorResponse", "(", "self", ",", "request", ",", "error", "=", "None", ")", ":", "if", "error", "is", "not", "None", ":", "cls", ",", "e", ",", "tb", "=", "error", "else", ":", "cls", ",", "e", ",", "tb", "=", "sys", ".", "exc_info"...
Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>}
[ "Builds", "an", "error", "response", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/amf3.py#L100-L114
synw/goerr
goerr/__init__.py
Err.panic
def panic(self, *args): """ Creates a fatal error and exit """ self._err("fatal", *args) if self.test_errs_mode is False: # pragma: no cover sys.exit(1)
python
def panic(self, *args): """ Creates a fatal error and exit """ self._err("fatal", *args) if self.test_errs_mode is False: # pragma: no cover sys.exit(1)
[ "def", "panic", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_err", "(", "\"fatal\"", ",", "*", "args", ")", "if", "self", ".", "test_errs_mode", "is", "False", ":", "# pragma: no cover", "sys", ".", "exit", "(", "1", ")" ]
Creates a fatal error and exit
[ "Creates", "a", "fatal", "error", "and", "exit" ]
train
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/__init__.py#L59-L65
synw/goerr
goerr/__init__.py
Err.warning
def warning(self, *args) -> "Err": """ Creates a warning message """ error = self._create_err("warning", *args) print(self._errmsg(error)) return error
python
def warning(self, *args) -> "Err": """ Creates a warning message """ error = self._create_err("warning", *args) print(self._errmsg(error)) return error
[ "def", "warning", "(", "self", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_create_err", "(", "\"warning\"", ",", "*", "args", ")", "print", "(", "self", ".", "_errmsg", "(", "error", ")", ")", "return", "error" ]
Creates a warning message
[ "Creates", "a", "warning", "message" ]
train
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/__init__.py#L67-L73
synw/goerr
goerr/__init__.py
Err.info
def info(self, *args) -> "Err": """ Creates an info message """ error = self._create_err("info", *args) print(self._errmsg(error)) return error
python
def info(self, *args) -> "Err": """ Creates an info message """ error = self._create_err("info", *args) print(self._errmsg(error)) return error
[ "def", "info", "(", "self", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_create_err", "(", "\"info\"", ",", "*", "args", ")", "print", "(", "self", ".", "_errmsg", "(", "error", ")", ")", "return", "error" ]
Creates an info message
[ "Creates", "an", "info", "message" ]
train
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/__init__.py#L75-L81
synw/goerr
goerr/__init__.py
Err.debug
def debug(self, *args) -> "Err": """ Creates a debug message """ error = self._create_err("debug", *args) print(self._errmsg(error)) return error
python
def debug(self, *args) -> "Err": """ Creates a debug message """ error = self._create_err("debug", *args) print(self._errmsg(error)) return error
[ "def", "debug", "(", "self", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_create_err", "(", "\"debug\"", ",", "*", "args", ")", "print", "(", "self", ".", "_errmsg", "(", "error", ")", ")", "return", "error" ]
Creates a debug message
[ "Creates", "a", "debug", "message" ]
train
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/__init__.py#L83-L89
synw/goerr
goerr/__init__.py
Err._create_err
def _create_err(self, errclass: str, *args) -> "Err": """ Create an error """ error = self._new_err(errclass, *args) self._add(error) return error
python
def _create_err(self, errclass: str, *args) -> "Err": """ Create an error """ error = self._new_err(errclass, *args) self._add(error) return error
[ "def", "_create_err", "(", "self", ",", "errclass", ":", "str", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_new_err", "(", "errclass", ",", "*", "args", ")", "self", ".", "_add", "(", "error", ")", "return", "error" ]
Create an error
[ "Create", "an", "error" ]
train
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/__init__.py#L91-L97
synw/goerr
goerr/__init__.py
Err._err
def _err(self, errclass: str="error", *args) -> "Err": """ Creates an error """ error = self._new_err(errclass, *args) if self.log_errs is True: sep = " " if self.log_format == "csv": sep = "," msg = str(datetime.now()) + sep + ...
python
def _err(self, errclass: str="error", *args) -> "Err": """ Creates an error """ error = self._new_err(errclass, *args) if self.log_errs is True: sep = " " if self.log_format == "csv": sep = "," msg = str(datetime.now()) + sep + ...
[ "def", "_err", "(", "self", ",", "errclass", ":", "str", "=", "\"error\"", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_new_err", "(", "errclass", ",", "*", "args", ")", "if", "self", ".", "log_errs", "is", "True", ":",...
Creates an error
[ "Creates", "an", "error" ]
train
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/__init__.py#L99-L113
synw/goerr
goerr/__init__.py
Err._new_err
def _new_err(self, errclass: str, *args) -> 'Err': """ Error constructor """ # get the message or exception ex, msg = self._get_args(*args) # construct the error # handle exception ftb = None # type: str function = None # type: str errtyp...
python
def _new_err(self, errclass: str, *args) -> 'Err': """ Error constructor """ # get the message or exception ex, msg = self._get_args(*args) # construct the error # handle exception ftb = None # type: str function = None # type: str errtyp...
[ "def", "_new_err", "(", "self", ",", "errclass", ":", "str", ",", "*", "args", ")", "->", "'Err'", ":", "# get the message or exception", "ex", ",", "msg", "=", "self", ".", "_get_args", "(", "*", "args", ")", "# construct the error", "# handle exception", "...
Error constructor
[ "Error", "constructor" ]
train
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/__init__.py#L115-L188