id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
246,800
minhhoit/yacms
yacms/core/templatetags/yacms_tags.py
try_url
def try_url(url_name): """ Mimics Django's ``url`` template tag but fails silently. Used for url names in admin templates as these won't resolve when admin tests are running. """ from warnings import warn warn("try_url is deprecated, use the url tag with the 'as' arg instead.") try: url = reverse(url_name) except NoReverseMatch: return "" return url
python
def try_url(url_name): """ Mimics Django's ``url`` template tag but fails silently. Used for url names in admin templates as these won't resolve when admin tests are running. """ from warnings import warn warn("try_url is deprecated, use the url tag with the 'as' arg instead.") try: url = reverse(url_name) except NoReverseMatch: return "" return url
[ "def", "try_url", "(", "url_name", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "\"try_url is deprecated, use the url tag with the 'as' arg instead.\"", ")", "try", ":", "url", "=", "reverse", "(", "url_name", ")", "except", "NoReverseMatch", ":", "return", "\"\"", "return", "url" ]
Mimics Django's ``url`` template tag but fails silently. Used for url names in admin templates as these won't resolve when admin tests are running.
[ "Mimics", "Django", "s", "url", "template", "tag", "but", "fails", "silently", ".", "Used", "for", "url", "names", "in", "admin", "templates", "as", "these", "won", "t", "resolve", "when", "admin", "tests", "are", "running", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L518-L530
246,801
minhhoit/yacms
yacms/core/templatetags/yacms_tags.py
admin_dropdown_menu
def admin_dropdown_menu(context): """ Renders the app list for the admin dropdown menu navigation. """ template_vars = context.flatten() user = context["request"].user if user.is_staff: template_vars["dropdown_menu_app_list"] = admin_app_list( context["request"]) if user.is_superuser: sites = Site.objects.all() else: try: sites = user.sitepermissions.sites.all() except ObjectDoesNotExist: sites = Site.objects.none() template_vars["dropdown_menu_sites"] = list(sites) template_vars["dropdown_menu_selected_site_id"] = current_site_id() template_vars["settings"] = context["settings"] template_vars["request"] = context["request"] return template_vars
python
def admin_dropdown_menu(context): """ Renders the app list for the admin dropdown menu navigation. """ template_vars = context.flatten() user = context["request"].user if user.is_staff: template_vars["dropdown_menu_app_list"] = admin_app_list( context["request"]) if user.is_superuser: sites = Site.objects.all() else: try: sites = user.sitepermissions.sites.all() except ObjectDoesNotExist: sites = Site.objects.none() template_vars["dropdown_menu_sites"] = list(sites) template_vars["dropdown_menu_selected_site_id"] = current_site_id() template_vars["settings"] = context["settings"] template_vars["request"] = context["request"] return template_vars
[ "def", "admin_dropdown_menu", "(", "context", ")", ":", "template_vars", "=", "context", ".", "flatten", "(", ")", "user", "=", "context", "[", "\"request\"", "]", ".", "user", "if", "user", ".", "is_staff", ":", "template_vars", "[", "\"dropdown_menu_app_list\"", "]", "=", "admin_app_list", "(", "context", "[", "\"request\"", "]", ")", "if", "user", ".", "is_superuser", ":", "sites", "=", "Site", ".", "objects", ".", "all", "(", ")", "else", ":", "try", ":", "sites", "=", "user", ".", "sitepermissions", ".", "sites", ".", "all", "(", ")", "except", "ObjectDoesNotExist", ":", "sites", "=", "Site", ".", "objects", ".", "none", "(", ")", "template_vars", "[", "\"dropdown_menu_sites\"", "]", "=", "list", "(", "sites", ")", "template_vars", "[", "\"dropdown_menu_selected_site_id\"", "]", "=", "current_site_id", "(", ")", "template_vars", "[", "\"settings\"", "]", "=", "context", "[", "\"settings\"", "]", "template_vars", "[", "\"request\"", "]", "=", "context", "[", "\"request\"", "]", "return", "template_vars" ]
Renders the app list for the admin dropdown menu navigation.
[ "Renders", "the", "app", "list", "for", "the", "admin", "dropdown", "menu", "navigation", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L646-L666
246,802
minhhoit/yacms
yacms/core/templatetags/yacms_tags.py
dashboard_column
def dashboard_column(context, token): """ Takes an index for retrieving the sequence of template tags from ``yacms.conf.DASHBOARD_TAGS`` to render into the admin dashboard. """ column_index = int(token.split_contents()[1]) output = [] for tag in settings.DASHBOARD_TAGS[column_index]: t = Template("{%% load %s %%}{%% %s %%}" % tuple(tag.split("."))) output.append(t.render(context)) return "".join(output)
python
def dashboard_column(context, token): """ Takes an index for retrieving the sequence of template tags from ``yacms.conf.DASHBOARD_TAGS`` to render into the admin dashboard. """ column_index = int(token.split_contents()[1]) output = [] for tag in settings.DASHBOARD_TAGS[column_index]: t = Template("{%% load %s %%}{%% %s %%}" % tuple(tag.split("."))) output.append(t.render(context)) return "".join(output)
[ "def", "dashboard_column", "(", "context", ",", "token", ")", ":", "column_index", "=", "int", "(", "token", ".", "split_contents", "(", ")", "[", "1", "]", ")", "output", "=", "[", "]", "for", "tag", "in", "settings", ".", "DASHBOARD_TAGS", "[", "column_index", "]", ":", "t", "=", "Template", "(", "\"{%% load %s %%}{%% %s %%}\"", "%", "tuple", "(", "tag", ".", "split", "(", "\".\"", ")", ")", ")", "output", ".", "append", "(", "t", ".", "render", "(", "context", ")", ")", "return", "\"\"", ".", "join", "(", "output", ")" ]
Takes an index for retrieving the sequence of template tags from ``yacms.conf.DASHBOARD_TAGS`` to render into the admin dashboard.
[ "Takes", "an", "index", "for", "retrieving", "the", "sequence", "of", "template", "tags", "from", "yacms", ".", "conf", ".", "DASHBOARD_TAGS", "to", "render", "into", "the", "admin", "dashboard", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L688-L699
246,803
mushkevych/synergy_odm
odm/fields.py
BaseField.raise_error
def raise_error(self, message='', errors=None, field_name=None): """Raises a ValidationError. """ field_name = field_name if field_name else self.field_name raise ValidationError(message, errors=errors, field_name=field_name)
python
def raise_error(self, message='', errors=None, field_name=None): """Raises a ValidationError. """ field_name = field_name if field_name else self.field_name raise ValidationError(message, errors=errors, field_name=field_name)
[ "def", "raise_error", "(", "self", ",", "message", "=", "''", ",", "errors", "=", "None", ",", "field_name", "=", "None", ")", ":", "field_name", "=", "field_name", "if", "field_name", "else", "self", ".", "field_name", "raise", "ValidationError", "(", "message", ",", "errors", "=", "errors", ",", "field_name", "=", "field_name", ")" ]
Raises a ValidationError.
[ "Raises", "a", "ValidationError", "." ]
3a5ac37333fc6391478564ef653a4be38e332f68
https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L98-L101
246,804
mushkevych/synergy_odm
odm/fields.py
NestedDocumentField.validate
def validate(self, value): """Make sure that value is of the right type """ if not isinstance(value, self.nested_klass): self.raise_error('NestedClass is of the wrong type: {0} vs expected {1}' .format(value.__class__.__name__, self.nested_klass.__name__)) super(NestedDocumentField, self).validate(value)
python
def validate(self, value): """Make sure that value is of the right type """ if not isinstance(value, self.nested_klass): self.raise_error('NestedClass is of the wrong type: {0} vs expected {1}' .format(value.__class__.__name__, self.nested_klass.__name__)) super(NestedDocumentField, self).validate(value)
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "self", ".", "nested_klass", ")", ":", "self", ".", "raise_error", "(", "'NestedClass is of the wrong type: {0} vs expected {1}'", ".", "format", "(", "value", ".", "__class__", ".", "__name__", ",", "self", ".", "nested_klass", ".", "__name__", ")", ")", "super", "(", "NestedDocumentField", ",", "self", ")", ".", "validate", "(", "value", ")" ]
Make sure that value is of the right type
[ "Make", "sure", "that", "value", "is", "of", "the", "right", "type" ]
3a5ac37333fc6391478564ef653a4be38e332f68
https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L141-L146
246,805
mushkevych/synergy_odm
odm/fields.py
ListField.validate
def validate(self, value): """Make sure that the inspected value is of type `list` or `tuple` """ if not isinstance(value, (list, tuple)) or isinstance(value, str_types): self.raise_error('Only lists and tuples may be used in the ListField vs provided {0}' .format(type(value).__name__)) super(ListField, self).validate(value)
python
def validate(self, value): """Make sure that the inspected value is of type `list` or `tuple` """ if not isinstance(value, (list, tuple)) or isinstance(value, str_types): self.raise_error('Only lists and tuples may be used in the ListField vs provided {0}' .format(type(value).__name__)) super(ListField, self).validate(value)
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", "or", "isinstance", "(", "value", ",", "str_types", ")", ":", "self", ".", "raise_error", "(", "'Only lists and tuples may be used in the ListField vs provided {0}'", ".", "format", "(", "type", "(", "value", ")", ".", "__name__", ")", ")", "super", "(", "ListField", ",", "self", ")", ".", "validate", "(", "value", ")" ]
Make sure that the inspected value is of type `list` or `tuple`
[ "Make", "sure", "that", "the", "inspected", "value", "is", "of", "type", "list", "or", "tuple" ]
3a5ac37333fc6391478564ef653a4be38e332f68
https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L156-L161
246,806
mushkevych/synergy_odm
odm/fields.py
DictField.validate
def validate(self, value): """Make sure that the inspected value is of type `dict` """ if not isinstance(value, dict): self.raise_error('Only Python dict may be used in the DictField vs provided {0}' .format(type(value).__name__)) super(DictField, self).validate(value)
python
def validate(self, value): """Make sure that the inspected value is of type `dict` """ if not isinstance(value, dict): self.raise_error('Only Python dict may be used in the DictField vs provided {0}' .format(type(value).__name__)) super(DictField, self).validate(value)
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "self", ".", "raise_error", "(", "'Only Python dict may be used in the DictField vs provided {0}'", ".", "format", "(", "type", "(", "value", ")", ".", "__name__", ")", ")", "super", "(", "DictField", ",", "self", ")", ".", "validate", "(", "value", ")" ]
Make sure that the inspected value is of type `dict`
[ "Make", "sure", "that", "the", "inspected", "value", "is", "of", "type", "dict" ]
3a5ac37333fc6391478564ef653a4be38e332f68
https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L172-L177
246,807
scraperwiki/data-services-helpers
dshelpers.py
install_cache
def install_cache(expire_after=12 * 3600, cache_post=False): """ Patches the requests library with requests_cache. """ allowable_methods = ['GET'] if cache_post: allowable_methods.append('POST') requests_cache.install_cache( expire_after=expire_after, allowable_methods=allowable_methods)
python
def install_cache(expire_after=12 * 3600, cache_post=False): """ Patches the requests library with requests_cache. """ allowable_methods = ['GET'] if cache_post: allowable_methods.append('POST') requests_cache.install_cache( expire_after=expire_after, allowable_methods=allowable_methods)
[ "def", "install_cache", "(", "expire_after", "=", "12", "*", "3600", ",", "cache_post", "=", "False", ")", ":", "allowable_methods", "=", "[", "'GET'", "]", "if", "cache_post", ":", "allowable_methods", ".", "append", "(", "'POST'", ")", "requests_cache", ".", "install_cache", "(", "expire_after", "=", "expire_after", ",", "allowable_methods", "=", "allowable_methods", ")" ]
Patches the requests library with requests_cache.
[ "Patches", "the", "requests", "library", "with", "requests_cache", "." ]
a31ea2f40d20fd99d4c0938b87466330679db2c9
https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L97-L106
246,808
scraperwiki/data-services-helpers
dshelpers.py
download_url
def download_url(url, back_off=True, **kwargs): """ Get the content of a URL and return a file-like object. back_off=True provides retry """ if back_off: return _download_with_backoff(url, as_file=True, **kwargs) else: return _download_without_backoff(url, as_file=True, **kwargs)
python
def download_url(url, back_off=True, **kwargs): """ Get the content of a URL and return a file-like object. back_off=True provides retry """ if back_off: return _download_with_backoff(url, as_file=True, **kwargs) else: return _download_without_backoff(url, as_file=True, **kwargs)
[ "def", "download_url", "(", "url", ",", "back_off", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "back_off", ":", "return", "_download_with_backoff", "(", "url", ",", "as_file", "=", "True", ",", "*", "*", "kwargs", ")", "else", ":", "return", "_download_without_backoff", "(", "url", ",", "as_file", "=", "True", ",", "*", "*", "kwargs", ")" ]
Get the content of a URL and return a file-like object. back_off=True provides retry
[ "Get", "the", "content", "of", "a", "URL", "and", "return", "a", "file", "-", "like", "object", ".", "back_off", "=", "True", "provides", "retry" ]
a31ea2f40d20fd99d4c0938b87466330679db2c9
https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L109-L117
246,809
scraperwiki/data-services-helpers
dshelpers.py
_download_without_backoff
def _download_without_backoff(url, as_file=True, method='GET', **kwargs): """ Get the content of a URL and return a file-like object. """ # Make requests consistently hashable for caching. # 'headers' is handled by requests itself. # 'cookies' and 'proxies' contributes to headers. # 'files' and 'json' contribute to data. for k in ['data', 'params']: if k in kwargs and isinstance(kwargs[k], dict): kwargs[k] = OrderedDict(sorted(kwargs[k].items())) kwargs_copy = dict(kwargs) if not _is_url_in_cache(method, url, **kwargs): now = datetime.datetime.now() _rate_limit_for_url(url, now) _rate_limit_touch_url(url, now) L.info("Download {}".format(url)) if 'timeout' not in kwargs_copy: kwargs_copy['timeout'] = _TIMEOUT if 'headers' in kwargs_copy: head_dict = CaseInsensitiveDict(kwargs_copy['headers']) if 'user-agent' not in head_dict: head_dict['user-agent'] = _USER_AGENT kwargs_copy['headers'] = head_dict else: kwargs_copy['headers'] = CaseInsensitiveDict({'user-agent': _USER_AGENT}) response = requests.request(method, url, **kwargs_copy) if logging.getLogger().isEnabledFor(logging.DEBUG): # This can be slow on large responses, due to chardet. L.debug('"{}"'.format(response.text)) response.raise_for_status() if as_file: return BytesIO(response.content) else: return response
python
def _download_without_backoff(url, as_file=True, method='GET', **kwargs): """ Get the content of a URL and return a file-like object. """ # Make requests consistently hashable for caching. # 'headers' is handled by requests itself. # 'cookies' and 'proxies' contributes to headers. # 'files' and 'json' contribute to data. for k in ['data', 'params']: if k in kwargs and isinstance(kwargs[k], dict): kwargs[k] = OrderedDict(sorted(kwargs[k].items())) kwargs_copy = dict(kwargs) if not _is_url_in_cache(method, url, **kwargs): now = datetime.datetime.now() _rate_limit_for_url(url, now) _rate_limit_touch_url(url, now) L.info("Download {}".format(url)) if 'timeout' not in kwargs_copy: kwargs_copy['timeout'] = _TIMEOUT if 'headers' in kwargs_copy: head_dict = CaseInsensitiveDict(kwargs_copy['headers']) if 'user-agent' not in head_dict: head_dict['user-agent'] = _USER_AGENT kwargs_copy['headers'] = head_dict else: kwargs_copy['headers'] = CaseInsensitiveDict({'user-agent': _USER_AGENT}) response = requests.request(method, url, **kwargs_copy) if logging.getLogger().isEnabledFor(logging.DEBUG): # This can be slow on large responses, due to chardet. L.debug('"{}"'.format(response.text)) response.raise_for_status() if as_file: return BytesIO(response.content) else: return response
[ "def", "_download_without_backoff", "(", "url", ",", "as_file", "=", "True", ",", "method", "=", "'GET'", ",", "*", "*", "kwargs", ")", ":", "# Make requests consistently hashable for caching.", "# 'headers' is handled by requests itself.", "# 'cookies' and 'proxies' contributes to headers.", "# 'files' and 'json' contribute to data.", "for", "k", "in", "[", "'data'", ",", "'params'", "]", ":", "if", "k", "in", "kwargs", "and", "isinstance", "(", "kwargs", "[", "k", "]", ",", "dict", ")", ":", "kwargs", "[", "k", "]", "=", "OrderedDict", "(", "sorted", "(", "kwargs", "[", "k", "]", ".", "items", "(", ")", ")", ")", "kwargs_copy", "=", "dict", "(", "kwargs", ")", "if", "not", "_is_url_in_cache", "(", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "_rate_limit_for_url", "(", "url", ",", "now", ")", "_rate_limit_touch_url", "(", "url", ",", "now", ")", "L", ".", "info", "(", "\"Download {}\"", ".", "format", "(", "url", ")", ")", "if", "'timeout'", "not", "in", "kwargs_copy", ":", "kwargs_copy", "[", "'timeout'", "]", "=", "_TIMEOUT", "if", "'headers'", "in", "kwargs_copy", ":", "head_dict", "=", "CaseInsensitiveDict", "(", "kwargs_copy", "[", "'headers'", "]", ")", "if", "'user-agent'", "not", "in", "head_dict", ":", "head_dict", "[", "'user-agent'", "]", "=", "_USER_AGENT", "kwargs_copy", "[", "'headers'", "]", "=", "head_dict", "else", ":", "kwargs_copy", "[", "'headers'", "]", "=", "CaseInsensitiveDict", "(", "{", "'user-agent'", ":", "_USER_AGENT", "}", ")", "response", "=", "requests", ".", "request", "(", "method", ",", "url", ",", "*", "*", "kwargs_copy", ")", "if", "logging", ".", "getLogger", "(", ")", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "# This can be slow on large responses, due to chardet.", "L", ".", "debug", "(", "'\"{}\"'", ".", "format", "(", "response", ".", "text", ")", ")", "response", ".", "raise_for_status", "(", ")", "if", "as_file", ":", "return", "BytesIO", "(", "response", ".", "content", ")", "else", ":", "return", "response" ]
Get the content of a URL and return a file-like object.
[ "Get", "the", "content", "of", "a", "URL", "and", "return", "a", "file", "-", "like", "object", "." ]
a31ea2f40d20fd99d4c0938b87466330679db2c9
https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L137-L177
246,810
scraperwiki/data-services-helpers
dshelpers.py
_is_url_in_cache
def _is_url_in_cache(*args, **kwargs): """ Return True if request has been cached or False otherwise. """ # Only include allowed arguments for a PreparedRequest. allowed_args = inspect.getargspec( requests.models.PreparedRequest.prepare).args # self is in there as .prepare() is a method. allowed_args.remove('self') kwargs_cleaned = {} for key, value in dict(kwargs).items(): if key in allowed_args: kwargs_cleaned[key] = value prepared_request = _prepare(*args, **kwargs_cleaned) request_hash = _get_hash(prepared_request) try: return requests_cache.get_cache().has_key(request_hash) except AttributeError as e: # requests_cache not enabled if str(e) == "'Session' object has no attribute 'cache'": return False raise
python
def _is_url_in_cache(*args, **kwargs): """ Return True if request has been cached or False otherwise. """ # Only include allowed arguments for a PreparedRequest. allowed_args = inspect.getargspec( requests.models.PreparedRequest.prepare).args # self is in there as .prepare() is a method. allowed_args.remove('self') kwargs_cleaned = {} for key, value in dict(kwargs).items(): if key in allowed_args: kwargs_cleaned[key] = value prepared_request = _prepare(*args, **kwargs_cleaned) request_hash = _get_hash(prepared_request) try: return requests_cache.get_cache().has_key(request_hash) except AttributeError as e: # requests_cache not enabled if str(e) == "'Session' object has no attribute 'cache'": return False raise
[ "def", "_is_url_in_cache", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Only include allowed arguments for a PreparedRequest.", "allowed_args", "=", "inspect", ".", "getargspec", "(", "requests", ".", "models", ".", "PreparedRequest", ".", "prepare", ")", ".", "args", "# self is in there as .prepare() is a method.", "allowed_args", ".", "remove", "(", "'self'", ")", "kwargs_cleaned", "=", "{", "}", "for", "key", ",", "value", "in", "dict", "(", "kwargs", ")", ".", "items", "(", ")", ":", "if", "key", "in", "allowed_args", ":", "kwargs_cleaned", "[", "key", "]", "=", "value", "prepared_request", "=", "_prepare", "(", "*", "args", ",", "*", "*", "kwargs_cleaned", ")", "request_hash", "=", "_get_hash", "(", "prepared_request", ")", "try", ":", "return", "requests_cache", ".", "get_cache", "(", ")", ".", "has_key", "(", "request_hash", ")", "except", "AttributeError", "as", "e", ":", "# requests_cache not enabled", "if", "str", "(", "e", ")", "==", "\"'Session' object has no attribute 'cache'\"", ":", "return", "False", "raise" ]
Return True if request has been cached or False otherwise.
[ "Return", "True", "if", "request", "has", "been", "cached", "or", "False", "otherwise", "." ]
a31ea2f40d20fd99d4c0938b87466330679db2c9
https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L195-L215
246,811
ulf1/oxyba
oxyba/block_idxmat_sets.py
block_idxmat_sets
def block_idxmat_sets(idxmat, b): """Reshapes idxmat into the idx vectors for the training set and validation set Parameters: ----------- idxmat : ndarray Matrix with N shuffled row indicies assigned to K blocks/columns from the oxyba.block_idxmat_shuffle function b : int The id of the current validation block b=[0,1,...,K-1] Returns: -------- idx_train : ndarray Vector with row indicies of the current training blocks, i.e. all blocks [0,1,...,K-1] except the b-th block. The vector contains int(N/K)*(K-1) elements. idx_valid : ndarray Vector with row indicies of the current validation block "b". The vector contains int(N/K) elements. Example: -------- K = idxmat.shape[1] for b in range(K): idx_train, idx_valid = block_idxmat_sets(idxmat, b) ... """ import numpy as np idx_train = idxmat[:, [c for c in range(idxmat.shape[1]) if c is not b]] idx_train = idx_train.reshape((np.prod(idx_train.shape),)) return idx_train, idxmat[:, b]
python
def block_idxmat_sets(idxmat, b): """Reshapes idxmat into the idx vectors for the training set and validation set Parameters: ----------- idxmat : ndarray Matrix with N shuffled row indicies assigned to K blocks/columns from the oxyba.block_idxmat_shuffle function b : int The id of the current validation block b=[0,1,...,K-1] Returns: -------- idx_train : ndarray Vector with row indicies of the current training blocks, i.e. all blocks [0,1,...,K-1] except the b-th block. The vector contains int(N/K)*(K-1) elements. idx_valid : ndarray Vector with row indicies of the current validation block "b". The vector contains int(N/K) elements. Example: -------- K = idxmat.shape[1] for b in range(K): idx_train, idx_valid = block_idxmat_sets(idxmat, b) ... """ import numpy as np idx_train = idxmat[:, [c for c in range(idxmat.shape[1]) if c is not b]] idx_train = idx_train.reshape((np.prod(idx_train.shape),)) return idx_train, idxmat[:, b]
[ "def", "block_idxmat_sets", "(", "idxmat", ",", "b", ")", ":", "import", "numpy", "as", "np", "idx_train", "=", "idxmat", "[", ":", ",", "[", "c", "for", "c", "in", "range", "(", "idxmat", ".", "shape", "[", "1", "]", ")", "if", "c", "is", "not", "b", "]", "]", "idx_train", "=", "idx_train", ".", "reshape", "(", "(", "np", ".", "prod", "(", "idx_train", ".", "shape", ")", ",", ")", ")", "return", "idx_train", ",", "idxmat", "[", ":", ",", "b", "]" ]
Reshapes idxmat into the idx vectors for the training set and validation set Parameters: ----------- idxmat : ndarray Matrix with N shuffled row indicies assigned to K blocks/columns from the oxyba.block_idxmat_shuffle function b : int The id of the current validation block b=[0,1,...,K-1] Returns: -------- idx_train : ndarray Vector with row indicies of the current training blocks, i.e. all blocks [0,1,...,K-1] except the b-th block. The vector contains int(N/K)*(K-1) elements. idx_valid : ndarray Vector with row indicies of the current validation block "b". The vector contains int(N/K) elements. Example: -------- K = idxmat.shape[1] for b in range(K): idx_train, idx_valid = block_idxmat_sets(idxmat, b) ...
[ "Reshapes", "idxmat", "into", "the", "idx", "vectors", "for", "the", "training", "set", "and", "validation", "set" ]
b3043116050de275124365cb11e7df91fb40169d
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/block_idxmat_sets.py#L2-L35
246,812
markpasc/arghlog
arghlog.py
add_logging
def add_logging(parser, log_format=LOG_FORMAT, log_level=LOG_LEVEL, color=True): """Configures the `argparse.ArgumentParser` with arguments to configure logging. This adds arguments: * ``-v`` to increase the log level * ``-q`` to decrease the log level * ``--color`` to enable color logging when available * ``--no-color`` to disable color logging The root logger is configured with the given format and log level. ANSI color codes are supported in the logging format string. If color is enabled and stderr is a tty, the codes will be passed through. Otherwise the logging formatter will strip them out. The logging format supports these additional format variables for coloration: %(levelcolor)s If stderr is a terminal, an ANSI color code appropriate for the level of the logged record. %(resetcolor)s If stderr is a terminal, an ANSI color reset code. """ parser.set_defaults(log_level=log_level) parser.add_argument('-v', dest='log_level', action=_LogLevelAddAction, const=1, help='use more verbose logging (stackable)') parser.add_argument('-q', dest='log_level', action=_LogLevelAddAction, const=-1, help='use less verbose logging (stackable)') root_logger = logging.getLogger() root_logger.setLevel(log_level) handler = logging.StreamHandler() # using sys.stderr if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): class ColorAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, True) handler.setFormatter(_ColorLogFormatter(log_format)) class NoColorAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, False) handler.setFormatter(_NoColorLogFormatter(log_format)) parser.add_argument('--color', dest='color', action=ColorAction, nargs=0, help='use color in log (when available)') parser.add_argument('--no-color', dest='color', action=NoColorAction, nargs=0, help='use no color in log') if color: formatter_class = _ColorLogFormatter else: formatter_class = _NoColorLogFormatter else: # Make the options available, but they don't do anything. parser.add_argument('--color', dest='color', action='store_true', help='use color in log (when available)') parser.add_argument('--no-color', dest='color', action='store_false', help='use no color in log') formatter_class = _NoColorLogFormatter handler.setFormatter(formatter_class(log_format)) root_logger.addHandler(handler)
python
def add_logging(parser, log_format=LOG_FORMAT, log_level=LOG_LEVEL, color=True): """Configures the `argparse.ArgumentParser` with arguments to configure logging. This adds arguments: * ``-v`` to increase the log level * ``-q`` to decrease the log level * ``--color`` to enable color logging when available * ``--no-color`` to disable color logging The root logger is configured with the given format and log level. ANSI color codes are supported in the logging format string. If color is enabled and stderr is a tty, the codes will be passed through. Otherwise the logging formatter will strip them out. The logging format supports these additional format variables for coloration: %(levelcolor)s If stderr is a terminal, an ANSI color code appropriate for the level of the logged record. %(resetcolor)s If stderr is a terminal, an ANSI color reset code. """ parser.set_defaults(log_level=log_level) parser.add_argument('-v', dest='log_level', action=_LogLevelAddAction, const=1, help='use more verbose logging (stackable)') parser.add_argument('-q', dest='log_level', action=_LogLevelAddAction, const=-1, help='use less verbose logging (stackable)') root_logger = logging.getLogger() root_logger.setLevel(log_level) handler = logging.StreamHandler() # using sys.stderr if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): class ColorAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, True) handler.setFormatter(_ColorLogFormatter(log_format)) class NoColorAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, False) handler.setFormatter(_NoColorLogFormatter(log_format)) parser.add_argument('--color', dest='color', action=ColorAction, nargs=0, help='use color in log (when available)') parser.add_argument('--no-color', dest='color', action=NoColorAction, nargs=0, help='use no color in log') if color: formatter_class = _ColorLogFormatter else: formatter_class = _NoColorLogFormatter else: # Make the options available, but they don't do anything. parser.add_argument('--color', dest='color', action='store_true', help='use color in log (when available)') parser.add_argument('--no-color', dest='color', action='store_false', help='use no color in log') formatter_class = _NoColorLogFormatter handler.setFormatter(formatter_class(log_format)) root_logger.addHandler(handler)
[ "def", "add_logging", "(", "parser", ",", "log_format", "=", "LOG_FORMAT", ",", "log_level", "=", "LOG_LEVEL", ",", "color", "=", "True", ")", ":", "parser", ".", "set_defaults", "(", "log_level", "=", "log_level", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "dest", "=", "'log_level'", ",", "action", "=", "_LogLevelAddAction", ",", "const", "=", "1", ",", "help", "=", "'use more verbose logging (stackable)'", ")", "parser", ".", "add_argument", "(", "'-q'", ",", "dest", "=", "'log_level'", ",", "action", "=", "_LogLevelAddAction", ",", "const", "=", "-", "1", ",", "help", "=", "'use less verbose logging (stackable)'", ")", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "root_logger", ".", "setLevel", "(", "log_level", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "# using sys.stderr", "if", "hasattr", "(", "sys", ".", "stderr", ",", "'isatty'", ")", "and", "sys", ".", "stderr", ".", "isatty", "(", ")", ":", "class", "ColorAction", "(", "argparse", ".", "Action", ")", ":", "def", "__call__", "(", "self", ",", "parser", ",", "namespace", ",", "values", ",", "option_string", "=", "None", ")", ":", "setattr", "(", "namespace", ",", "self", ".", "dest", ",", "True", ")", "handler", ".", "setFormatter", "(", "_ColorLogFormatter", "(", "log_format", ")", ")", "class", "NoColorAction", "(", "argparse", ".", "Action", ")", ":", "def", "__call__", "(", "self", ",", "parser", ",", "namespace", ",", "values", ",", "option_string", "=", "None", ")", ":", "setattr", "(", "namespace", ",", "self", ".", "dest", ",", "False", ")", "handler", ".", "setFormatter", "(", "_NoColorLogFormatter", "(", "log_format", ")", ")", "parser", ".", "add_argument", "(", "'--color'", ",", "dest", "=", "'color'", ",", "action", "=", "ColorAction", ",", "nargs", "=", "0", ",", "help", "=", "'use color in log (when available)'", ")", "parser", ".", "add_argument", "(", "'--no-color'", ",", "dest", "=", "'color'", ",", "action", "=", "NoColorAction", ",", "nargs", "=", "0", ",", "help", "=", "'use no color in log'", ")", "if", "color", ":", "formatter_class", "=", "_ColorLogFormatter", "else", ":", "formatter_class", "=", "_NoColorLogFormatter", "else", ":", "# Make the options available, but they don't do anything.", "parser", ".", "add_argument", "(", "'--color'", ",", "dest", "=", "'color'", ",", "action", "=", "'store_true'", ",", "help", "=", "'use color in log (when available)'", ")", "parser", ".", "add_argument", "(", "'--no-color'", ",", "dest", "=", "'color'", ",", "action", "=", "'store_false'", ",", "help", "=", "'use no color in log'", ")", "formatter_class", "=", "_NoColorLogFormatter", "handler", ".", "setFormatter", "(", "formatter_class", "(", "log_format", ")", ")", "root_logger", ".", "addHandler", "(", "handler", ")" ]
Configures the `argparse.ArgumentParser` with arguments to configure logging. This adds arguments: * ``-v`` to increase the log level * ``-q`` to decrease the log level * ``--color`` to enable color logging when available * ``--no-color`` to disable color logging The root logger is configured with the given format and log level. ANSI color codes are supported in the logging format string. If color is enabled and stderr is a tty, the codes will be passed through. Otherwise the logging formatter will strip them out. The logging format supports these additional format variables for coloration: %(levelcolor)s If stderr is a terminal, an ANSI color code appropriate for the level of the logged record. %(resetcolor)s If stderr is a terminal, an ANSI color reset code.
[ "Configures", "the", "argparse", ".", "ArgumentParser", "with", "arguments", "to", "configure", "logging", "." ]
268c5936922b6b5e1f91acaf0390c1bf85d90dd9
https://github.com/markpasc/arghlog/blob/268c5936922b6b5e1f91acaf0390c1bf85d90dd9/arghlog.py#L77-L133
246,813
amcfague/webunit2
webunit2/response.py
HttpResponse.assertHeader
def assertHeader(self, name, value=None, *args, **kwargs): """ Returns `True` if ``name`` was in the headers and, if ``value`` is True, whether or not the values match, or `False` otherwise. """ return name in self.raw_headers and ( True if value is None else self.raw_headers[name] == value)
python
def assertHeader(self, name, value=None, *args, **kwargs): """ Returns `True` if ``name`` was in the headers and, if ``value`` is True, whether or not the values match, or `False` otherwise. """ return name in self.raw_headers and ( True if value is None else self.raw_headers[name] == value)
[ "def", "assertHeader", "(", "self", ",", "name", ",", "value", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "name", "in", "self", ".", "raw_headers", "and", "(", "True", "if", "value", "is", "None", "else", "self", ".", "raw_headers", "[", "name", "]", "==", "value", ")" ]
Returns `True` if ``name`` was in the headers and, if ``value`` is True, whether or not the values match, or `False` otherwise.
[ "Returns", "True", "if", "name", "was", "in", "the", "headers", "and", "if", "value", "is", "True", "whether", "or", "not", "the", "values", "match", "or", "False", "otherwise", "." ]
3157e5837aad0810800628c1383f1fe11ee3e513
https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/response.py#L59-L65
246,814
cirruscluster/cirruscluster
cirruscluster/cluster/mapr.py
MaprCluster.ConfigureLazyWorkers
def ConfigureLazyWorkers(self): """ Lazy workers are instances that are running and reachable but failed to register with the cldb to join the mapr cluster. This trys to find these missing workers and add them to the cluster. """ lazy_worker_instances = self.__GetMissingWorkers() if not lazy_worker_instances: return reachable_states = self.__AreInstancesReachable(lazy_worker_instances) reachable_instances = [t[0] for t in zip(lazy_worker_instances, reachable_states) if t[1]] print 'reachable_instances: %s' % reachable_instances self.__ConfigureWorkers(reachable_instances) return
python
def ConfigureLazyWorkers(self): """ Lazy workers are instances that are running and reachable but failed to register with the cldb to join the mapr cluster. This trys to find these missing workers and add them to the cluster. """ lazy_worker_instances = self.__GetMissingWorkers() if not lazy_worker_instances: return reachable_states = self.__AreInstancesReachable(lazy_worker_instances) reachable_instances = [t[0] for t in zip(lazy_worker_instances, reachable_states) if t[1]] print 'reachable_instances: %s' % reachable_instances self.__ConfigureWorkers(reachable_instances) return
[ "def", "ConfigureLazyWorkers", "(", "self", ")", ":", "lazy_worker_instances", "=", "self", ".", "__GetMissingWorkers", "(", ")", "if", "not", "lazy_worker_instances", ":", "return", "reachable_states", "=", "self", ".", "__AreInstancesReachable", "(", "lazy_worker_instances", ")", "reachable_instances", "=", "[", "t", "[", "0", "]", "for", "t", "in", "zip", "(", "lazy_worker_instances", ",", "reachable_states", ")", "if", "t", "[", "1", "]", "]", "print", "'reachable_instances: %s'", "%", "reachable_instances", "self", ".", "__ConfigureWorkers", "(", "reachable_instances", ")", "return" ]
Lazy workers are instances that are running and reachable but failed to register with the cldb to join the mapr cluster. This trys to find these missing workers and add them to the cluster.
[ "Lazy", "workers", "are", "instances", "that", "are", "running", "and", "reachable", "but", "failed", "to", "register", "with", "the", "cldb", "to", "join", "the", "mapr", "cluster", ".", "This", "trys", "to", "find", "these", "missing", "workers", "and", "add", "them", "to", "the", "cluster", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L289-L301
246,815
cirruscluster/cirruscluster
cirruscluster/cluster/mapr.py
MaprCluster.__StartMaster
def __StartMaster(self): """ Starts a master node, configures it, and starts services. """ num_masters = len(self.cluster.get_instances_in_role("master", "running")) assert(num_masters < 1) logging.info( "waiting for masters to start") if self.config.master_on_spot_instances: self.__LaunchSpotMasterInstances() else: self.__LaunchOnDemandMasterInstances() time.sleep(1) self.__ConfigureMaster() return True
python
def __StartMaster(self): """ Starts a master node, configures it, and starts services. """ num_masters = len(self.cluster.get_instances_in_role("master", "running")) assert(num_masters < 1) logging.info( "waiting for masters to start") if self.config.master_on_spot_instances: self.__LaunchSpotMasterInstances() else: self.__LaunchOnDemandMasterInstances() time.sleep(1) self.__ConfigureMaster() return True
[ "def", "__StartMaster", "(", "self", ")", ":", "num_masters", "=", "len", "(", "self", ".", "cluster", ".", "get_instances_in_role", "(", "\"master\"", ",", "\"running\"", ")", ")", "assert", "(", "num_masters", "<", "1", ")", "logging", ".", "info", "(", "\"waiting for masters to start\"", ")", "if", "self", ".", "config", ".", "master_on_spot_instances", ":", "self", ".", "__LaunchSpotMasterInstances", "(", ")", "else", ":", "self", ".", "__LaunchOnDemandMasterInstances", "(", ")", "time", ".", "sleep", "(", "1", ")", "self", ".", "__ConfigureMaster", "(", ")", "return", "True" ]
Starts a master node, configures it, and starts services.
[ "Starts", "a", "master", "node", "configures", "it", "and", "starts", "services", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L365-L376
246,816
cirruscluster/cirruscluster
cirruscluster/cluster/mapr.py
MaprCluster.__AddWorkers
def __AddWorkers(self, num_to_add): """ Adds workers evenly across all enabled zones.""" # Check preconditions assert(self.__IsWebUiReady()) zone_to_ips = self.__GetZoneToWorkerIpsTable() zone_old_new = [] for zone, ips in zone_to_ips.iteritems(): num_nodes_in_zone = len(ips) num_nodes_to_add = 0 zone_old_new.append((zone, num_nodes_in_zone, num_nodes_to_add)) print 'num_to_add %s' % num_to_add for _ in range(num_to_add): zone_old_new.sort(key= lambda z : z[1]+z[2]) zt = zone_old_new[0] zone_old_new[0] = (zt[0], zt[1], zt[2]+1) #print zone_old_new zone_plan = [(zt[2], zt[0]) for zt in zone_old_new] print 'resize plan' if self.config.workers_on_spot_instances: new_worker_instances = self.__LaunchSpotWorkerInstances(zone_plan) else: new_worker_instances = self.__LaunchOnDemandWorkerInstances(zone_plan) self.__WaitForInstancesReachable(new_worker_instances) self.__ConfigureWorkers(new_worker_instances) return
python
def __AddWorkers(self, num_to_add): """ Adds workers evenly across all enabled zones.""" # Check preconditions assert(self.__IsWebUiReady()) zone_to_ips = self.__GetZoneToWorkerIpsTable() zone_old_new = [] for zone, ips in zone_to_ips.iteritems(): num_nodes_in_zone = len(ips) num_nodes_to_add = 0 zone_old_new.append((zone, num_nodes_in_zone, num_nodes_to_add)) print 'num_to_add %s' % num_to_add for _ in range(num_to_add): zone_old_new.sort(key= lambda z : z[1]+z[2]) zt = zone_old_new[0] zone_old_new[0] = (zt[0], zt[1], zt[2]+1) #print zone_old_new zone_plan = [(zt[2], zt[0]) for zt in zone_old_new] print 'resize plan' if self.config.workers_on_spot_instances: new_worker_instances = self.__LaunchSpotWorkerInstances(zone_plan) else: new_worker_instances = self.__LaunchOnDemandWorkerInstances(zone_plan) self.__WaitForInstancesReachable(new_worker_instances) self.__ConfigureWorkers(new_worker_instances) return
[ "def", "__AddWorkers", "(", "self", ",", "num_to_add", ")", ":", "# Check preconditions", "assert", "(", "self", ".", "__IsWebUiReady", "(", ")", ")", "zone_to_ips", "=", "self", ".", "__GetZoneToWorkerIpsTable", "(", ")", "zone_old_new", "=", "[", "]", "for", "zone", ",", "ips", "in", "zone_to_ips", ".", "iteritems", "(", ")", ":", "num_nodes_in_zone", "=", "len", "(", "ips", ")", "num_nodes_to_add", "=", "0", "zone_old_new", ".", "append", "(", "(", "zone", ",", "num_nodes_in_zone", ",", "num_nodes_to_add", ")", ")", "print", "'num_to_add %s'", "%", "num_to_add", "for", "_", "in", "range", "(", "num_to_add", ")", ":", "zone_old_new", ".", "sort", "(", "key", "=", "lambda", "z", ":", "z", "[", "1", "]", "+", "z", "[", "2", "]", ")", "zt", "=", "zone_old_new", "[", "0", "]", "zone_old_new", "[", "0", "]", "=", "(", "zt", "[", "0", "]", ",", "zt", "[", "1", "]", ",", "zt", "[", "2", "]", "+", "1", ")", "#print zone_old_new", "zone_plan", "=", "[", "(", "zt", "[", "2", "]", ",", "zt", "[", "0", "]", ")", "for", "zt", "in", "zone_old_new", "]", "print", "'resize plan'", "if", "self", ".", "config", ".", "workers_on_spot_instances", ":", "new_worker_instances", "=", "self", ".", "__LaunchSpotWorkerInstances", "(", "zone_plan", ")", "else", ":", "new_worker_instances", "=", "self", ".", "__LaunchOnDemandWorkerInstances", "(", "zone_plan", ")", "self", ".", "__WaitForInstancesReachable", "(", "new_worker_instances", ")", "self", ".", "__ConfigureWorkers", "(", "new_worker_instances", ")", "return" ]
Adds workers evenly across all enabled zones.
[ "Adds", "workers", "evenly", "across", "all", "enabled", "zones", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L536-L560
246,817
cirruscluster/cirruscluster
cirruscluster/cluster/mapr.py
MaprCluster.__IpsToServerIds
def __IpsToServerIds(self): """ Get list of mapping of ip address into a server id""" master_instance = self.__GetMasterInstance() assert(master_instance) retval, response = self.__RunMaprCli('node list -columns id') ip_to_id = {} for line_num, line in enumerate(response.split('\n')): tokens = line.split() if len(tokens) == 3 and tokens[0] != 'id': instance_id = tokens[0] ip = tokens[2] ip_to_id[ip] = instance_id return ip_to_id
python
def __IpsToServerIds(self): """ Get list of mapping of ip address into a server id""" master_instance = self.__GetMasterInstance() assert(master_instance) retval, response = self.__RunMaprCli('node list -columns id') ip_to_id = {} for line_num, line in enumerate(response.split('\n')): tokens = line.split() if len(tokens) == 3 and tokens[0] != 'id': instance_id = tokens[0] ip = tokens[2] ip_to_id[ip] = instance_id return ip_to_id
[ "def", "__IpsToServerIds", "(", "self", ")", ":", "master_instance", "=", "self", ".", "__GetMasterInstance", "(", ")", "assert", "(", "master_instance", ")", "retval", ",", "response", "=", "self", ".", "__RunMaprCli", "(", "'node list -columns id'", ")", "ip_to_id", "=", "{", "}", "for", "line_num", ",", "line", "in", "enumerate", "(", "response", ".", "split", "(", "'\\n'", ")", ")", ":", "tokens", "=", "line", ".", "split", "(", ")", "if", "len", "(", "tokens", ")", "==", "3", "and", "tokens", "[", "0", "]", "!=", "'id'", ":", "instance_id", "=", "tokens", "[", "0", "]", "ip", "=", "tokens", "[", "2", "]", "ip_to_id", "[", "ip", "]", "=", "instance_id", "return", "ip_to_id" ]
Get list of mapping of ip address into a server id
[ "Get", "list", "of", "mapping", "of", "ip", "address", "into", "a", "server", "id" ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L995-L1007
246,818
mrallen1/pygett
pygett/files.py
GettFile.contents
def contents(self): """ This method downloads the contents of the file represented by a `GettFile` object's metadata. Input: * None Output: * A byte stream **NOTE**: You are responsible for handling any encoding/decoding which may be necessary. Example:: file = client.get_file("4ddfds", 0) print file.contents() """ response = GettRequest().get("/files/%s/%s/blob" % (self.sharename, self.fileid)) return response.response
python
def contents(self): """ This method downloads the contents of the file represented by a `GettFile` object's metadata. Input: * None Output: * A byte stream **NOTE**: You are responsible for handling any encoding/decoding which may be necessary. Example:: file = client.get_file("4ddfds", 0) print file.contents() """ response = GettRequest().get("/files/%s/%s/blob" % (self.sharename, self.fileid)) return response.response
[ "def", "contents", "(", "self", ")", ":", "response", "=", "GettRequest", "(", ")", ".", "get", "(", "\"/files/%s/%s/blob\"", "%", "(", "self", ".", "sharename", ",", "self", ".", "fileid", ")", ")", "return", "response", ".", "response" ]
This method downloads the contents of the file represented by a `GettFile` object's metadata. Input: * None Output: * A byte stream **NOTE**: You are responsible for handling any encoding/decoding which may be necessary. Example:: file = client.get_file("4ddfds", 0) print file.contents()
[ "This", "method", "downloads", "the", "contents", "of", "the", "file", "represented", "by", "a", "GettFile", "object", "s", "metadata", "." ]
1e21f8674a3634a901af054226670174b5ce2d87
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L48-L67
246,819
mrallen1/pygett
pygett/files.py
GettFile.thumbnail
def thumbnail(self): """ This method returns a thumbnail representation of the file if the data is a supported graphics format. Input: * None Output: * A byte stream representing a thumbnail of a support graphics file Example:: file = client.get_file("4ddfds", 0) open("thumbnail.jpg", "wb").write(file.thumbnail()) """ response = GettRequest().get("/files/%s/%s/blob/thumb" % (self.sharename, self.fileid)) return response.response
python
def thumbnail(self): """ This method returns a thumbnail representation of the file if the data is a supported graphics format. Input: * None Output: * A byte stream representing a thumbnail of a support graphics file Example:: file = client.get_file("4ddfds", 0) open("thumbnail.jpg", "wb").write(file.thumbnail()) """ response = GettRequest().get("/files/%s/%s/blob/thumb" % (self.sharename, self.fileid)) return response.response
[ "def", "thumbnail", "(", "self", ")", ":", "response", "=", "GettRequest", "(", ")", ".", "get", "(", "\"/files/%s/%s/blob/thumb\"", "%", "(", "self", ".", "sharename", ",", "self", ".", "fileid", ")", ")", "return", "response", ".", "response" ]
This method returns a thumbnail representation of the file if the data is a supported graphics format. Input: * None Output: * A byte stream representing a thumbnail of a support graphics file Example:: file = client.get_file("4ddfds", 0) open("thumbnail.jpg", "wb").write(file.thumbnail())
[ "This", "method", "returns", "a", "thumbnail", "representation", "of", "the", "file", "if", "the", "data", "is", "a", "supported", "graphics", "format", "." ]
1e21f8674a3634a901af054226670174b5ce2d87
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L69-L86
246,820
mrallen1/pygett
pygett/files.py
GettFile.send_data
def send_data(self, **kwargs): """ This method transmits data to the Gett service. Input: * ``put_url`` A PUT url to use when transmitting the data (required) * ``data`` A byte stream (required) Output: * ``True`` Example:: if file.send_data(put_url=file.upload_url, data=open("example.txt", "rb").read()): print "Your file has been uploaded." """ put_url = None if 'put_url' in kwargs: put_url = kwargs['put_url'] else: put_url = self.put_upload_url if 'data' not in kwargs: raise AttributeError("'data' parameter is required") if not put_url: raise AttributeError("'put_url' cannot be None") if not isinstance(kwargs['data'], str): raise TypeError("'data' parameter must be of type 'str'") response = GettRequest().put(put_url, kwargs['data']) if response.http_status == 200: return True
python
def send_data(self, **kwargs): """ This method transmits data to the Gett service. Input: * ``put_url`` A PUT url to use when transmitting the data (required) * ``data`` A byte stream (required) Output: * ``True`` Example:: if file.send_data(put_url=file.upload_url, data=open("example.txt", "rb").read()): print "Your file has been uploaded." """ put_url = None if 'put_url' in kwargs: put_url = kwargs['put_url'] else: put_url = self.put_upload_url if 'data' not in kwargs: raise AttributeError("'data' parameter is required") if not put_url: raise AttributeError("'put_url' cannot be None") if not isinstance(kwargs['data'], str): raise TypeError("'data' parameter must be of type 'str'") response = GettRequest().put(put_url, kwargs['data']) if response.http_status == 200: return True
[ "def", "send_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "put_url", "=", "None", "if", "'put_url'", "in", "kwargs", ":", "put_url", "=", "kwargs", "[", "'put_url'", "]", "else", ":", "put_url", "=", "self", ".", "put_upload_url", "if", "'data'", "not", "in", "kwargs", ":", "raise", "AttributeError", "(", "\"'data' parameter is required\"", ")", "if", "not", "put_url", ":", "raise", "AttributeError", "(", "\"'put_url' cannot be None\"", ")", "if", "not", "isinstance", "(", "kwargs", "[", "'data'", "]", ",", "str", ")", ":", "raise", "TypeError", "(", "\"'data' parameter must be of type 'str'\"", ")", "response", "=", "GettRequest", "(", ")", ".", "put", "(", "put_url", ",", "kwargs", "[", "'data'", "]", ")", "if", "response", ".", "http_status", "==", "200", ":", "return", "True" ]
This method transmits data to the Gett service. Input: * ``put_url`` A PUT url to use when transmitting the data (required) * ``data`` A byte stream (required) Output: * ``True`` Example:: if file.send_data(put_url=file.upload_url, data=open("example.txt", "rb").read()): print "Your file has been uploaded."
[ "This", "method", "transmits", "data", "to", "the", "Gett", "service", "." ]
1e21f8674a3634a901af054226670174b5ce2d87
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L155-L189
246,821
spookey/photon
photon/tools/signal.py
Signal.__signal
def __signal(self, sig, verbose=None): ''' Helper class preventing code duplication.. :param sig: Signal to use (e.g. "HUP", "ALRM") :param verbose: Overwrite :func:`photon.Photon.m`'s `verbose` :returns: |kill_return| with specified `pid` .. |kill_return| replace:: :func:`photon.Photon.m`'s result of killing `pid` .. |kill_verbose| replace:: with visible shell warning ''' return self.m( 'killing process %s with "%s"' % (self.__pid, sig), cmdd=dict(cmd='%s kill -%s %d' % (self.__sudo, sig, self.__pid)), verbose=verbose )
python
def __signal(self, sig, verbose=None): ''' Helper class preventing code duplication.. :param sig: Signal to use (e.g. "HUP", "ALRM") :param verbose: Overwrite :func:`photon.Photon.m`'s `verbose` :returns: |kill_return| with specified `pid` .. |kill_return| replace:: :func:`photon.Photon.m`'s result of killing `pid` .. |kill_verbose| replace:: with visible shell warning ''' return self.m( 'killing process %s with "%s"' % (self.__pid, sig), cmdd=dict(cmd='%s kill -%s %d' % (self.__sudo, sig, self.__pid)), verbose=verbose )
[ "def", "__signal", "(", "self", ",", "sig", ",", "verbose", "=", "None", ")", ":", "return", "self", ".", "m", "(", "'killing process %s with \"%s\"'", "%", "(", "self", ".", "__pid", ",", "sig", ")", ",", "cmdd", "=", "dict", "(", "cmd", "=", "'%s kill -%s %d'", "%", "(", "self", ".", "__sudo", ",", "sig", ",", "self", ".", "__pid", ")", ")", ",", "verbose", "=", "verbose", ")" ]
Helper class preventing code duplication.. :param sig: Signal to use (e.g. "HUP", "ALRM") :param verbose: Overwrite :func:`photon.Photon.m`'s `verbose` :returns: |kill_return| with specified `pid` .. |kill_return| replace:: :func:`photon.Photon.m`'s result of killing `pid` .. |kill_verbose| replace:: with visible shell warning
[ "Helper", "class", "preventing", "code", "duplication", ".." ]
57212a26ce713ab7723910ee49e3d0ba1697799f
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/tools/signal.py#L56-L75
246,822
ulf1/oxyba
oxyba/linreg_mle.py
linreg_mle
def linreg_mle(y, X, algorithm='Nelder-Mead', debug=False): """MLE for Linear Regression Model Parameters: ----------- y : ndarray target variable with N observations X : ndarray The <N x C> design matrix with C independent variables, features, factors, etc. algorithm : str Optional. Default 'Nelder-Mead' (Simplex). The algorithm used in scipy.optimize.minimize debug : bool Optional. Returns: -------- beta : ndarray Estimated regression coefficients. results : scipy.optimize.optimize.OptimizeResult Optional. If debug=True then only scipy's optimization result variable is returned. """ import numpy as np import scipy.stats as sstat import scipy.optimize as sopt def objective_nll_linreg(theta, y, X): yhat = np.dot(X, theta[:-1]) # =X*beta return -1.0 * sstat.norm.logpdf(y, loc=yhat, scale=theta[-1]).sum() # check eligible algorithm if algorithm not in ('Nelder-Mead', 'CG', 'BFGS'): raise Exception('Optimization Algorithm not supported.') # set start values theta0 = np.ones((X.shape[1] + 1, )) # run solver results = sopt.minimize( objective_nll_linreg, theta0, args=(y, X), method=algorithm, options={'disp': False}) # debug? if debug: return results # done return results.x[:-1]
python
def linreg_mle(y, X, algorithm='Nelder-Mead', debug=False): """MLE for Linear Regression Model Parameters: ----------- y : ndarray target variable with N observations X : ndarray The <N x C> design matrix with C independent variables, features, factors, etc. algorithm : str Optional. Default 'Nelder-Mead' (Simplex). The algorithm used in scipy.optimize.minimize debug : bool Optional. Returns: -------- beta : ndarray Estimated regression coefficients. results : scipy.optimize.optimize.OptimizeResult Optional. If debug=True then only scipy's optimization result variable is returned. """ import numpy as np import scipy.stats as sstat import scipy.optimize as sopt def objective_nll_linreg(theta, y, X): yhat = np.dot(X, theta[:-1]) # =X*beta return -1.0 * sstat.norm.logpdf(y, loc=yhat, scale=theta[-1]).sum() # check eligible algorithm if algorithm not in ('Nelder-Mead', 'CG', 'BFGS'): raise Exception('Optimization Algorithm not supported.') # set start values theta0 = np.ones((X.shape[1] + 1, )) # run solver results = sopt.minimize( objective_nll_linreg, theta0, args=(y, X), method=algorithm, options={'disp': False}) # debug? if debug: return results # done return results.x[:-1]
[ "def", "linreg_mle", "(", "y", ",", "X", ",", "algorithm", "=", "'Nelder-Mead'", ",", "debug", "=", "False", ")", ":", "import", "numpy", "as", "np", "import", "scipy", ".", "stats", "as", "sstat", "import", "scipy", ".", "optimize", "as", "sopt", "def", "objective_nll_linreg", "(", "theta", ",", "y", ",", "X", ")", ":", "yhat", "=", "np", ".", "dot", "(", "X", ",", "theta", "[", ":", "-", "1", "]", ")", "# =X*beta", "return", "-", "1.0", "*", "sstat", ".", "norm", ".", "logpdf", "(", "y", ",", "loc", "=", "yhat", ",", "scale", "=", "theta", "[", "-", "1", "]", ")", ".", "sum", "(", ")", "# check eligible algorithm", "if", "algorithm", "not", "in", "(", "'Nelder-Mead'", ",", "'CG'", ",", "'BFGS'", ")", ":", "raise", "Exception", "(", "'Optimization Algorithm not supported.'", ")", "# set start values", "theta0", "=", "np", ".", "ones", "(", "(", "X", ".", "shape", "[", "1", "]", "+", "1", ",", ")", ")", "# run solver", "results", "=", "sopt", ".", "minimize", "(", "objective_nll_linreg", ",", "theta0", ",", "args", "=", "(", "y", ",", "X", ")", ",", "method", "=", "algorithm", ",", "options", "=", "{", "'disp'", ":", "False", "}", ")", "# debug?", "if", "debug", ":", "return", "results", "# done", "return", "results", ".", "x", "[", ":", "-", "1", "]" ]
MLE for Linear Regression Model Parameters: ----------- y : ndarray target variable with N observations X : ndarray The <N x C> design matrix with C independent variables, features, factors, etc. algorithm : str Optional. Default 'Nelder-Mead' (Simplex). The algorithm used in scipy.optimize.minimize debug : bool Optional. Returns: -------- beta : ndarray Estimated regression coefficients. results : scipy.optimize.optimize.OptimizeResult Optional. If debug=True then only scipy's optimization result variable is returned.
[ "MLE", "for", "Linear", "Regression", "Model" ]
b3043116050de275124365cb11e7df91fb40169d
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/linreg_mle.py#L2-L59
246,823
delfick/gitmit
gitmit/prefix_tree.py
PrefixTree.fill
def fill(self, paths): """ Initialise the tree. paths is a list of strings where each string is the relative path to some file. """ for path in paths: tree = self.tree parts = tuple(path.split('/')) dir_parts = parts[:-1] built = () for part in dir_parts: self.cache[built] = tree built += (part, ) parent = tree tree = parent.folders.get(part, empty) if tree is empty: tree = parent.folders[part] = TreeItem(name=built, folders={}, files=set(), parent=parent) self.cache[dir_parts] = tree tree.files.add(parts[-1])
python
def fill(self, paths): """ Initialise the tree. paths is a list of strings where each string is the relative path to some file. """ for path in paths: tree = self.tree parts = tuple(path.split('/')) dir_parts = parts[:-1] built = () for part in dir_parts: self.cache[built] = tree built += (part, ) parent = tree tree = parent.folders.get(part, empty) if tree is empty: tree = parent.folders[part] = TreeItem(name=built, folders={}, files=set(), parent=parent) self.cache[dir_parts] = tree tree.files.add(parts[-1])
[ "def", "fill", "(", "self", ",", "paths", ")", ":", "for", "path", "in", "paths", ":", "tree", "=", "self", ".", "tree", "parts", "=", "tuple", "(", "path", ".", "split", "(", "'/'", ")", ")", "dir_parts", "=", "parts", "[", ":", "-", "1", "]", "built", "=", "(", ")", "for", "part", "in", "dir_parts", ":", "self", ".", "cache", "[", "built", "]", "=", "tree", "built", "+=", "(", "part", ",", ")", "parent", "=", "tree", "tree", "=", "parent", ".", "folders", ".", "get", "(", "part", ",", "empty", ")", "if", "tree", "is", "empty", ":", "tree", "=", "parent", ".", "folders", "[", "part", "]", "=", "TreeItem", "(", "name", "=", "built", ",", "folders", "=", "{", "}", ",", "files", "=", "set", "(", ")", ",", "parent", "=", "parent", ")", "self", ".", "cache", "[", "dir_parts", "]", "=", "tree", "tree", ".", "files", ".", "add", "(", "parts", "[", "-", "1", "]", ")" ]
Initialise the tree. paths is a list of strings where each string is the relative path to some file.
[ "Initialise", "the", "tree", "." ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L59-L80
246,824
delfick/gitmit
gitmit/prefix_tree.py
PrefixTree.remove
def remove(self, prefix, name): """ Remove a path from the tree prefix is a tuple of the parts in the dirpath name is a string representing the name of the file itself. Any empty folders from the point of the file backwards to the root of the tree is removed. """ tree = self.cache.get(prefix, empty) if tree is empty: return False if name not in tree.files: return False tree.files.remove(name) self.remove_folder(tree, list(prefix)) return True
python
def remove(self, prefix, name): """ Remove a path from the tree prefix is a tuple of the parts in the dirpath name is a string representing the name of the file itself. Any empty folders from the point of the file backwards to the root of the tree is removed. """ tree = self.cache.get(prefix, empty) if tree is empty: return False if name not in tree.files: return False tree.files.remove(name) self.remove_folder(tree, list(prefix)) return True
[ "def", "remove", "(", "self", ",", "prefix", ",", "name", ")", ":", "tree", "=", "self", ".", "cache", ".", "get", "(", "prefix", ",", "empty", ")", "if", "tree", "is", "empty", ":", "return", "False", "if", "name", "not", "in", "tree", ".", "files", ":", "return", "False", "tree", ".", "files", ".", "remove", "(", "name", ")", "self", ".", "remove_folder", "(", "tree", ",", "list", "(", "prefix", ")", ")", "return", "True" ]
Remove a path from the tree prefix is a tuple of the parts in the dirpath name is a string representing the name of the file itself. Any empty folders from the point of the file backwards to the root of the tree is removed.
[ "Remove", "a", "path", "from", "the", "tree" ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L82-L103
246,825
delfick/gitmit
gitmit/prefix_tree.py
PrefixTree.remove_folder
def remove_folder(self, tree, prefix): """ Used to remove any empty folders If this folder is empty then it is removed. If the parent is empty as a result, then the parent is also removed, and so on. """ while True: child = tree tree = tree.parent if not child.folders and not child.files: del self.cache[tuple(prefix)] if tree: del tree.folders[prefix.pop()] if not tree or tree.folders or tree.files: break
python
def remove_folder(self, tree, prefix): """ Used to remove any empty folders If this folder is empty then it is removed. If the parent is empty as a result, then the parent is also removed, and so on. """ while True: child = tree tree = tree.parent if not child.folders and not child.files: del self.cache[tuple(prefix)] if tree: del tree.folders[prefix.pop()] if not tree or tree.folders or tree.files: break
[ "def", "remove_folder", "(", "self", ",", "tree", ",", "prefix", ")", ":", "while", "True", ":", "child", "=", "tree", "tree", "=", "tree", ".", "parent", "if", "not", "child", ".", "folders", "and", "not", "child", ".", "files", ":", "del", "self", ".", "cache", "[", "tuple", "(", "prefix", ")", "]", "if", "tree", ":", "del", "tree", ".", "folders", "[", "prefix", ".", "pop", "(", ")", "]", "if", "not", "tree", "or", "tree", ".", "folders", "or", "tree", ".", "files", ":", "break" ]
Used to remove any empty folders If this folder is empty then it is removed. If the parent is empty as a result, then the parent is also removed, and so on.
[ "Used", "to", "remove", "any", "empty", "folders" ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L105-L122
246,826
knagra/farnsworth
workshift/utils.py
can_manage
def can_manage(user, semester=None, pool=None, any_pool=False): """ Whether a user is allowed to manage a workshift semester. This includes the current workshift managers, that semester's workshift managers, and site superusers. """ if semester and user in semester.workshift_managers.all(): return True if Manager and Manager.objects.filter( incumbent__user=user, workshift_manager=True, ).count() > 0: return True if pool and pool.managers.filter(incumbent__user=user).count() > 0: return True if any_pool and WorkshiftPool.objects.filter( managers__incumbent__user=user, ): return True return user.is_superuser or user.is_staff
python
def can_manage(user, semester=None, pool=None, any_pool=False): """ Whether a user is allowed to manage a workshift semester. This includes the current workshift managers, that semester's workshift managers, and site superusers. """ if semester and user in semester.workshift_managers.all(): return True if Manager and Manager.objects.filter( incumbent__user=user, workshift_manager=True, ).count() > 0: return True if pool and pool.managers.filter(incumbent__user=user).count() > 0: return True if any_pool and WorkshiftPool.objects.filter( managers__incumbent__user=user, ): return True return user.is_superuser or user.is_staff
[ "def", "can_manage", "(", "user", ",", "semester", "=", "None", ",", "pool", "=", "None", ",", "any_pool", "=", "False", ")", ":", "if", "semester", "and", "user", "in", "semester", ".", "workshift_managers", ".", "all", "(", ")", ":", "return", "True", "if", "Manager", "and", "Manager", ".", "objects", ".", "filter", "(", "incumbent__user", "=", "user", ",", "workshift_manager", "=", "True", ",", ")", ".", "count", "(", ")", ">", "0", ":", "return", "True", "if", "pool", "and", "pool", ".", "managers", ".", "filter", "(", "incumbent__user", "=", "user", ")", ".", "count", "(", ")", ">", "0", ":", "return", "True", "if", "any_pool", "and", "WorkshiftPool", ".", "objects", ".", "filter", "(", "managers__incumbent__user", "=", "user", ",", ")", ":", "return", "True", "return", "user", ".", "is_superuser", "or", "user", ".", "is_staff" ]
Whether a user is allowed to manage a workshift semester. This includes the current workshift managers, that semester's workshift managers, and site superusers.
[ "Whether", "a", "user", "is", "allowed", "to", "manage", "a", "workshift", "semester", ".", "This", "includes", "the", "current", "workshift", "managers", "that", "semester", "s", "workshift", "managers", "and", "site", "superusers", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L25-L47
246,827
knagra/farnsworth
workshift/utils.py
get_year_season
def get_year_season(day=None): """ Returns a guess of the year and season of the current semester. """ if day is None: day = date.today() year = day.year if day.month > 3 and day.month <= 7: season = Semester.SUMMER elif day.month > 7 and day.month <= 10: season = Semester.FALL else: season = Semester.SPRING if day.month > 10: year += 1 return year, season
python
def get_year_season(day=None): """ Returns a guess of the year and season of the current semester. """ if day is None: day = date.today() year = day.year if day.month > 3 and day.month <= 7: season = Semester.SUMMER elif day.month > 7 and day.month <= 10: season = Semester.FALL else: season = Semester.SPRING if day.month > 10: year += 1 return year, season
[ "def", "get_year_season", "(", "day", "=", "None", ")", ":", "if", "day", "is", "None", ":", "day", "=", "date", ".", "today", "(", ")", "year", "=", "day", ".", "year", "if", "day", ".", "month", ">", "3", "and", "day", ".", "month", "<=", "7", ":", "season", "=", "Semester", ".", "SUMMER", "elif", "day", ".", "month", ">", "7", "and", "day", ".", "month", "<=", "10", ":", "season", "=", "Semester", ".", "FALL", "else", ":", "season", "=", "Semester", ".", "SPRING", "if", "day", ".", "month", ">", "10", ":", "year", "+=", "1", "return", "year", ",", "season" ]
Returns a guess of the year and season of the current semester.
[ "Returns", "a", "guess", "of", "the", "year", "and", "season", "of", "the", "current", "semester", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L50-L66
246,828
knagra/farnsworth
workshift/utils.py
get_semester_start_end
def get_semester_start_end(year, season): """ Returns a guess of the start and end dates for given semester. """ if season == Semester.SPRING: start_month, start_day = 1, 20 end_month, end_day = 5, 17 elif season == Semester.SUMMER: start_month, start_day = 5, 25 end_month, end_day = 8, 16 else: start_month, start_day = 8, 24 end_month, end_day = 12, 20 return date(year, start_month, start_day), date(year, end_month, end_day)
python
def get_semester_start_end(year, season): """ Returns a guess of the start and end dates for given semester. """ if season == Semester.SPRING: start_month, start_day = 1, 20 end_month, end_day = 5, 17 elif season == Semester.SUMMER: start_month, start_day = 5, 25 end_month, end_day = 8, 16 else: start_month, start_day = 8, 24 end_month, end_day = 12, 20 return date(year, start_month, start_day), date(year, end_month, end_day)
[ "def", "get_semester_start_end", "(", "year", ",", "season", ")", ":", "if", "season", "==", "Semester", ".", "SPRING", ":", "start_month", ",", "start_day", "=", "1", ",", "20", "end_month", ",", "end_day", "=", "5", ",", "17", "elif", "season", "==", "Semester", ".", "SUMMER", ":", "start_month", ",", "start_day", "=", "5", ",", "25", "end_month", ",", "end_day", "=", "8", ",", "16", "else", ":", "start_month", ",", "start_day", "=", "8", ",", "24", "end_month", ",", "end_day", "=", "12", ",", "20", "return", "date", "(", "year", ",", "start_month", ",", "start_day", ")", ",", "date", "(", "year", ",", "end_month", ",", "end_day", ")" ]
Returns a guess of the start and end dates for given semester.
[ "Returns", "a", "guess", "of", "the", "start", "and", "end", "dates", "for", "given", "semester", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L69-L83
246,829
knagra/farnsworth
workshift/utils.py
randomly_assign_instances
def randomly_assign_instances(semester, pool, profiles=None, instances=None): """ Randomly assigns workshift instances to profiles. Returns ------- list of workshift.WorkshiftProfile list of workshift.WorkshiftInstance """ if profiles is None: profiles = WorkshiftProfile.objects.filter(semester=semester) if instances is None: instances = WorkshiftInstance.objects.filter( Q(info__pool=pool) | Q(weekly_workshift__pool=pool), workshifter__isnull=True, closed=False, ).exclude( weekly_workshift__workshift_type__assignment=WorkshiftType.NO_ASSIGN, ) instances = list(instances) profiles = list(profiles) # List of hours assigned to each profile hours_mapping = defaultdict(float) total_hours_owed = defaultdict(float) semester_weeks = (semester.end_date - semester.start_date).days / 7 # Initialize with already-assigned instances for profile in profiles: for shift in profile.instance_workshifter.filter( Q(info__pool=pool) | Q(weekly_workshift__pool=pool) ): hours_mapping[profile] += float(shift.hours) pool_hours = profile.pool_hours.get(pool=pool) if pool.weeks_per_period == 0: total_hours_owed[profile] = pool_hours.hours else: periods = semester_weeks / pool.weeks_per_period total_hours_owed[profile] = periods * float(pool_hours.hours) while profiles and instances: for profile in profiles[:]: instance = random.choice(instances) instance.workshifter = profile instance.save(update_fields=["workshifter"]) instance.logs.add( ShiftLogEntry.objects.create( person=instance.workshifter, entry_type=ShiftLogEntry.ASSIGNED, note="Randomly assigned.", ) ) instances.remove(instance) hours_mapping[profile] += float(instance.hours) if hours_mapping[profile] >= total_hours_owed[profile]: profiles.remove(profile) if not instances: break return profiles, instances
python
def randomly_assign_instances(semester, pool, profiles=None, instances=None): """ Randomly assigns workshift instances to profiles. Returns ------- list of workshift.WorkshiftProfile list of workshift.WorkshiftInstance """ if profiles is None: profiles = WorkshiftProfile.objects.filter(semester=semester) if instances is None: instances = WorkshiftInstance.objects.filter( Q(info__pool=pool) | Q(weekly_workshift__pool=pool), workshifter__isnull=True, closed=False, ).exclude( weekly_workshift__workshift_type__assignment=WorkshiftType.NO_ASSIGN, ) instances = list(instances) profiles = list(profiles) # List of hours assigned to each profile hours_mapping = defaultdict(float) total_hours_owed = defaultdict(float) semester_weeks = (semester.end_date - semester.start_date).days / 7 # Initialize with already-assigned instances for profile in profiles: for shift in profile.instance_workshifter.filter( Q(info__pool=pool) | Q(weekly_workshift__pool=pool) ): hours_mapping[profile] += float(shift.hours) pool_hours = profile.pool_hours.get(pool=pool) if pool.weeks_per_period == 0: total_hours_owed[profile] = pool_hours.hours else: periods = semester_weeks / pool.weeks_per_period total_hours_owed[profile] = periods * float(pool_hours.hours) while profiles and instances: for profile in profiles[:]: instance = random.choice(instances) instance.workshifter = profile instance.save(update_fields=["workshifter"]) instance.logs.add( ShiftLogEntry.objects.create( person=instance.workshifter, entry_type=ShiftLogEntry.ASSIGNED, note="Randomly assigned.", ) ) instances.remove(instance) hours_mapping[profile] += float(instance.hours) if hours_mapping[profile] >= total_hours_owed[profile]: profiles.remove(profile) if not instances: break return profiles, instances
[ "def", "randomly_assign_instances", "(", "semester", ",", "pool", ",", "profiles", "=", "None", ",", "instances", "=", "None", ")", ":", "if", "profiles", "is", "None", ":", "profiles", "=", "WorkshiftProfile", ".", "objects", ".", "filter", "(", "semester", "=", "semester", ")", "if", "instances", "is", "None", ":", "instances", "=", "WorkshiftInstance", ".", "objects", ".", "filter", "(", "Q", "(", "info__pool", "=", "pool", ")", "|", "Q", "(", "weekly_workshift__pool", "=", "pool", ")", ",", "workshifter__isnull", "=", "True", ",", "closed", "=", "False", ",", ")", ".", "exclude", "(", "weekly_workshift__workshift_type__assignment", "=", "WorkshiftType", ".", "NO_ASSIGN", ",", ")", "instances", "=", "list", "(", "instances", ")", "profiles", "=", "list", "(", "profiles", ")", "# List of hours assigned to each profile", "hours_mapping", "=", "defaultdict", "(", "float", ")", "total_hours_owed", "=", "defaultdict", "(", "float", ")", "semester_weeks", "=", "(", "semester", ".", "end_date", "-", "semester", ".", "start_date", ")", ".", "days", "/", "7", "# Initialize with already-assigned instances", "for", "profile", "in", "profiles", ":", "for", "shift", "in", "profile", ".", "instance_workshifter", ".", "filter", "(", "Q", "(", "info__pool", "=", "pool", ")", "|", "Q", "(", "weekly_workshift__pool", "=", "pool", ")", ")", ":", "hours_mapping", "[", "profile", "]", "+=", "float", "(", "shift", ".", "hours", ")", "pool_hours", "=", "profile", ".", "pool_hours", ".", "get", "(", "pool", "=", "pool", ")", "if", "pool", ".", "weeks_per_period", "==", "0", ":", "total_hours_owed", "[", "profile", "]", "=", "pool_hours", ".", "hours", "else", ":", "periods", "=", "semester_weeks", "/", "pool", ".", "weeks_per_period", "total_hours_owed", "[", "profile", "]", "=", "periods", "*", "float", "(", "pool_hours", ".", "hours", ")", "while", "profiles", "and", "instances", ":", "for", "profile", "in", "profiles", "[", ":", "]", ":", "instance", "=", "random", ".", "choice", "(", "instances", ")", "instance", ".", "workshifter", "=", "profile", "instance", ".", "save", "(", "update_fields", "=", "[", "\"workshifter\"", "]", ")", "instance", ".", "logs", ".", "add", "(", "ShiftLogEntry", ".", "objects", ".", "create", "(", "person", "=", "instance", ".", "workshifter", ",", "entry_type", "=", "ShiftLogEntry", ".", "ASSIGNED", ",", "note", "=", "\"Randomly assigned.\"", ",", ")", ")", "instances", ".", "remove", "(", "instance", ")", "hours_mapping", "[", "profile", "]", "+=", "float", "(", "instance", ".", "hours", ")", "if", "hours_mapping", "[", "profile", "]", ">=", "total_hours_owed", "[", "profile", "]", ":", "profiles", ".", "remove", "(", "profile", ")", "if", "not", "instances", ":", "break", "return", "profiles", ",", "instances" ]
Randomly assigns workshift instances to profiles. Returns ------- list of workshift.WorkshiftProfile list of workshift.WorkshiftInstance
[ "Randomly", "assigns", "workshift", "instances", "to", "profiles", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L563-L629
246,830
knagra/farnsworth
workshift/utils.py
clear_all_assignments
def clear_all_assignments(semester=None, pool=None, shifts=None): """ Clears all regular workshift assignments. Parameters ---------- semester : workshift.models.Semester, optional pool : workshift.models.WorkshiftPool, optional If set, grab workshifts from a specific pool. Otherwise, the primary workshift pool will be used. shifts : list of workshift.models.RegularWorkshift, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return [] if pool is None: pool = WorkshiftPool.objects.get( semester=semester, is_primary=True, ) if shifts is None: shifts = RegularWorkshift.objects.filter( pool=pool, is_manager_shift=False, workshift_type__assignment=WorkshiftType.AUTO_ASSIGN, ) for shift in shifts: shift.current_assignees.clear()
python
def clear_all_assignments(semester=None, pool=None, shifts=None): """ Clears all regular workshift assignments. Parameters ---------- semester : workshift.models.Semester, optional pool : workshift.models.WorkshiftPool, optional If set, grab workshifts from a specific pool. Otherwise, the primary workshift pool will be used. shifts : list of workshift.models.RegularWorkshift, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return [] if pool is None: pool = WorkshiftPool.objects.get( semester=semester, is_primary=True, ) if shifts is None: shifts = RegularWorkshift.objects.filter( pool=pool, is_manager_shift=False, workshift_type__assignment=WorkshiftType.AUTO_ASSIGN, ) for shift in shifts: shift.current_assignees.clear()
[ "def", "clear_all_assignments", "(", "semester", "=", "None", ",", "pool", "=", "None", ",", "shifts", "=", "None", ")", ":", "if", "semester", "is", "None", ":", "try", ":", "semester", "=", "Semester", ".", "objects", ".", "get", "(", "current", "=", "True", ")", "except", "(", "Semester", ".", "DoesNotExist", ",", "Semester", ".", "MultipleObjectsReturned", ")", ":", "return", "[", "]", "if", "pool", "is", "None", ":", "pool", "=", "WorkshiftPool", ".", "objects", ".", "get", "(", "semester", "=", "semester", ",", "is_primary", "=", "True", ",", ")", "if", "shifts", "is", "None", ":", "shifts", "=", "RegularWorkshift", ".", "objects", ".", "filter", "(", "pool", "=", "pool", ",", "is_manager_shift", "=", "False", ",", "workshift_type__assignment", "=", "WorkshiftType", ".", "AUTO_ASSIGN", ",", ")", "for", "shift", "in", "shifts", ":", "shift", ".", "current_assignees", ".", "clear", "(", ")" ]
Clears all regular workshift assignments. Parameters ---------- semester : workshift.models.Semester, optional pool : workshift.models.WorkshiftPool, optional If set, grab workshifts from a specific pool. Otherwise, the primary workshift pool will be used. shifts : list of workshift.models.RegularWorkshift, optional
[ "Clears", "all", "regular", "workshift", "assignments", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L632-L662
246,831
knagra/farnsworth
workshift/utils.py
update_standings
def update_standings(semester=None, pool_hours=None, moment=None): """ This function acts to update a list of PoolHours objects to adjust their current standing based on the time in the semester. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional If None, runs on all pool hours for semester. moment : datetime, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return [] if moment is None: moment = localtime(now()) if pool_hours is None: pool_hours = PoolHours.objects.filter(pool__semester=semester) for hours in pool_hours: # Don't update hours after the semester ends if hours.last_updated and \ hours.last_updated.date() > semester.end_date: continue # Calculate the number of periods (n weeks / once per semester) that # have passed since last update periods = hours.periods_since_last_update(moment=moment) # Update the actual standings if periods > 0: hours.standing -= hours.hours * periods hours.last_updated = moment hours.save(update_fields=["standing", "last_updated"])
python
def update_standings(semester=None, pool_hours=None, moment=None): """ This function acts to update a list of PoolHours objects to adjust their current standing based on the time in the semester. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional If None, runs on all pool hours for semester. moment : datetime, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return [] if moment is None: moment = localtime(now()) if pool_hours is None: pool_hours = PoolHours.objects.filter(pool__semester=semester) for hours in pool_hours: # Don't update hours after the semester ends if hours.last_updated and \ hours.last_updated.date() > semester.end_date: continue # Calculate the number of periods (n weeks / once per semester) that # have passed since last update periods = hours.periods_since_last_update(moment=moment) # Update the actual standings if periods > 0: hours.standing -= hours.hours * periods hours.last_updated = moment hours.save(update_fields=["standing", "last_updated"])
[ "def", "update_standings", "(", "semester", "=", "None", ",", "pool_hours", "=", "None", ",", "moment", "=", "None", ")", ":", "if", "semester", "is", "None", ":", "try", ":", "semester", "=", "Semester", ".", "objects", ".", "get", "(", "current", "=", "True", ")", "except", "(", "Semester", ".", "DoesNotExist", ",", "Semester", ".", "MultipleObjectsReturned", ")", ":", "return", "[", "]", "if", "moment", "is", "None", ":", "moment", "=", "localtime", "(", "now", "(", ")", ")", "if", "pool_hours", "is", "None", ":", "pool_hours", "=", "PoolHours", ".", "objects", ".", "filter", "(", "pool__semester", "=", "semester", ")", "for", "hours", "in", "pool_hours", ":", "# Don't update hours after the semester ends", "if", "hours", ".", "last_updated", "and", "hours", ".", "last_updated", ".", "date", "(", ")", ">", "semester", ".", "end_date", ":", "continue", "# Calculate the number of periods (n weeks / once per semester) that", "# have passed since last update", "periods", "=", "hours", ".", "periods_since_last_update", "(", "moment", "=", "moment", ")", "# Update the actual standings", "if", "periods", ">", "0", ":", "hours", ".", "standing", "-=", "hours", ".", "hours", "*", "periods", "hours", ".", "last_updated", "=", "moment", "hours", ".", "save", "(", "update_fields", "=", "[", "\"standing\"", ",", "\"last_updated\"", "]", ")" ]
This function acts to update a list of PoolHours objects to adjust their current standing based on the time in the semester. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional If None, runs on all pool hours for semester. moment : datetime, optional
[ "This", "function", "acts", "to", "update", "a", "list", "of", "PoolHours", "objects", "to", "adjust", "their", "current", "standing", "based", "on", "the", "time", "in", "the", "semester", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L665-L703
246,832
knagra/farnsworth
workshift/utils.py
reset_standings
def reset_standings(semester=None, pool_hours=None): """ Utility function to recalculate workshift standings. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return if pool_hours is None: pool_hours = PoolHours.objects.filter(pool__semester=semester) for hours in pool_hours: hours.last_updated = None hours.standing = hours.hour_adjustment profile = WorkshiftProfile.objects.get(pool_hours=hours) instances = WorkshiftInstance.objects.filter( Q(weekly_workshift__pool=hours.pool) | Q(info__pool=hours.pool), Q(workshifter=profile) | Q(liable=profile), closed=True, ) for instance in instances: if instance.blown: hours.standing -= instance.hours else: hours.standing += instance.hours hours.save(update_fields=["standing", "last_updated"]) update_standings( semester=semester, pool_hours=pool_hours, )
python
def reset_standings(semester=None, pool_hours=None): """ Utility function to recalculate workshift standings. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return if pool_hours is None: pool_hours = PoolHours.objects.filter(pool__semester=semester) for hours in pool_hours: hours.last_updated = None hours.standing = hours.hour_adjustment profile = WorkshiftProfile.objects.get(pool_hours=hours) instances = WorkshiftInstance.objects.filter( Q(weekly_workshift__pool=hours.pool) | Q(info__pool=hours.pool), Q(workshifter=profile) | Q(liable=profile), closed=True, ) for instance in instances: if instance.blown: hours.standing -= instance.hours else: hours.standing += instance.hours hours.save(update_fields=["standing", "last_updated"]) update_standings( semester=semester, pool_hours=pool_hours, )
[ "def", "reset_standings", "(", "semester", "=", "None", ",", "pool_hours", "=", "None", ")", ":", "if", "semester", "is", "None", ":", "try", ":", "semester", "=", "Semester", ".", "objects", ".", "get", "(", "current", "=", "True", ")", "except", "(", "Semester", ".", "DoesNotExist", ",", "Semester", ".", "MultipleObjectsReturned", ")", ":", "return", "if", "pool_hours", "is", "None", ":", "pool_hours", "=", "PoolHours", ".", "objects", ".", "filter", "(", "pool__semester", "=", "semester", ")", "for", "hours", "in", "pool_hours", ":", "hours", ".", "last_updated", "=", "None", "hours", ".", "standing", "=", "hours", ".", "hour_adjustment", "profile", "=", "WorkshiftProfile", ".", "objects", ".", "get", "(", "pool_hours", "=", "hours", ")", "instances", "=", "WorkshiftInstance", ".", "objects", ".", "filter", "(", "Q", "(", "weekly_workshift__pool", "=", "hours", ".", "pool", ")", "|", "Q", "(", "info__pool", "=", "hours", ".", "pool", ")", ",", "Q", "(", "workshifter", "=", "profile", ")", "|", "Q", "(", "liable", "=", "profile", ")", ",", "closed", "=", "True", ",", ")", "for", "instance", "in", "instances", ":", "if", "instance", ".", "blown", ":", "hours", ".", "standing", "-=", "instance", ".", "hours", "else", ":", "hours", ".", "standing", "+=", "instance", ".", "hours", "hours", ".", "save", "(", "update_fields", "=", "[", "\"standing\"", ",", "\"last_updated\"", "]", ")", "update_standings", "(", "semester", "=", "semester", ",", "pool_hours", "=", "pool_hours", ",", ")" ]
Utility function to recalculate workshift standings. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional
[ "Utility", "function", "to", "recalculate", "workshift", "standings", ".", "This", "function", "is", "meant", "to", "only", "be", "called", "from", "the", "manager", "shell", "it", "is", "not", "referenced", "anywhere", "else", "in", "the", "workshift", "module", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L706-L748
246,833
knagra/farnsworth
workshift/utils.py
calculate_assigned_hours
def calculate_assigned_hours(semester=None, profiles=None): """ Utility function to recalculate the assigned workshift hours. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional profiles : list of workshift.models.WorkshiftProfile, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return if profiles is None: profiles = WorkshiftProfile.objects.filter(semester=semester) for profile in profiles: for pool_hours in profile.pool_hours.all(): shifts = RegularWorkshift.objects.filter( current_assignees=profile, pool=pool_hours.pool, active=True, ) pool_hours.assigned_hours = sum(shift.hours for shift in shifts) pool_hours.save(update_fields=["assigned_hours"])
python
def calculate_assigned_hours(semester=None, profiles=None): """ Utility function to recalculate the assigned workshift hours. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional profiles : list of workshift.models.WorkshiftProfile, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return if profiles is None: profiles = WorkshiftProfile.objects.filter(semester=semester) for profile in profiles: for pool_hours in profile.pool_hours.all(): shifts = RegularWorkshift.objects.filter( current_assignees=profile, pool=pool_hours.pool, active=True, ) pool_hours.assigned_hours = sum(shift.hours for shift in shifts) pool_hours.save(update_fields=["assigned_hours"])
[ "def", "calculate_assigned_hours", "(", "semester", "=", "None", ",", "profiles", "=", "None", ")", ":", "if", "semester", "is", "None", ":", "try", ":", "semester", "=", "Semester", ".", "objects", ".", "get", "(", "current", "=", "True", ")", "except", "(", "Semester", ".", "DoesNotExist", ",", "Semester", ".", "MultipleObjectsReturned", ")", ":", "return", "if", "profiles", "is", "None", ":", "profiles", "=", "WorkshiftProfile", ".", "objects", ".", "filter", "(", "semester", "=", "semester", ")", "for", "profile", "in", "profiles", ":", "for", "pool_hours", "in", "profile", ".", "pool_hours", ".", "all", "(", ")", ":", "shifts", "=", "RegularWorkshift", ".", "objects", ".", "filter", "(", "current_assignees", "=", "profile", ",", "pool", "=", "pool_hours", ".", "pool", ",", "active", "=", "True", ",", ")", "pool_hours", ".", "assigned_hours", "=", "sum", "(", "shift", ".", "hours", "for", "shift", "in", "shifts", ")", "pool_hours", ".", "save", "(", "update_fields", "=", "[", "\"assigned_hours\"", "]", ")" ]
Utility function to recalculate the assigned workshift hours. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional profiles : list of workshift.models.WorkshiftProfile, optional
[ "Utility", "function", "to", "recalculate", "the", "assigned", "workshift", "hours", ".", "This", "function", "is", "meant", "to", "only", "be", "called", "from", "the", "manager", "shell", "it", "is", "not", "referenced", "anywhere", "else", "in", "the", "workshift", "module", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L751-L778
246,834
knagra/farnsworth
workshift/utils.py
reset_instance_assignments
def reset_instance_assignments(semester=None, shifts=None): """ Utility function to reset instance assignments. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional shifts : list of workshift.models.RegularWorkshift, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return if shifts is None: shifts = RegularWorkshift.objects.filter( pool__semester=semester, ) for shift in shifts: instances = WorkshiftInstance.objects.filter( closed=False, weekly_workshift=shift, ).order_by("date") assignees = list(shift.current_assignees.all()) assignees += [None] * (shift.count - len(assignees)) dates = defaultdict(set) for assignee, instance in zip(cycle(assignees), instances): if assignee is not None: if instance.date in dates[assignee.pk]: continue dates[assignee.pk].add(instance.date) instance.workshifter = assignee instance.liable = None instance.save(update_fields=["workshifter", "liable"]) instance.logs.add( ShiftLogEntry.objects.create( person=instance.workshifter, entry_type=ShiftLogEntry.ASSIGNED, note="Manager reset assignment.", ) )
python
def reset_instance_assignments(semester=None, shifts=None): """ Utility function to reset instance assignments. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional shifts : list of workshift.models.RegularWorkshift, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return if shifts is None: shifts = RegularWorkshift.objects.filter( pool__semester=semester, ) for shift in shifts: instances = WorkshiftInstance.objects.filter( closed=False, weekly_workshift=shift, ).order_by("date") assignees = list(shift.current_assignees.all()) assignees += [None] * (shift.count - len(assignees)) dates = defaultdict(set) for assignee, instance in zip(cycle(assignees), instances): if assignee is not None: if instance.date in dates[assignee.pk]: continue dates[assignee.pk].add(instance.date) instance.workshifter = assignee instance.liable = None instance.save(update_fields=["workshifter", "liable"]) instance.logs.add( ShiftLogEntry.objects.create( person=instance.workshifter, entry_type=ShiftLogEntry.ASSIGNED, note="Manager reset assignment.", ) )
[ "def", "reset_instance_assignments", "(", "semester", "=", "None", ",", "shifts", "=", "None", ")", ":", "if", "semester", "is", "None", ":", "try", ":", "semester", "=", "Semester", ".", "objects", ".", "get", "(", "current", "=", "True", ")", "except", "(", "Semester", ".", "DoesNotExist", ",", "Semester", ".", "MultipleObjectsReturned", ")", ":", "return", "if", "shifts", "is", "None", ":", "shifts", "=", "RegularWorkshift", ".", "objects", ".", "filter", "(", "pool__semester", "=", "semester", ",", ")", "for", "shift", "in", "shifts", ":", "instances", "=", "WorkshiftInstance", ".", "objects", ".", "filter", "(", "closed", "=", "False", ",", "weekly_workshift", "=", "shift", ",", ")", ".", "order_by", "(", "\"date\"", ")", "assignees", "=", "list", "(", "shift", ".", "current_assignees", ".", "all", "(", ")", ")", "assignees", "+=", "[", "None", "]", "*", "(", "shift", ".", "count", "-", "len", "(", "assignees", ")", ")", "dates", "=", "defaultdict", "(", "set", ")", "for", "assignee", ",", "instance", "in", "zip", "(", "cycle", "(", "assignees", ")", ",", "instances", ")", ":", "if", "assignee", "is", "not", "None", ":", "if", "instance", ".", "date", "in", "dates", "[", "assignee", ".", "pk", "]", ":", "continue", "dates", "[", "assignee", ".", "pk", "]", ".", "add", "(", "instance", ".", "date", ")", "instance", ".", "workshifter", "=", "assignee", "instance", ".", "liable", "=", "None", "instance", ".", "save", "(", "update_fields", "=", "[", "\"workshifter\"", ",", "\"liable\"", "]", ")", "instance", ".", "logs", ".", "add", "(", "ShiftLogEntry", ".", "objects", ".", "create", "(", "person", "=", "instance", ".", "workshifter", ",", "entry_type", "=", "ShiftLogEntry", ".", "ASSIGNED", ",", "note", "=", "\"Manager reset assignment.\"", ",", ")", ")" ]
Utility function to reset instance assignments. This function is meant to only be called from the manager shell, it is not referenced anywhere else in the workshift module. Parameters ---------- semester : workshift.models.Semester, optional shifts : list of workshift.models.RegularWorkshift, optional
[ "Utility", "function", "to", "reset", "instance", "assignments", ".", "This", "function", "is", "meant", "to", "only", "be", "called", "from", "the", "manager", "shell", "it", "is", "not", "referenced", "anywhere", "else", "in", "the", "workshift", "module", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L781-L829
246,835
xtrementl/focus
focus/daemon.py
pid_exists
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
python
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
[ "def", "pid_exists", "(", "pid", ")", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "0", ")", "except", "OSError", "as", "exc", ":", "return", "exc", ".", "errno", "==", "errno", ".", "EPERM", "else", ":", "return", "True" ]
Determines if a system process identifer exists in process table.
[ "Determines", "if", "a", "system", "process", "identifer", "exists", "in", "process", "table", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L54-L62
246,836
xtrementl/focus
focus/daemon.py
daemonize
def daemonize(pid_file, working_dir, func): """ Turns the current process into a daemon. `pid_file` File path to use as pid lock file for daemon. `working_dir` Working directory to switch to when daemon starts. `func` Callable to run after daemon is forked. """ def _fork(): """ Fork a child process. Returns ``False`` if fork failed; otherwise, we are inside the new child process. """ try: pid = os.fork() if pid > 0: os._exit(0) # exit parent return True except OSError: return False def _register_pidfile(filename): """ Registers a pid file for the current process which will cleaned up when the process terminates. `filename` Filename to save pid to. """ if common.writefile(filename, str(os.getpid()) + os.linesep): os.chmod(filename, 0644) # rw-r--r-- def _cleanup_pid(): """ Removes pidfile. """ common.safe_remove_file(filename) atexit.register(_cleanup_pid) if not pid_file or not working_dir or not func: return if not os.path.isfile(pid_file): # enforce pid lock file # attempt first fork if not _fork(): return try: # detach from current environment os.chdir(working_dir) os.setsid() os.umask(0) except OSError: return # attempt second fork if not _fork(): return # we'll ignore closing file descriptors.. # redirecting the streams should be sufficient # redirect streams to /dev/null _fd = os.open(os.devnull, os.O_RDWR) os.dup2(_fd, sys.stdin.fileno()) os.dup2(_fd, sys.stdout.fileno()) os.dup2(_fd, sys.stderr.fileno()) # setup pidfile _register_pidfile(pid_file) # execute provided callable func()
python
def daemonize(pid_file, working_dir, func): """ Turns the current process into a daemon. `pid_file` File path to use as pid lock file for daemon. `working_dir` Working directory to switch to when daemon starts. `func` Callable to run after daemon is forked. """ def _fork(): """ Fork a child process. Returns ``False`` if fork failed; otherwise, we are inside the new child process. """ try: pid = os.fork() if pid > 0: os._exit(0) # exit parent return True except OSError: return False def _register_pidfile(filename): """ Registers a pid file for the current process which will cleaned up when the process terminates. `filename` Filename to save pid to. """ if common.writefile(filename, str(os.getpid()) + os.linesep): os.chmod(filename, 0644) # rw-r--r-- def _cleanup_pid(): """ Removes pidfile. """ common.safe_remove_file(filename) atexit.register(_cleanup_pid) if not pid_file or not working_dir or not func: return if not os.path.isfile(pid_file): # enforce pid lock file # attempt first fork if not _fork(): return try: # detach from current environment os.chdir(working_dir) os.setsid() os.umask(0) except OSError: return # attempt second fork if not _fork(): return # we'll ignore closing file descriptors.. # redirecting the streams should be sufficient # redirect streams to /dev/null _fd = os.open(os.devnull, os.O_RDWR) os.dup2(_fd, sys.stdin.fileno()) os.dup2(_fd, sys.stdout.fileno()) os.dup2(_fd, sys.stderr.fileno()) # setup pidfile _register_pidfile(pid_file) # execute provided callable func()
[ "def", "daemonize", "(", "pid_file", ",", "working_dir", ",", "func", ")", ":", "def", "_fork", "(", ")", ":", "\"\"\" Fork a child process.\n\n Returns ``False`` if fork failed; otherwise,\n we are inside the new child process.\n \"\"\"", "try", ":", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", ">", "0", ":", "os", ".", "_exit", "(", "0", ")", "# exit parent", "return", "True", "except", "OSError", ":", "return", "False", "def", "_register_pidfile", "(", "filename", ")", ":", "\"\"\" Registers a pid file for the current process which will cleaned up\n when the process terminates.\n\n `filename`\n Filename to save pid to.\n \"\"\"", "if", "common", ".", "writefile", "(", "filename", ",", "str", "(", "os", ".", "getpid", "(", ")", ")", "+", "os", ".", "linesep", ")", ":", "os", ".", "chmod", "(", "filename", ",", "0644", ")", "# rw-r--r--", "def", "_cleanup_pid", "(", ")", ":", "\"\"\" Removes pidfile.\n \"\"\"", "common", ".", "safe_remove_file", "(", "filename", ")", "atexit", ".", "register", "(", "_cleanup_pid", ")", "if", "not", "pid_file", "or", "not", "working_dir", "or", "not", "func", ":", "return", "if", "not", "os", ".", "path", ".", "isfile", "(", "pid_file", ")", ":", "# enforce pid lock file", "# attempt first fork", "if", "not", "_fork", "(", ")", ":", "return", "try", ":", "# detach from current environment", "os", ".", "chdir", "(", "working_dir", ")", "os", ".", "setsid", "(", ")", "os", ".", "umask", "(", "0", ")", "except", "OSError", ":", "return", "# attempt second fork", "if", "not", "_fork", "(", ")", ":", "return", "# we'll ignore closing file descriptors..", "# redirecting the streams should be sufficient", "# redirect streams to /dev/null", "_fd", "=", "os", ".", "open", "(", "os", ".", "devnull", ",", "os", ".", "O_RDWR", ")", "os", ".", "dup2", "(", "_fd", ",", "sys", ".", "stdin", ".", "fileno", "(", ")", ")", "os", ".", "dup2", "(", "_fd", ",", "sys", ".", "stdout", ".", "fileno", "(", ")", ")", "os", ".", "dup2", "(", "_fd", ",", "sys", ".", "stderr", ".", "fileno", "(", ")", ")", "# setup pidfile", "_register_pidfile", "(", "pid_file", ")", "# execute provided callable", "func", "(", ")" ]
Turns the current process into a daemon. `pid_file` File path to use as pid lock file for daemon. `working_dir` Working directory to switch to when daemon starts. `func` Callable to run after daemon is forked.
[ "Turns", "the", "current", "process", "into", "a", "daemon", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L65-L141
246,837
xtrementl/focus
focus/daemon.py
shell_focusd
def shell_focusd(data_dir): """ Shells a new instance of a focusd daemon process. `data_dir` Home directory for focusd data. Returns boolean. * Raises ``ValueError`` if sudo used and all passwords tries failed. """ command = 'focusd {0}'.format(data_dir) # see what event hook plugins are registered plugins = registration.get_registered(event_hooks=True) if not plugins: # none registered, bail raise errors.NoPluginsRegistered # do any of the plugins need root access? # if so, wrap command with sudo to escalate privs, if not already root needs_root = any(p for p in plugins if p.needs_root) if needs_root and os.getuid() != 0: # only if not already root command = 'sudo ' + command else: needs_root = False # shell the daemon process _, code = common.shell_process(command, exitcode=True) if code == 1 and needs_root: # passwords failed? raise ValueError return code == 0
python
def shell_focusd(data_dir): """ Shells a new instance of a focusd daemon process. `data_dir` Home directory for focusd data. Returns boolean. * Raises ``ValueError`` if sudo used and all passwords tries failed. """ command = 'focusd {0}'.format(data_dir) # see what event hook plugins are registered plugins = registration.get_registered(event_hooks=True) if not plugins: # none registered, bail raise errors.NoPluginsRegistered # do any of the plugins need root access? # if so, wrap command with sudo to escalate privs, if not already root needs_root = any(p for p in plugins if p.needs_root) if needs_root and os.getuid() != 0: # only if not already root command = 'sudo ' + command else: needs_root = False # shell the daemon process _, code = common.shell_process(command, exitcode=True) if code == 1 and needs_root: # passwords failed? raise ValueError return code == 0
[ "def", "shell_focusd", "(", "data_dir", ")", ":", "command", "=", "'focusd {0}'", ".", "format", "(", "data_dir", ")", "# see what event hook plugins are registered", "plugins", "=", "registration", ".", "get_registered", "(", "event_hooks", "=", "True", ")", "if", "not", "plugins", ":", "# none registered, bail", "raise", "errors", ".", "NoPluginsRegistered", "# do any of the plugins need root access?", "# if so, wrap command with sudo to escalate privs, if not already root", "needs_root", "=", "any", "(", "p", "for", "p", "in", "plugins", "if", "p", ".", "needs_root", ")", "if", "needs_root", "and", "os", ".", "getuid", "(", ")", "!=", "0", ":", "# only if not already root", "command", "=", "'sudo '", "+", "command", "else", ":", "needs_root", "=", "False", "# shell the daemon process", "_", ",", "code", "=", "common", ".", "shell_process", "(", "command", ",", "exitcode", "=", "True", ")", "if", "code", "==", "1", "and", "needs_root", ":", "# passwords failed?", "raise", "ValueError", "return", "code", "==", "0" ]
Shells a new instance of a focusd daemon process. `data_dir` Home directory for focusd data. Returns boolean. * Raises ``ValueError`` if sudo used and all passwords tries failed.
[ "Shells", "a", "new", "instance", "of", "a", "focusd", "daemon", "process", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L144-L178
246,838
xtrementl/focus
focus/daemon.py
focusd
def focusd(task): """ Forks the current process as a daemon to run a task. `task` ``Task`` instance for the task to run. """ # determine if command server should be started if registration.get_registered(event_hooks=True, root_access=True): # root event plugins available start_cmd_srv = (os.getuid() == 0) # must be root else: start_cmd_srv = False # daemonize our current process _run = lambda: Focusd(task).run(start_cmd_srv) daemonize(get_daemon_pidfile(task), task.task_dir, _run)
python
def focusd(task): """ Forks the current process as a daemon to run a task. `task` ``Task`` instance for the task to run. """ # determine if command server should be started if registration.get_registered(event_hooks=True, root_access=True): # root event plugins available start_cmd_srv = (os.getuid() == 0) # must be root else: start_cmd_srv = False # daemonize our current process _run = lambda: Focusd(task).run(start_cmd_srv) daemonize(get_daemon_pidfile(task), task.task_dir, _run)
[ "def", "focusd", "(", "task", ")", ":", "# determine if command server should be started", "if", "registration", ".", "get_registered", "(", "event_hooks", "=", "True", ",", "root_access", "=", "True", ")", ":", "# root event plugins available", "start_cmd_srv", "=", "(", "os", ".", "getuid", "(", ")", "==", "0", ")", "# must be root", "else", ":", "start_cmd_srv", "=", "False", "# daemonize our current process", "_run", "=", "lambda", ":", "Focusd", "(", "task", ")", ".", "run", "(", "start_cmd_srv", ")", "daemonize", "(", "get_daemon_pidfile", "(", "task", ")", ",", "task", ".", "task_dir", ",", "_run", ")" ]
Forks the current process as a daemon to run a task. `task` ``Task`` instance for the task to run.
[ "Forks", "the", "current", "process", "as", "a", "daemon", "to", "run", "a", "task", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L181-L197
246,839
xtrementl/focus
focus/daemon.py
Focusd._reg_sighandlers
def _reg_sighandlers(self): """ Registers signal handlers to this class. """ # SIGCHLD, so we shutdown when any of the child processes exit _handler = lambda signo, frame: self.shutdown() signal.signal(signal.SIGCHLD, _handler) signal.signal(signal.SIGTERM, _handler)
python
def _reg_sighandlers(self): """ Registers signal handlers to this class. """ # SIGCHLD, so we shutdown when any of the child processes exit _handler = lambda signo, frame: self.shutdown() signal.signal(signal.SIGCHLD, _handler) signal.signal(signal.SIGTERM, _handler)
[ "def", "_reg_sighandlers", "(", "self", ")", ":", "# SIGCHLD, so we shutdown when any of the child processes exit", "_handler", "=", "lambda", "signo", ",", "frame", ":", "self", ".", "shutdown", "(", ")", "signal", ".", "signal", "(", "signal", ".", "SIGCHLD", ",", "_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "_handler", ")" ]
Registers signal handlers to this class.
[ "Registers", "signal", "handlers", "to", "this", "class", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L219-L226
246,840
xtrementl/focus
focus/daemon.py
Focusd._drop_privs
def _drop_privs(self): """ Reduces effective privileges for this process to that of the task owner. The umask and environment variables are also modified to recreate the environment of the user. """ uid = self._task.owner # get pwd database info for task owner try: pwd_info = pwd.getpwuid(uid) except OSError: pwd_info = None # set secondary group ids for user, must come first if pwd_info: try: gids = [g.gr_gid for g in grp.getgrall() if pwd_info.pw_name in g.gr_mem] gids.append(pwd_info.pw_gid) os.setgroups(gids) except OSError: pass # set group id, must come before uid try: os.setgid(pwd_info.pw_gid) except OSError: pass # set user id try: os.setuid(uid) # update user env variables if pwd_info: for k in ('USER', 'USERNAME', 'SHELL', 'HOME'): if k in os.environ: if k in ('USER', 'USERNAME'): val = pwd_info.pw_name elif k == 'SHELL': val = pwd_info.pw_shell elif k == 'HOME': val = pwd_info.pw_dir # update value os.environ[k] = val # remove unneeded env variables keys = [] for k, _ in os.environ.iteritems(): if k.startswith('SUDO_') or k == 'LOGNAME': keys.append(k) for k in keys: del os.environ[k] except OSError: pass # set default umask try: os.umask(022) except OSError: pass
python
def _drop_privs(self): """ Reduces effective privileges for this process to that of the task owner. The umask and environment variables are also modified to recreate the environment of the user. """ uid = self._task.owner # get pwd database info for task owner try: pwd_info = pwd.getpwuid(uid) except OSError: pwd_info = None # set secondary group ids for user, must come first if pwd_info: try: gids = [g.gr_gid for g in grp.getgrall() if pwd_info.pw_name in g.gr_mem] gids.append(pwd_info.pw_gid) os.setgroups(gids) except OSError: pass # set group id, must come before uid try: os.setgid(pwd_info.pw_gid) except OSError: pass # set user id try: os.setuid(uid) # update user env variables if pwd_info: for k in ('USER', 'USERNAME', 'SHELL', 'HOME'): if k in os.environ: if k in ('USER', 'USERNAME'): val = pwd_info.pw_name elif k == 'SHELL': val = pwd_info.pw_shell elif k == 'HOME': val = pwd_info.pw_dir # update value os.environ[k] = val # remove unneeded env variables keys = [] for k, _ in os.environ.iteritems(): if k.startswith('SUDO_') or k == 'LOGNAME': keys.append(k) for k in keys: del os.environ[k] except OSError: pass # set default umask try: os.umask(022) except OSError: pass
[ "def", "_drop_privs", "(", "self", ")", ":", "uid", "=", "self", ".", "_task", ".", "owner", "# get pwd database info for task owner", "try", ":", "pwd_info", "=", "pwd", ".", "getpwuid", "(", "uid", ")", "except", "OSError", ":", "pwd_info", "=", "None", "# set secondary group ids for user, must come first", "if", "pwd_info", ":", "try", ":", "gids", "=", "[", "g", ".", "gr_gid", "for", "g", "in", "grp", ".", "getgrall", "(", ")", "if", "pwd_info", ".", "pw_name", "in", "g", ".", "gr_mem", "]", "gids", ".", "append", "(", "pwd_info", ".", "pw_gid", ")", "os", ".", "setgroups", "(", "gids", ")", "except", "OSError", ":", "pass", "# set group id, must come before uid", "try", ":", "os", ".", "setgid", "(", "pwd_info", ".", "pw_gid", ")", "except", "OSError", ":", "pass", "# set user id", "try", ":", "os", ".", "setuid", "(", "uid", ")", "# update user env variables", "if", "pwd_info", ":", "for", "k", "in", "(", "'USER'", ",", "'USERNAME'", ",", "'SHELL'", ",", "'HOME'", ")", ":", "if", "k", "in", "os", ".", "environ", ":", "if", "k", "in", "(", "'USER'", ",", "'USERNAME'", ")", ":", "val", "=", "pwd_info", ".", "pw_name", "elif", "k", "==", "'SHELL'", ":", "val", "=", "pwd_info", ".", "pw_shell", "elif", "k", "==", "'HOME'", ":", "val", "=", "pwd_info", ".", "pw_dir", "# update value", "os", ".", "environ", "[", "k", "]", "=", "val", "# remove unneeded env variables", "keys", "=", "[", "]", "for", "k", ",", "_", "in", "os", ".", "environ", ".", "iteritems", "(", ")", ":", "if", "k", ".", "startswith", "(", "'SUDO_'", ")", "or", "k", "==", "'LOGNAME'", ":", "keys", ".", "append", "(", "k", ")", "for", "k", "in", "keys", ":", "del", "os", ".", "environ", "[", "k", "]", "except", "OSError", ":", "pass", "# set default umask", "try", ":", "os", ".", "umask", "(", "022", ")", "except", "OSError", ":", "pass" ]
Reduces effective privileges for this process to that of the task owner. The umask and environment variables are also modified to recreate the environment of the user.
[ "Reduces", "effective", "privileges", "for", "this", "process", "to", "that", "of", "the", "task", "owner", ".", "The", "umask", "and", "environment", "variables", "are", "also", "modified", "to", "recreate", "the", "environment", "of", "the", "user", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L228-L295
246,841
xtrementl/focus
focus/daemon.py
Focusd.shutdown
def shutdown(self): """ Shuts down the daemon process. """ if not self._exited: self._exited = True # signal task runner to terminate via SIGTERM if self._task_runner.is_alive(): self._task_runner.terminate() # if command server is running, then block until # task runner completes so it has time to use # the command server to clean up root plugins if self._command_server.is_alive(): if self._task_runner.is_alive(): self._task_runner.join() _shutdown_pipe(self._pipe) self._task.stop()
python
def shutdown(self): """ Shuts down the daemon process. """ if not self._exited: self._exited = True # signal task runner to terminate via SIGTERM if self._task_runner.is_alive(): self._task_runner.terminate() # if command server is running, then block until # task runner completes so it has time to use # the command server to clean up root plugins if self._command_server.is_alive(): if self._task_runner.is_alive(): self._task_runner.join() _shutdown_pipe(self._pipe) self._task.stop()
[ "def", "shutdown", "(", "self", ")", ":", "if", "not", "self", ".", "_exited", ":", "self", ".", "_exited", "=", "True", "# signal task runner to terminate via SIGTERM", "if", "self", ".", "_task_runner", ".", "is_alive", "(", ")", ":", "self", ".", "_task_runner", ".", "terminate", "(", ")", "# if command server is running, then block until", "# task runner completes so it has time to use", "# the command server to clean up root plugins", "if", "self", ".", "_command_server", ".", "is_alive", "(", ")", ":", "if", "self", ".", "_task_runner", ".", "is_alive", "(", ")", ":", "self", ".", "_task_runner", ".", "join", "(", ")", "_shutdown_pipe", "(", "self", ".", "_pipe", ")", "self", ".", "_task", ".", "stop", "(", ")" ]
Shuts down the daemon process.
[ "Shuts", "down", "the", "daemon", "process", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L297-L316
246,842
xtrementl/focus
focus/daemon.py
Focusd.run
def run(self, start_command_srv): """ Setup daemon process, start child forks, and sleep until events are signalled. `start_command_srv` Set to ``True`` if command server should be started. """ if start_command_srv: # note, this must be established *before* the task runner is forked # so the task runner can communicate with the command server. # fork the command server self._command_server.start() # drop root privileges; command server will remain as the only # daemon process with root privileges. while root plugins have root # shell access, they are known and the commands are logged by the # command server. self._drop_privs() # fork the task runner self._task_runner.start() # setup signal handlers self._reg_sighandlers() while self.running: time.sleep(self._sleep_period) self.shutdown()
python
def run(self, start_command_srv): """ Setup daemon process, start child forks, and sleep until events are signalled. `start_command_srv` Set to ``True`` if command server should be started. """ if start_command_srv: # note, this must be established *before* the task runner is forked # so the task runner can communicate with the command server. # fork the command server self._command_server.start() # drop root privileges; command server will remain as the only # daemon process with root privileges. while root plugins have root # shell access, they are known and the commands are logged by the # command server. self._drop_privs() # fork the task runner self._task_runner.start() # setup signal handlers self._reg_sighandlers() while self.running: time.sleep(self._sleep_period) self.shutdown()
[ "def", "run", "(", "self", ",", "start_command_srv", ")", ":", "if", "start_command_srv", ":", "# note, this must be established *before* the task runner is forked", "# so the task runner can communicate with the command server.", "# fork the command server", "self", ".", "_command_server", ".", "start", "(", ")", "# drop root privileges; command server will remain as the only", "# daemon process with root privileges. while root plugins have root", "# shell access, they are known and the commands are logged by the", "# command server.", "self", ".", "_drop_privs", "(", ")", "# fork the task runner", "self", ".", "_task_runner", ".", "start", "(", ")", "# setup signal handlers", "self", ".", "_reg_sighandlers", "(", ")", "while", "self", ".", "running", ":", "time", ".", "sleep", "(", "self", ".", "_sleep_period", ")", "self", ".", "shutdown", "(", ")" ]
Setup daemon process, start child forks, and sleep until events are signalled. `start_command_srv` Set to ``True`` if command server should be started.
[ "Setup", "daemon", "process", "start", "child", "forks", "and", "sleep", "until", "events", "are", "signalled", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L318-L348
246,843
xtrementl/focus
focus/daemon.py
Focusd.running
def running(self): """ Determines if daemon is active. Returns boolean. """ # check if task is active and pid file exists return (not self._exited and os.path.isfile(self._pidfile) and self._task.active)
python
def running(self): """ Determines if daemon is active. Returns boolean. """ # check if task is active and pid file exists return (not self._exited and os.path.isfile(self._pidfile) and self._task.active)
[ "def", "running", "(", "self", ")", ":", "# check if task is active and pid file exists", "return", "(", "not", "self", ".", "_exited", "and", "os", ".", "path", ".", "isfile", "(", "self", ".", "_pidfile", ")", "and", "self", ".", "_task", ".", "active", ")" ]
Determines if daemon is active. Returns boolean.
[ "Determines", "if", "daemon", "is", "active", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L351-L359
246,844
xtrementl/focus
focus/daemon.py
TaskProcess._register_sigterm
def _register_sigterm(self): """ Registers SIGTERM signal handler. """ _handler = lambda signo, frame: self.shutdown() signal.signal(signal.SIGTERM, _handler)
python
def _register_sigterm(self): """ Registers SIGTERM signal handler. """ _handler = lambda signo, frame: self.shutdown() signal.signal(signal.SIGTERM, _handler)
[ "def", "_register_sigterm", "(", "self", ")", ":", "_handler", "=", "lambda", "signo", ",", "frame", ":", "self", ".", "shutdown", "(", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "_handler", ")" ]
Registers SIGTERM signal handler.
[ "Registers", "SIGTERM", "signal", "handler", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L382-L387
246,845
xtrementl/focus
focus/daemon.py
TaskProcess.run
def run(self): """ Main process loop. """ self._prepare() while self.running: if self._run() is False: break time.sleep(self._sleep_period) self.shutdown()
python
def run(self): """ Main process loop. """ self._prepare() while self.running: if self._run() is False: break time.sleep(self._sleep_period) self.shutdown()
[ "def", "run", "(", "self", ")", ":", "self", ".", "_prepare", "(", ")", "while", "self", ".", "running", ":", "if", "self", ".", "_run", "(", ")", "is", "False", ":", "break", "time", ".", "sleep", "(", "self", ".", "_sleep_period", ")", "self", ".", "shutdown", "(", ")" ]
Main process loop.
[ "Main", "process", "loop", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L401-L412
246,846
xtrementl/focus
focus/daemon.py
TaskRunner._setup_root_plugins
def _setup_root_plugins(self): """ Injects a `run_root` method into the registered root event plugins. """ def run_root(_self, command): """ Executes a shell command as root. `command` Shell command string. Returns boolean. """ try: # get lock, so this plugin has exclusive access to command pipe self._rlock.acquire() # TODO: log root command for this plugin self._cmd_pipe.send_bytes('\x80'.join(['SHL', command])) res = self._cmd_pipe.recv_bytes() if res != 'TRM': # sentinel value, shutdown return res == 'OK' except (EOFError, IOError): pass finally: self._rlock.release() self.shutdown(skip_hooks=True) return False # inject method into each event plugin for plugin in registration.get_registered(event_hooks=True, root_access=True): plugin.run_root = types.MethodType(run_root, plugin)
python
def _setup_root_plugins(self): """ Injects a `run_root` method into the registered root event plugins. """ def run_root(_self, command): """ Executes a shell command as root. `command` Shell command string. Returns boolean. """ try: # get lock, so this plugin has exclusive access to command pipe self._rlock.acquire() # TODO: log root command for this plugin self._cmd_pipe.send_bytes('\x80'.join(['SHL', command])) res = self._cmd_pipe.recv_bytes() if res != 'TRM': # sentinel value, shutdown return res == 'OK' except (EOFError, IOError): pass finally: self._rlock.release() self.shutdown(skip_hooks=True) return False # inject method into each event plugin for plugin in registration.get_registered(event_hooks=True, root_access=True): plugin.run_root = types.MethodType(run_root, plugin)
[ "def", "_setup_root_plugins", "(", "self", ")", ":", "def", "run_root", "(", "_self", ",", "command", ")", ":", "\"\"\" Executes a shell command as root.\n\n `command`\n Shell command string.\n\n Returns boolean.\n \"\"\"", "try", ":", "# get lock, so this plugin has exclusive access to command pipe", "self", ".", "_rlock", ".", "acquire", "(", ")", "# TODO: log root command for this plugin", "self", ".", "_cmd_pipe", ".", "send_bytes", "(", "'\\x80'", ".", "join", "(", "[", "'SHL'", ",", "command", "]", ")", ")", "res", "=", "self", ".", "_cmd_pipe", ".", "recv_bytes", "(", ")", "if", "res", "!=", "'TRM'", ":", "# sentinel value, shutdown", "return", "res", "==", "'OK'", "except", "(", "EOFError", ",", "IOError", ")", ":", "pass", "finally", ":", "self", ".", "_rlock", ".", "release", "(", ")", "self", ".", "shutdown", "(", "skip_hooks", "=", "True", ")", "return", "False", "# inject method into each event plugin", "for", "plugin", "in", "registration", ".", "get_registered", "(", "event_hooks", "=", "True", ",", "root_access", "=", "True", ")", ":", "plugin", ".", "run_root", "=", "types", ".", "MethodType", "(", "run_root", ",", "plugin", ")" ]
Injects a `run_root` method into the registered root event plugins.
[ "Injects", "a", "run_root", "method", "into", "the", "registered", "root", "event", "plugins", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L447-L483
246,847
xtrementl/focus
focus/daemon.py
TaskRunner._run_events
def _run_events(self, shutdown=False): """ Runs event hooks for registered event plugins. `shutdown` Set to ``True`` to run task_end events; otherwise, run task_run events. """ # run task_start events, if not ran already if not self._ran_taskstart: self._ran_taskstart = True registration.run_event_hooks('task_start', self._task) # run events event = 'task_end' if shutdown else 'task_run' registration.run_event_hooks(event, self._task) # reclaim any subprocesses plugins may have forked try: os.waitpid(-1, os.P_NOWAIT) except OSError: pass
python
def _run_events(self, shutdown=False): """ Runs event hooks for registered event plugins. `shutdown` Set to ``True`` to run task_end events; otherwise, run task_run events. """ # run task_start events, if not ran already if not self._ran_taskstart: self._ran_taskstart = True registration.run_event_hooks('task_start', self._task) # run events event = 'task_end' if shutdown else 'task_run' registration.run_event_hooks(event, self._task) # reclaim any subprocesses plugins may have forked try: os.waitpid(-1, os.P_NOWAIT) except OSError: pass
[ "def", "_run_events", "(", "self", ",", "shutdown", "=", "False", ")", ":", "# run task_start events, if not ran already", "if", "not", "self", ".", "_ran_taskstart", ":", "self", ".", "_ran_taskstart", "=", "True", "registration", ".", "run_event_hooks", "(", "'task_start'", ",", "self", ".", "_task", ")", "# run events", "event", "=", "'task_end'", "if", "shutdown", "else", "'task_run'", "registration", ".", "run_event_hooks", "(", "event", ",", "self", ".", "_task", ")", "# reclaim any subprocesses plugins may have forked", "try", ":", "os", ".", "waitpid", "(", "-", "1", ",", "os", ".", "P_NOWAIT", ")", "except", "OSError", ":", "pass" ]
Runs event hooks for registered event plugins. `shutdown` Set to ``True`` to run task_end events; otherwise, run task_run events.
[ "Runs", "event", "hooks", "for", "registered", "event", "plugins", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L485-L506
246,848
xtrementl/focus
focus/daemon.py
CommandServer._process_commands
def _process_commands(self): """ Processes commands received and executes them accordingly. Returns ``True`` if successful, ``False`` if connection closed or server terminated. """ try: # poll for data, so we don't block forever if self._cmd_pipe.poll(1): # 1 sec timeout payload = self._cmd_pipe.recv_bytes() if payload: # segment payload parts = payload.split('\x80', 2) _op = parts[0] # terminate operation if _op == 'TRM': raise EOFError # shell command operation elif _op == 'SHL' and len(parts) == 2: command = parts[1] if command: # run command and return success or fail res = common.shell_process(command) if res is not None: self._cmd_pipe.send_bytes('OK') return True # everything else, should reply with "FAIL" self._cmd_pipe.send_bytes('FAIL') except (EOFError, IOError): return False else: return True
python
def _process_commands(self): """ Processes commands received and executes them accordingly. Returns ``True`` if successful, ``False`` if connection closed or server terminated. """ try: # poll for data, so we don't block forever if self._cmd_pipe.poll(1): # 1 sec timeout payload = self._cmd_pipe.recv_bytes() if payload: # segment payload parts = payload.split('\x80', 2) _op = parts[0] # terminate operation if _op == 'TRM': raise EOFError # shell command operation elif _op == 'SHL' and len(parts) == 2: command = parts[1] if command: # run command and return success or fail res = common.shell_process(command) if res is not None: self._cmd_pipe.send_bytes('OK') return True # everything else, should reply with "FAIL" self._cmd_pipe.send_bytes('FAIL') except (EOFError, IOError): return False else: return True
[ "def", "_process_commands", "(", "self", ")", ":", "try", ":", "# poll for data, so we don't block forever", "if", "self", ".", "_cmd_pipe", ".", "poll", "(", "1", ")", ":", "# 1 sec timeout", "payload", "=", "self", ".", "_cmd_pipe", ".", "recv_bytes", "(", ")", "if", "payload", ":", "# segment payload", "parts", "=", "payload", ".", "split", "(", "'\\x80'", ",", "2", ")", "_op", "=", "parts", "[", "0", "]", "# terminate operation", "if", "_op", "==", "'TRM'", ":", "raise", "EOFError", "# shell command operation", "elif", "_op", "==", "'SHL'", "and", "len", "(", "parts", ")", "==", "2", ":", "command", "=", "parts", "[", "1", "]", "if", "command", ":", "# run command and return success or fail", "res", "=", "common", ".", "shell_process", "(", "command", ")", "if", "res", "is", "not", "None", ":", "self", ".", "_cmd_pipe", ".", "send_bytes", "(", "'OK'", ")", "return", "True", "# everything else, should reply with \"FAIL\"", "self", ".", "_cmd_pipe", ".", "send_bytes", "(", "'FAIL'", ")", "except", "(", "EOFError", ",", "IOError", ")", ":", "return", "False", "else", ":", "return", "True" ]
Processes commands received and executes them accordingly. Returns ``True`` if successful, ``False`` if connection closed or server terminated.
[ "Processes", "commands", "received", "and", "executes", "them", "accordingly", ".", "Returns", "True", "if", "successful", "False", "if", "connection", "closed", "or", "server", "terminated", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L557-L596
246,849
fotonauts/fwissr-python
fwissr/source/mongodb.py
Mongodb.from_settings
def from_settings(cls, settings): """Read Mongodb Source configuration from the provided settings""" if not 'mongodb' in settings or not 'collection' in settings or \ settings['mongodb'] == '' or settings['collection'] == '': raise Exception( "Erroneous mongodb settings, " "needs a collection and mongodb setting", settings) cx_uri = urlparse.urlsplit(settings["mongodb"]) db_name = cx_uri.path if '?' in db_name: db_name, query = db_name.split('?', 1) db_name = db_name[1:] if db_name == "": raise Exception( "Erroneous mongodb settings, " "missing db_name", settings) cx_uri = urlparse.urlunsplit( (cx_uri.scheme, cx_uri.netloc, "/", cx_uri.query, cx_uri.fragment)) options = copy.deepcopy(settings) del options['mongodb'] del options['collection'] return Mongodb( cls.connection_for_uri(cx_uri), db_name, settings['collection'], options)
python
def from_settings(cls, settings): """Read Mongodb Source configuration from the provided settings""" if not 'mongodb' in settings or not 'collection' in settings or \ settings['mongodb'] == '' or settings['collection'] == '': raise Exception( "Erroneous mongodb settings, " "needs a collection and mongodb setting", settings) cx_uri = urlparse.urlsplit(settings["mongodb"]) db_name = cx_uri.path if '?' in db_name: db_name, query = db_name.split('?', 1) db_name = db_name[1:] if db_name == "": raise Exception( "Erroneous mongodb settings, " "missing db_name", settings) cx_uri = urlparse.urlunsplit( (cx_uri.scheme, cx_uri.netloc, "/", cx_uri.query, cx_uri.fragment)) options = copy.deepcopy(settings) del options['mongodb'] del options['collection'] return Mongodb( cls.connection_for_uri(cx_uri), db_name, settings['collection'], options)
[ "def", "from_settings", "(", "cls", ",", "settings", ")", ":", "if", "not", "'mongodb'", "in", "settings", "or", "not", "'collection'", "in", "settings", "or", "settings", "[", "'mongodb'", "]", "==", "''", "or", "settings", "[", "'collection'", "]", "==", "''", ":", "raise", "Exception", "(", "\"Erroneous mongodb settings, \"", "\"needs a collection and mongodb setting\"", ",", "settings", ")", "cx_uri", "=", "urlparse", ".", "urlsplit", "(", "settings", "[", "\"mongodb\"", "]", ")", "db_name", "=", "cx_uri", ".", "path", "if", "'?'", "in", "db_name", ":", "db_name", ",", "query", "=", "db_name", ".", "split", "(", "'?'", ",", "1", ")", "db_name", "=", "db_name", "[", "1", ":", "]", "if", "db_name", "==", "\"\"", ":", "raise", "Exception", "(", "\"Erroneous mongodb settings, \"", "\"missing db_name\"", ",", "settings", ")", "cx_uri", "=", "urlparse", ".", "urlunsplit", "(", "(", "cx_uri", ".", "scheme", ",", "cx_uri", ".", "netloc", ",", "\"/\"", ",", "cx_uri", ".", "query", ",", "cx_uri", ".", "fragment", ")", ")", "options", "=", "copy", ".", "deepcopy", "(", "settings", ")", "del", "options", "[", "'mongodb'", "]", "del", "options", "[", "'collection'", "]", "return", "Mongodb", "(", "cls", ".", "connection_for_uri", "(", "cx_uri", ")", ",", "db_name", ",", "settings", "[", "'collection'", "]", ",", "options", ")" ]
Read Mongodb Source configuration from the provided settings
[ "Read", "Mongodb", "Source", "configuration", "from", "the", "provided", "settings" ]
4314aa53ca45b4534cd312f6343a88596b4416d4
https://github.com/fotonauts/fwissr-python/blob/4314aa53ca45b4534cd312f6343a88596b4416d4/fwissr/source/mongodb.py#L14-L44
246,850
fred49/linshare-api
linshareapi/cache.py
compute_key
def compute_key(cli, familly, discriminant=None): """This function is used to compute a unique key from all connection parametters.""" hash_key = hashlib.sha256() hash_key.update(familly) hash_key.update(cli.host) hash_key.update(cli.user) hash_key.update(cli.password) if discriminant: if isinstance(discriminant, list): for i in discriminant: if i is not None and i is not False: hash_key.update(str(i)) elif isinstance(discriminant, tuple): for i in discriminant: if i is not None and i is not False: hash_key.update(str(i)) else: hash_key.update(discriminant) hash_key = hash_key.hexdigest() cli.log.debug("hash_key: " + hash_key) return hash_key
python
def compute_key(cli, familly, discriminant=None): """This function is used to compute a unique key from all connection parametters.""" hash_key = hashlib.sha256() hash_key.update(familly) hash_key.update(cli.host) hash_key.update(cli.user) hash_key.update(cli.password) if discriminant: if isinstance(discriminant, list): for i in discriminant: if i is not None and i is not False: hash_key.update(str(i)) elif isinstance(discriminant, tuple): for i in discriminant: if i is not None and i is not False: hash_key.update(str(i)) else: hash_key.update(discriminant) hash_key = hash_key.hexdigest() cli.log.debug("hash_key: " + hash_key) return hash_key
[ "def", "compute_key", "(", "cli", ",", "familly", ",", "discriminant", "=", "None", ")", ":", "hash_key", "=", "hashlib", ".", "sha256", "(", ")", "hash_key", ".", "update", "(", "familly", ")", "hash_key", ".", "update", "(", "cli", ".", "host", ")", "hash_key", ".", "update", "(", "cli", ".", "user", ")", "hash_key", ".", "update", "(", "cli", ".", "password", ")", "if", "discriminant", ":", "if", "isinstance", "(", "discriminant", ",", "list", ")", ":", "for", "i", "in", "discriminant", ":", "if", "i", "is", "not", "None", "and", "i", "is", "not", "False", ":", "hash_key", ".", "update", "(", "str", "(", "i", ")", ")", "elif", "isinstance", "(", "discriminant", ",", "tuple", ")", ":", "for", "i", "in", "discriminant", ":", "if", "i", "is", "not", "None", "and", "i", "is", "not", "False", ":", "hash_key", ".", "update", "(", "str", "(", "i", ")", ")", "else", ":", "hash_key", ".", "update", "(", "discriminant", ")", "hash_key", "=", "hash_key", ".", "hexdigest", "(", ")", "cli", ".", "log", ".", "debug", "(", "\"hash_key: \"", "+", "hash_key", ")", "return", "hash_key" ]
This function is used to compute a unique key from all connection parametters.
[ "This", "function", "is", "used", "to", "compute", "a", "unique", "key", "from", "all", "connection", "parametters", "." ]
be646c25aa8ba3718abb6869c620b157d53d6e41
https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/cache.py#L18-L38
246,851
fred49/linshare-api
linshareapi/cache.py
Invalid.override_familly
def override_familly(self, args): """Look in the current wrapped object to find a cache configuration to override the current default configuration.""" resourceapi = args[0] cache_cfg = resourceapi.cache if cache_cfg.has_key('familly'): self.familly = cache_cfg['familly'] if cache_cfg.has_key('whole_familly'): self.whole_familly = cache_cfg['whole_familly'] if self.familly is None: raise Exception("Invalid familly value for Cache decorator.")
python
def override_familly(self, args): """Look in the current wrapped object to find a cache configuration to override the current default configuration.""" resourceapi = args[0] cache_cfg = resourceapi.cache if cache_cfg.has_key('familly'): self.familly = cache_cfg['familly'] if cache_cfg.has_key('whole_familly'): self.whole_familly = cache_cfg['whole_familly'] if self.familly is None: raise Exception("Invalid familly value for Cache decorator.")
[ "def", "override_familly", "(", "self", ",", "args", ")", ":", "resourceapi", "=", "args", "[", "0", "]", "cache_cfg", "=", "resourceapi", ".", "cache", "if", "cache_cfg", ".", "has_key", "(", "'familly'", ")", ":", "self", ".", "familly", "=", "cache_cfg", "[", "'familly'", "]", "if", "cache_cfg", ".", "has_key", "(", "'whole_familly'", ")", ":", "self", ".", "whole_familly", "=", "cache_cfg", "[", "'whole_familly'", "]", "if", "self", ".", "familly", "is", "None", ":", "raise", "Exception", "(", "\"Invalid familly value for Cache decorator.\"", ")" ]
Look in the current wrapped object to find a cache configuration to override the current default configuration.
[ "Look", "in", "the", "current", "wrapped", "object", "to", "find", "a", "cache", "configuration", "to", "override", "the", "current", "default", "configuration", "." ]
be646c25aa8ba3718abb6869c620b157d53d6e41
https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/cache.py#L117-L127
246,852
etcher-be/elib_config
elib_config/_utils.py
friendly_type_name
def friendly_type_name(raw_type: typing.Type) -> str: """ Returns a user-friendly type name :param raw_type: raw type (str, int, ...) :return: user friendly type as string """ try: return _TRANSLATE_TYPE[raw_type] except KeyError: LOGGER.error('unmanaged value type: %s', raw_type) return str(raw_type)
python
def friendly_type_name(raw_type: typing.Type) -> str: """ Returns a user-friendly type name :param raw_type: raw type (str, int, ...) :return: user friendly type as string """ try: return _TRANSLATE_TYPE[raw_type] except KeyError: LOGGER.error('unmanaged value type: %s', raw_type) return str(raw_type)
[ "def", "friendly_type_name", "(", "raw_type", ":", "typing", ".", "Type", ")", "->", "str", ":", "try", ":", "return", "_TRANSLATE_TYPE", "[", "raw_type", "]", "except", "KeyError", ":", "LOGGER", ".", "error", "(", "'unmanaged value type: %s'", ",", "raw_type", ")", "return", "str", "(", "raw_type", ")" ]
Returns a user-friendly type name :param raw_type: raw type (str, int, ...) :return: user friendly type as string
[ "Returns", "a", "user", "-", "friendly", "type", "name" ]
5d8c839e84d70126620ab0186dc1f717e5868bd0
https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_utils.py#L28-L39
246,853
smartmob-project/dotenvfile
dotenvfile/__init__.py
loads
def loads(content): """Loads variable definitions from a string.""" lines = _group_lines(line for line in content.split('\n')) lines = [ (i, _parse_envfile_line(line)) for i, line in lines if line.strip() ] errors = [] # Reject files with duplicate variables (no sane default). duplicates = _find_duplicates(((i, line[0]) for i, line in lines)) for i, variable, j in duplicates: errors.append(''.join([ 'Line %d: duplicate environment variable "%s": ', 'already appears on line %d.', ]) % (i + 1, variable, j + 1) ) # Done! if errors: raise ValueError(errors) return {k: v for _, (k, v) in lines}
python
def loads(content): """Loads variable definitions from a string.""" lines = _group_lines(line for line in content.split('\n')) lines = [ (i, _parse_envfile_line(line)) for i, line in lines if line.strip() ] errors = [] # Reject files with duplicate variables (no sane default). duplicates = _find_duplicates(((i, line[0]) for i, line in lines)) for i, variable, j in duplicates: errors.append(''.join([ 'Line %d: duplicate environment variable "%s": ', 'already appears on line %d.', ]) % (i + 1, variable, j + 1) ) # Done! if errors: raise ValueError(errors) return {k: v for _, (k, v) in lines}
[ "def", "loads", "(", "content", ")", ":", "lines", "=", "_group_lines", "(", "line", "for", "line", "in", "content", ".", "split", "(", "'\\n'", ")", ")", "lines", "=", "[", "(", "i", ",", "_parse_envfile_line", "(", "line", ")", ")", "for", "i", ",", "line", "in", "lines", "if", "line", ".", "strip", "(", ")", "]", "errors", "=", "[", "]", "# Reject files with duplicate variables (no sane default).", "duplicates", "=", "_find_duplicates", "(", "(", "(", "i", ",", "line", "[", "0", "]", ")", "for", "i", ",", "line", "in", "lines", ")", ")", "for", "i", ",", "variable", ",", "j", "in", "duplicates", ":", "errors", ".", "append", "(", "''", ".", "join", "(", "[", "'Line %d: duplicate environment variable \"%s\": '", ",", "'already appears on line %d.'", ",", "]", ")", "%", "(", "i", "+", "1", ",", "variable", ",", "j", "+", "1", ")", ")", "# Done!", "if", "errors", ":", "raise", "ValueError", "(", "errors", ")", "return", "{", "k", ":", "v", "for", "_", ",", "(", "k", ",", "v", ")", "in", "lines", "}" ]
Loads variable definitions from a string.
[ "Loads", "variable", "definitions", "from", "a", "string", "." ]
8a71eddfe73669c8fcd97a0062845257753ad85a
https://github.com/smartmob-project/dotenvfile/blob/8a71eddfe73669c8fcd97a0062845257753ad85a/dotenvfile/__init__.py#L73-L92
246,854
Vesuvium/aratrum
aratrum/Aratrum.py
Aratrum.get
def get(self): """ Loads the configuration and returns it as a dictionary """ with open(self.filename, 'r') as f: self.config = ujson.load(f) return self.config
python
def get(self): """ Loads the configuration and returns it as a dictionary """ with open(self.filename, 'r') as f: self.config = ujson.load(f) return self.config
[ "def", "get", "(", "self", ")", ":", "with", "open", "(", "self", ".", "filename", ",", "'r'", ")", "as", "f", ":", "self", ".", "config", "=", "ujson", ".", "load", "(", "f", ")", "return", "self", ".", "config" ]
Loads the configuration and returns it as a dictionary
[ "Loads", "the", "configuration", "and", "returns", "it", "as", "a", "dictionary" ]
7d237fe0c2afd615cf758a2a6485e93fa879b7e1
https://github.com/Vesuvium/aratrum/blob/7d237fe0c2afd615cf758a2a6485e93fa879b7e1/aratrum/Aratrum.py#L17-L23
246,855
Vesuvium/aratrum
aratrum/Aratrum.py
Aratrum.set
def set(self, option, value): """ Sets an option to a value. """ if self.config is None: self.config = {} self.config[option] = value
python
def set(self, option, value): """ Sets an option to a value. """ if self.config is None: self.config = {} self.config[option] = value
[ "def", "set", "(", "self", ",", "option", ",", "value", ")", ":", "if", "self", ".", "config", "is", "None", ":", "self", ".", "config", "=", "{", "}", "self", ".", "config", "[", "option", "]", "=", "value" ]
Sets an option to a value.
[ "Sets", "an", "option", "to", "a", "value", "." ]
7d237fe0c2afd615cf758a2a6485e93fa879b7e1
https://github.com/Vesuvium/aratrum/blob/7d237fe0c2afd615cf758a2a6485e93fa879b7e1/aratrum/Aratrum.py#L31-L37
246,856
Vesuvium/aratrum
aratrum/Aratrum.py
Aratrum.delete
def delete(self, option): """ Deletes an option if exists """ if self.config is not None: if option in self.config: del self.config[option]
python
def delete(self, option): """ Deletes an option if exists """ if self.config is not None: if option in self.config: del self.config[option]
[ "def", "delete", "(", "self", ",", "option", ")", ":", "if", "self", ".", "config", "is", "not", "None", ":", "if", "option", "in", "self", ".", "config", ":", "del", "self", ".", "config", "[", "option", "]" ]
Deletes an option if exists
[ "Deletes", "an", "option", "if", "exists" ]
7d237fe0c2afd615cf758a2a6485e93fa879b7e1
https://github.com/Vesuvium/aratrum/blob/7d237fe0c2afd615cf758a2a6485e93fa879b7e1/aratrum/Aratrum.py#L39-L45
246,857
Vesuvium/aratrum
aratrum/Aratrum.py
Aratrum.save
def save(self): """ Saves the configuration """ with open(self.filename, 'w') as f: ujson.dump(self.config, f, indent=4)
python
def save(self): """ Saves the configuration """ with open(self.filename, 'w') as f: ujson.dump(self.config, f, indent=4)
[ "def", "save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "filename", ",", "'w'", ")", "as", "f", ":", "ujson", ".", "dump", "(", "self", ".", "config", ",", "f", ",", "indent", "=", "4", ")" ]
Saves the configuration
[ "Saves", "the", "configuration" ]
7d237fe0c2afd615cf758a2a6485e93fa879b7e1
https://github.com/Vesuvium/aratrum/blob/7d237fe0c2afd615cf758a2a6485e93fa879b7e1/aratrum/Aratrum.py#L47-L52
246,858
bmweiner/skillful
skillful/validate.py
timestamp
def timestamp(stamp, tolerance=150): """Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise. """ try: tolerance = datetime.timedelta(0, tolerance) timestamp_low = dateutil.parser.parse(stamp) timestamp_high = timestamp_low + tolerance now = datetime.datetime.now(timestamp_low.tzinfo) except ValueError: return False return now >= timestamp_low and now <= timestamp_high
python
def timestamp(stamp, tolerance=150): """Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise. """ try: tolerance = datetime.timedelta(0, tolerance) timestamp_low = dateutil.parser.parse(stamp) timestamp_high = timestamp_low + tolerance now = datetime.datetime.now(timestamp_low.tzinfo) except ValueError: return False return now >= timestamp_low and now <= timestamp_high
[ "def", "timestamp", "(", "stamp", ",", "tolerance", "=", "150", ")", ":", "try", ":", "tolerance", "=", "datetime", ".", "timedelta", "(", "0", ",", "tolerance", ")", "timestamp_low", "=", "dateutil", ".", "parser", ".", "parse", "(", "stamp", ")", "timestamp_high", "=", "timestamp_low", "+", "tolerance", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "timestamp_low", ".", "tzinfo", ")", "except", "ValueError", ":", "return", "False", "return", "now", ">=", "timestamp_low", "and", "now", "<=", "timestamp_high" ]
Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise.
[ "Validate", "timestamp", "specified", "by", "request", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L21-L41
246,859
bmweiner/skillful
skillful/validate.py
signature_cert_chain_url
def signature_cert_chain_url(url): """Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise. """ r = urlparse(url) if not r.scheme.lower() == 'https': warnings.warn('Certificate URL scheme is invalid.') return False if not r.hostname.lower() == 's3.amazonaws.com': warnings.warn('Certificate URL hostname is invalid.') return False if not os.path.normpath(r.path).startswith('/echo.api/'): warnings.warn('Certificate URL path is invalid.') return False if r.port and not r.port == 443: warnings.warn('Certificate URL port is invalid.') return False return True
python
def signature_cert_chain_url(url): """Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise. """ r = urlparse(url) if not r.scheme.lower() == 'https': warnings.warn('Certificate URL scheme is invalid.') return False if not r.hostname.lower() == 's3.amazonaws.com': warnings.warn('Certificate URL hostname is invalid.') return False if not os.path.normpath(r.path).startswith('/echo.api/'): warnings.warn('Certificate URL path is invalid.') return False if r.port and not r.port == 443: warnings.warn('Certificate URL port is invalid.') return False return True
[ "def", "signature_cert_chain_url", "(", "url", ")", ":", "r", "=", "urlparse", "(", "url", ")", "if", "not", "r", ".", "scheme", ".", "lower", "(", ")", "==", "'https'", ":", "warnings", ".", "warn", "(", "'Certificate URL scheme is invalid.'", ")", "return", "False", "if", "not", "r", ".", "hostname", ".", "lower", "(", ")", "==", "'s3.amazonaws.com'", ":", "warnings", ".", "warn", "(", "'Certificate URL hostname is invalid.'", ")", "return", "False", "if", "not", "os", ".", "path", ".", "normpath", "(", "r", ".", "path", ")", ".", "startswith", "(", "'/echo.api/'", ")", ":", "warnings", ".", "warn", "(", "'Certificate URL path is invalid.'", ")", "return", "False", "if", "r", ".", "port", "and", "not", "r", ".", "port", "==", "443", ":", "warnings", ".", "warn", "(", "'Certificate URL port is invalid.'", ")", "return", "False", "return", "True" ]
Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise.
[ "Validate", "URL", "specified", "by", "SignatureCertChainUrl", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L43-L67
246,860
bmweiner/skillful
skillful/validate.py
retrieve
def retrieve(url): """Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ try: pem_data = urlopen(url).read() except (ValueError, HTTPError): warnings.warn('Certificate URL is invalid.') return False if sys.version >= '3': try: pem_data = pem_data.decode() except(UnicodeDecodeError): warnings.warn('Certificate encoding is not utf-8.') return False return _parse_pem_data(pem_data)
python
def retrieve(url): """Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ try: pem_data = urlopen(url).read() except (ValueError, HTTPError): warnings.warn('Certificate URL is invalid.') return False if sys.version >= '3': try: pem_data = pem_data.decode() except(UnicodeDecodeError): warnings.warn('Certificate encoding is not utf-8.') return False return _parse_pem_data(pem_data)
[ "def", "retrieve", "(", "url", ")", ":", "try", ":", "pem_data", "=", "urlopen", "(", "url", ")", ".", "read", "(", ")", "except", "(", "ValueError", ",", "HTTPError", ")", ":", "warnings", ".", "warn", "(", "'Certificate URL is invalid.'", ")", "return", "False", "if", "sys", ".", "version", ">=", "'3'", ":", "try", ":", "pem_data", "=", "pem_data", ".", "decode", "(", ")", "except", "(", "UnicodeDecodeError", ")", ":", "warnings", ".", "warn", "(", "'Certificate encoding is not utf-8.'", ")", "return", "False", "return", "_parse_pem_data", "(", "pem_data", ")" ]
Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False.
[ "Retrieve", "and", "parse", "PEM", "-", "encoded", "X", ".", "509", "certificate", "chain", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L69-L96
246,861
bmweiner/skillful
skillful/validate.py
_parse_pem_data
def _parse_pem_data(pem_data): """Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ sep = '-----BEGIN CERTIFICATE-----' cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]] certs = [] load_cert = x509.load_pem_x509_certificate for cert in cert_chain: try: certs.append(load_cert(cert, default_backend())) except ValueError: warnings.warn('Certificate is invalid.') return False return certs
python
def _parse_pem_data(pem_data): """Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ sep = '-----BEGIN CERTIFICATE-----' cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]] certs = [] load_cert = x509.load_pem_x509_certificate for cert in cert_chain: try: certs.append(load_cert(cert, default_backend())) except ValueError: warnings.warn('Certificate is invalid.') return False return certs
[ "def", "_parse_pem_data", "(", "pem_data", ")", ":", "sep", "=", "'-----BEGIN CERTIFICATE-----'", "cert_chain", "=", "[", "six", ".", "b", "(", "sep", "+", "s", ")", "for", "s", "in", "pem_data", ".", "split", "(", "sep", ")", "[", "1", ":", "]", "]", "certs", "=", "[", "]", "load_cert", "=", "x509", ".", "load_pem_x509_certificate", "for", "cert", "in", "cert_chain", ":", "try", ":", "certs", ".", "append", "(", "load_cert", "(", "cert", ",", "default_backend", "(", ")", ")", ")", "except", "ValueError", ":", "warnings", ".", "warn", "(", "'Certificate is invalid.'", ")", "return", "False", "return", "certs" ]
Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False.
[ "Parse", "PEM", "-", "encoded", "X", ".", "509", "certificate", "chain", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L98-L121
246,862
bmweiner/skillful
skillful/validate.py
cert_chain
def cert_chain(certs): """Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise. """ if len(certs) < 2: warnings.warn('Certificate chain contains < 3 certificates.') return False cert = certs[0] today = datetime.datetime.today() if not today > cert.not_valid_before: warnings.warn('Certificate Not Before date is invalid.') return False if not today < cert.not_valid_after: warnings.warn('Certificate Not After date is invalid.') return False oid_san = x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME ext = cert.extensions.get_extension_for_oid(oid_san) sans = ext.value.get_values_for_type(x509.DNSName) if not 'echo-api.amazon.com' in sans: return False for i in range(len(certs) - 1): if not certs[i].issuer == certs[i + 1].subject: return False return True
python
def cert_chain(certs): """Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise. """ if len(certs) < 2: warnings.warn('Certificate chain contains < 3 certificates.') return False cert = certs[0] today = datetime.datetime.today() if not today > cert.not_valid_before: warnings.warn('Certificate Not Before date is invalid.') return False if not today < cert.not_valid_after: warnings.warn('Certificate Not After date is invalid.') return False oid_san = x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME ext = cert.extensions.get_extension_for_oid(oid_san) sans = ext.value.get_values_for_type(x509.DNSName) if not 'echo-api.amazon.com' in sans: return False for i in range(len(certs) - 1): if not certs[i].issuer == certs[i + 1].subject: return False return True
[ "def", "cert_chain", "(", "certs", ")", ":", "if", "len", "(", "certs", ")", "<", "2", ":", "warnings", ".", "warn", "(", "'Certificate chain contains < 3 certificates.'", ")", "return", "False", "cert", "=", "certs", "[", "0", "]", "today", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "if", "not", "today", ">", "cert", ".", "not_valid_before", ":", "warnings", ".", "warn", "(", "'Certificate Not Before date is invalid.'", ")", "return", "False", "if", "not", "today", "<", "cert", ".", "not_valid_after", ":", "warnings", ".", "warn", "(", "'Certificate Not After date is invalid.'", ")", "return", "False", "oid_san", "=", "x509", ".", "oid", ".", "ExtensionOID", ".", "SUBJECT_ALTERNATIVE_NAME", "ext", "=", "cert", ".", "extensions", ".", "get_extension_for_oid", "(", "oid_san", ")", "sans", "=", "ext", ".", "value", ".", "get_values_for_type", "(", "x509", ".", "DNSName", ")", "if", "not", "'echo-api.amazon.com'", "in", "sans", ":", "return", "False", "for", "i", "in", "range", "(", "len", "(", "certs", ")", "-", "1", ")", ":", "if", "not", "certs", "[", "i", "]", ".", "issuer", "==", "certs", "[", "i", "+", "1", "]", ".", "subject", ":", "return", "False", "return", "True" ]
Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise.
[ "Validate", "PEM", "-", "encoded", "X", ".", "509", "certificate", "chain", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L123-L159
246,863
bmweiner/skillful
skillful/validate.py
signature
def signature(cert, sig, body): """Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise. """ body = six.b(body) sig = base64.decodestring(sig) padder = padding.PKCS1v15() public_key = cert.public_key() try: public_key.verify(sig, body, padder, hashes.SHA1()) return True except InvalidSignature: warnings.warn('Signature verification failed.') return False
python
def signature(cert, sig, body): """Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise. """ body = six.b(body) sig = base64.decodestring(sig) padder = padding.PKCS1v15() public_key = cert.public_key() try: public_key.verify(sig, body, padder, hashes.SHA1()) return True except InvalidSignature: warnings.warn('Signature verification failed.') return False
[ "def", "signature", "(", "cert", ",", "sig", ",", "body", ")", ":", "body", "=", "six", ".", "b", "(", "body", ")", "sig", "=", "base64", ".", "decodestring", "(", "sig", ")", "padder", "=", "padding", ".", "PKCS1v15", "(", ")", "public_key", "=", "cert", ".", "public_key", "(", ")", "try", ":", "public_key", ".", "verify", "(", "sig", ",", "body", ",", "padder", ",", "hashes", ".", "SHA1", "(", ")", ")", "return", "True", "except", "InvalidSignature", ":", "warnings", ".", "warn", "(", "'Signature verification failed.'", ")", "return", "False" ]
Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise.
[ "Validate", "data", "request", "signature", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L161-L185
246,864
bmweiner/skillful
skillful/validate.py
Valid.application_id
def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True
python
def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True
[ "def", "application_id", "(", "self", ",", "app_id", ")", ":", "if", "self", ".", "app_id", "!=", "app_id", ":", "warnings", ".", "warn", "(", "'Application ID is invalid.'", ")", "return", "False", "return", "True" ]
Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise.
[ "Validate", "request", "application", "id", "matches", "true", "application", "id", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L204-L218
246,865
bmweiner/skillful
skillful/validate.py
Valid.sender
def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True
python
def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True
[ "def", "sender", "(", "self", ",", "body", ",", "stamp", ",", "url", ",", "sig", ")", ":", "if", "not", "timestamp", "(", "stamp", ")", ":", "return", "False", "if", "self", ".", "url", "!=", "url", ":", "if", "not", "signature_cert_chain_url", "(", "url", ")", ":", "return", "False", "certs", "=", "retrieve", "(", "url", ")", "if", "not", "certs", ":", "return", "False", "if", "not", "cert_chain", "(", "certs", ")", ":", "return", "False", "self", ".", "url", "=", "url", "self", ".", "cert", "=", "certs", "[", "0", "]", "if", "not", "signature", "(", "self", ".", "cert", ",", "sig", ",", "body", ")", ":", "return", "False", "return", "True" ]
Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise.
[ "Validate", "request", "is", "from", "Alexa", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L220-L258
246,866
bmweiner/skillful
skillful/validate.py
Valid.request
def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
python
def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
[ "def", "request", "(", "self", ",", "app_id", "=", "None", ",", "body", "=", "None", ",", "stamp", "=", "None", ",", "url", "=", "None", ",", "sig", "=", "None", ")", ":", "if", "self", ".", "app_id", ":", "if", "not", "self", ".", "application_id", "(", "app_id", ")", ":", "return", "False", "if", "(", "url", "or", "sig", ")", ":", "if", "not", "(", "body", "and", "stamp", "and", "url", "and", "sig", ")", ":", "raise", "ValueError", "(", "'Unable to validate sender, check arguments.'", ")", "else", ":", "if", "not", "self", ".", "sender", "(", "body", ",", "stamp", ",", "url", ",", "sig", ")", ":", "return", "False", "return", "True" ]
Validate application ID and request is from Alexa.
[ "Validate", "application", "ID", "and", "request", "is", "from", "Alexa", "." ]
8646f54faf62cb63f165f7699b8ace5b4a08233c
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L260-L273
246,867
evetrivia/thanatos
thanatos/database/db_utils.py
load_tables_from_files
def load_tables_from_files(db_connection): """ Looks in the current working directory for all required tables. """ _log.info('Loading tables from disk to DB.') sde_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'sde') for sde_file_name in os.listdir(sde_dir_path): _log.info('Loading the following table: {}'.format(sde_file_name)) sde_file_path = os.path.join(sde_dir_path, sde_file_name) with open(sde_file_path, 'r') as sde_file: sql = sde_file.read() execute_sql(sql, db_connection) _log.info('Finished loading all requested tables.')
python
def load_tables_from_files(db_connection): """ Looks in the current working directory for all required tables. """ _log.info('Loading tables from disk to DB.') sde_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'sde') for sde_file_name in os.listdir(sde_dir_path): _log.info('Loading the following table: {}'.format(sde_file_name)) sde_file_path = os.path.join(sde_dir_path, sde_file_name) with open(sde_file_path, 'r') as sde_file: sql = sde_file.read() execute_sql(sql, db_connection) _log.info('Finished loading all requested tables.')
[ "def", "load_tables_from_files", "(", "db_connection", ")", ":", "_log", ".", "info", "(", "'Loading tables from disk to DB.'", ")", "sde_dir_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "'sde'", ")", "for", "sde_file_name", "in", "os", ".", "listdir", "(", "sde_dir_path", ")", ":", "_log", ".", "info", "(", "'Loading the following table: {}'", ".", "format", "(", "sde_file_name", ")", ")", "sde_file_path", "=", "os", ".", "path", ".", "join", "(", "sde_dir_path", ",", "sde_file_name", ")", "with", "open", "(", "sde_file_path", ",", "'r'", ")", "as", "sde_file", ":", "sql", "=", "sde_file", ".", "read", "(", ")", "execute_sql", "(", "sql", ",", "db_connection", ")", "_log", ".", "info", "(", "'Finished loading all requested tables.'", ")" ]
Looks in the current working directory for all required tables.
[ "Looks", "in", "the", "current", "working", "directory", "for", "all", "required", "tables", "." ]
664c12a8ccf4d27ab0e06e0969bbb6381f74789c
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/db_utils.py#L84-L100
246,868
evetrivia/thanatos
thanatos/database/db_utils.py
get_connection
def get_connection(connection_details=None): """ Creates a connection to the MySQL DB. """ if connection_details is None: connection_details = get_default_connection_details() return MySQLdb.connect( connection_details['host'], connection_details['user'], connection_details['password'], connection_details['database'] )
python
def get_connection(connection_details=None): """ Creates a connection to the MySQL DB. """ if connection_details is None: connection_details = get_default_connection_details() return MySQLdb.connect( connection_details['host'], connection_details['user'], connection_details['password'], connection_details['database'] )
[ "def", "get_connection", "(", "connection_details", "=", "None", ")", ":", "if", "connection_details", "is", "None", ":", "connection_details", "=", "get_default_connection_details", "(", ")", "return", "MySQLdb", ".", "connect", "(", "connection_details", "[", "'host'", "]", ",", "connection_details", "[", "'user'", "]", ",", "connection_details", "[", "'password'", "]", ",", "connection_details", "[", "'database'", "]", ")" ]
Creates a connection to the MySQL DB.
[ "Creates", "a", "connection", "to", "the", "MySQL", "DB", "." ]
664c12a8ccf4d27ab0e06e0969bbb6381f74789c
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/db_utils.py#L103-L114
246,869
evetrivia/thanatos
thanatos/database/db_utils.py
get_default_connection_details
def get_default_connection_details(): """ Gets the connection details based on environment vars or Thanatos default settings. :return: Returns a dictionary of connection details. :rtype: dict """ return { 'host': os.environ.get('MYSQL_HOST', '127.0.0.1'), 'user': os.environ.get('MYSQL_USER', 'vagrant'), 'password': os.environ.get('MYSQL_PASSWORD', 'vagrant'), 'database': os.environ.get('MYSQL_DB', 'thanatos'), }
python
def get_default_connection_details(): """ Gets the connection details based on environment vars or Thanatos default settings. :return: Returns a dictionary of connection details. :rtype: dict """ return { 'host': os.environ.get('MYSQL_HOST', '127.0.0.1'), 'user': os.environ.get('MYSQL_USER', 'vagrant'), 'password': os.environ.get('MYSQL_PASSWORD', 'vagrant'), 'database': os.environ.get('MYSQL_DB', 'thanatos'), }
[ "def", "get_default_connection_details", "(", ")", ":", "return", "{", "'host'", ":", "os", ".", "environ", ".", "get", "(", "'MYSQL_HOST'", ",", "'127.0.0.1'", ")", ",", "'user'", ":", "os", ".", "environ", ".", "get", "(", "'MYSQL_USER'", ",", "'vagrant'", ")", ",", "'password'", ":", "os", ".", "environ", ".", "get", "(", "'MYSQL_PASSWORD'", ",", "'vagrant'", ")", ",", "'database'", ":", "os", ".", "environ", ".", "get", "(", "'MYSQL_DB'", ",", "'thanatos'", ")", ",", "}" ]
Gets the connection details based on environment vars or Thanatos default settings. :return: Returns a dictionary of connection details. :rtype: dict
[ "Gets", "the", "connection", "details", "based", "on", "environment", "vars", "or", "Thanatos", "default", "settings", "." ]
664c12a8ccf4d27ab0e06e0969bbb6381f74789c
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/db_utils.py#L117-L129
246,870
MaT1g3R/option
option/option_.py
Option.unwrap_or
def unwrap_or(self, default: U) -> Union[T, U]: """ Returns the contained value or ``default``. Args: default: The default value. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``default``. Notes: If you wish to use a result of a function call as the default, it is recommnded to use :py:meth:`unwrap_or_else` instead. Examples: >>> Some(0).unwrap_or(3) 0 >>> NONE.unwrap_or(0) 0 """ return self.unwrap_or_else(lambda: default)
python
def unwrap_or(self, default: U) -> Union[T, U]: """ Returns the contained value or ``default``. Args: default: The default value. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``default``. Notes: If you wish to use a result of a function call as the default, it is recommnded to use :py:meth:`unwrap_or_else` instead. Examples: >>> Some(0).unwrap_or(3) 0 >>> NONE.unwrap_or(0) 0 """ return self.unwrap_or_else(lambda: default)
[ "def", "unwrap_or", "(", "self", ",", "default", ":", "U", ")", "->", "Union", "[", "T", ",", "U", "]", ":", "return", "self", ".", "unwrap_or_else", "(", "lambda", ":", "default", ")" ]
Returns the contained value or ``default``. Args: default: The default value. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``default``. Notes: If you wish to use a result of a function call as the default, it is recommnded to use :py:meth:`unwrap_or_else` instead. Examples: >>> Some(0).unwrap_or(3) 0 >>> NONE.unwrap_or(0) 0
[ "Returns", "the", "contained", "value", "or", "default", "." ]
37c954e6e74273d48649b3236bc881a1286107d6
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L198-L219
246,871
MaT1g3R/option
option/option_.py
Option.unwrap_or_else
def unwrap_or_else(self, callback: Callable[[], U]) -> Union[T, U]: """ Returns the contained value or computes it from ``callback``. Args: callback: The the default callback. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``callback()``. Examples: >>> Some(0).unwrap_or_else(lambda: 111) 0 >>> NONE.unwrap_or_else(lambda: 'ha') 'ha' """ return self._val if self._is_some else callback()
python
def unwrap_or_else(self, callback: Callable[[], U]) -> Union[T, U]: """ Returns the contained value or computes it from ``callback``. Args: callback: The the default callback. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``callback()``. Examples: >>> Some(0).unwrap_or_else(lambda: 111) 0 >>> NONE.unwrap_or_else(lambda: 'ha') 'ha' """ return self._val if self._is_some else callback()
[ "def", "unwrap_or_else", "(", "self", ",", "callback", ":", "Callable", "[", "[", "]", ",", "U", "]", ")", "->", "Union", "[", "T", ",", "U", "]", ":", "return", "self", ".", "_val", "if", "self", ".", "_is_some", "else", "callback", "(", ")" ]
Returns the contained value or computes it from ``callback``. Args: callback: The the default callback. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``callback()``. Examples: >>> Some(0).unwrap_or_else(lambda: 111) 0 >>> NONE.unwrap_or_else(lambda: 'ha') 'ha'
[ "Returns", "the", "contained", "value", "or", "computes", "it", "from", "callback", "." ]
37c954e6e74273d48649b3236bc881a1286107d6
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L221-L238
246,872
MaT1g3R/option
option/option_.py
Option.map_or
def map_or(self, callback: Callable[[T], U], default: A) -> Union[U, A]: """ Applies the ``callback`` to the contained value or returns ``default``. Args: callback: The callback to apply to the contained value. default: The default value. Returns: The ``callback`` result if the contained value is ``Some``, otherwise ``default``. Notes: If you wish to use the result of a function call as ``default``, it is recommended to use :py:meth:`map_or_else` instead. Examples: >>> Some(0).map_or(lambda x: x + 1, 1000) 1 >>> NONE.map_or(lambda x: x * x, 1) 1 """ return callback(self._val) if self._is_some else default
python
def map_or(self, callback: Callable[[T], U], default: A) -> Union[U, A]: """ Applies the ``callback`` to the contained value or returns ``default``. Args: callback: The callback to apply to the contained value. default: The default value. Returns: The ``callback`` result if the contained value is ``Some``, otherwise ``default``. Notes: If you wish to use the result of a function call as ``default``, it is recommended to use :py:meth:`map_or_else` instead. Examples: >>> Some(0).map_or(lambda x: x + 1, 1000) 1 >>> NONE.map_or(lambda x: x * x, 1) 1 """ return callback(self._val) if self._is_some else default
[ "def", "map_or", "(", "self", ",", "callback", ":", "Callable", "[", "[", "T", "]", ",", "U", "]", ",", "default", ":", "A", ")", "->", "Union", "[", "U", ",", "A", "]", ":", "return", "callback", "(", "self", ".", "_val", ")", "if", "self", ".", "_is_some", "else", "default" ]
Applies the ``callback`` to the contained value or returns ``default``. Args: callback: The callback to apply to the contained value. default: The default value. Returns: The ``callback`` result if the contained value is ``Some``, otherwise ``default``. Notes: If you wish to use the result of a function call as ``default``, it is recommended to use :py:meth:`map_or_else` instead. Examples: >>> Some(0).map_or(lambda x: x + 1, 1000) 1 >>> NONE.map_or(lambda x: x * x, 1) 1
[ "Applies", "the", "callback", "to", "the", "contained", "value", "or", "returns", "default", "." ]
37c954e6e74273d48649b3236bc881a1286107d6
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L260-L282
246,873
MaT1g3R/option
option/option_.py
Option.get
def get( self: 'Option[Mapping[K,V]]', key: K, default=None ) -> 'Option[V]': """ Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of the mapping value if the key exists and the value is not None. * ``Some(default)`` if ``default`` is not None. * :py:data:`NONE` if ``default`` is None. Examples: >>> Some({'hi': 1}).get('hi') Some(1) >>> Some({}).get('hi', 12) Some(12) >>> NONE.get('hi', 12) Some(12) >>> NONE.get('hi') NONE """ if self._is_some: return self._type.maybe(self._val.get(key, default)) return self._type.maybe(default)
python
def get( self: 'Option[Mapping[K,V]]', key: K, default=None ) -> 'Option[V]': """ Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of the mapping value if the key exists and the value is not None. * ``Some(default)`` if ``default`` is not None. * :py:data:`NONE` if ``default`` is None. Examples: >>> Some({'hi': 1}).get('hi') Some(1) >>> Some({}).get('hi', 12) Some(12) >>> NONE.get('hi', 12) Some(12) >>> NONE.get('hi') NONE """ if self._is_some: return self._type.maybe(self._val.get(key, default)) return self._type.maybe(default)
[ "def", "get", "(", "self", ":", "'Option[Mapping[K,V]]'", ",", "key", ":", "K", ",", "default", "=", "None", ")", "->", "'Option[V]'", ":", "if", "self", ".", "_is_some", ":", "return", "self", ".", "_type", ".", "maybe", "(", "self", ".", "_val", ".", "get", "(", "key", ",", "default", ")", ")", "return", "self", ".", "_type", ".", "maybe", "(", "default", ")" ]
Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of the mapping value if the key exists and the value is not None. * ``Some(default)`` if ``default`` is not None. * :py:data:`NONE` if ``default`` is None. Examples: >>> Some({'hi': 1}).get('hi') Some(1) >>> Some({}).get('hi', 12) Some(12) >>> NONE.get('hi', 12) Some(12) >>> NONE.get('hi') NONE
[ "Gets", "a", "mapping", "value", "by", "key", "in", "the", "contained", "value", "or", "returns", "default", "if", "the", "key", "doesn", "t", "exist", "." ]
37c954e6e74273d48649b3236bc881a1286107d6
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L361-L392
246,874
joar/mig
mig/__init__.py
assure_migrations_table_setup
def assure_migrations_table_setup(db): """ Make sure the migrations table is set up in the database. """ from mig.models import MigrationData if not MigrationData.__table__.exists(db.bind): MigrationData.metadata.create_all( db.bind, tables=[MigrationData.__table__])
python
def assure_migrations_table_setup(db): """ Make sure the migrations table is set up in the database. """ from mig.models import MigrationData if not MigrationData.__table__.exists(db.bind): MigrationData.metadata.create_all( db.bind, tables=[MigrationData.__table__])
[ "def", "assure_migrations_table_setup", "(", "db", ")", ":", "from", "mig", ".", "models", "import", "MigrationData", "if", "not", "MigrationData", ".", "__table__", ".", "exists", "(", "db", ".", "bind", ")", ":", "MigrationData", ".", "metadata", ".", "create_all", "(", "db", ".", "bind", ",", "tables", "=", "[", "MigrationData", ".", "__table__", "]", ")" ]
Make sure the migrations table is set up in the database.
[ "Make", "sure", "the", "migrations", "table", "is", "set", "up", "in", "the", "database", "." ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L280-L288
246,875
joar/mig
mig/__init__.py
MigrationManager.sorted_migrations
def sorted_migrations(self): """ Sort migrations if necessary and store in self._sorted_migrations """ if not self._sorted_migrations: self._sorted_migrations = sorted( self.migration_registry.items(), # sort on the key... the migration number key=lambda migration_tuple: migration_tuple[0]) return self._sorted_migrations
python
def sorted_migrations(self): """ Sort migrations if necessary and store in self._sorted_migrations """ if not self._sorted_migrations: self._sorted_migrations = sorted( self.migration_registry.items(), # sort on the key... the migration number key=lambda migration_tuple: migration_tuple[0]) return self._sorted_migrations
[ "def", "sorted_migrations", "(", "self", ")", ":", "if", "not", "self", ".", "_sorted_migrations", ":", "self", ".", "_sorted_migrations", "=", "sorted", "(", "self", ".", "migration_registry", ".", "items", "(", ")", ",", "# sort on the key... the migration number", "key", "=", "lambda", "migration_tuple", ":", "migration_tuple", "[", "0", "]", ")", "return", "self", ".", "_sorted_migrations" ]
Sort migrations if necessary and store in self._sorted_migrations
[ "Sort", "migrations", "if", "necessary", "and", "store", "in", "self", ".", "_sorted_migrations" ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L75-L85
246,876
joar/mig
mig/__init__.py
MigrationManager.migration_data
def migration_data(self): """ Get the migration row associated with this object, if any. """ return self.session.query( self.migration_model).filter_by(name=self.name).first()
python
def migration_data(self): """ Get the migration row associated with this object, if any. """ return self.session.query( self.migration_model).filter_by(name=self.name).first()
[ "def", "migration_data", "(", "self", ")", ":", "return", "self", ".", "session", ".", "query", "(", "self", ".", "migration_model", ")", ".", "filter_by", "(", "name", "=", "self", ".", "name", ")", ".", "first", "(", ")" ]
Get the migration row associated with this object, if any.
[ "Get", "the", "migration", "row", "associated", "with", "this", "object", "if", "any", "." ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L88-L93
246,877
joar/mig
mig/__init__.py
MigrationManager.database_current_migration
def database_current_migration(self): """ Return the current migration in the database. """ # If the table doesn't even exist, return None. if not self.migration_table.exists(self.session.bind): return None # Also return None if self.migration_data is None. if self.migration_data is None: return None return self.migration_data.version
python
def database_current_migration(self): """ Return the current migration in the database. """ # If the table doesn't even exist, return None. if not self.migration_table.exists(self.session.bind): return None # Also return None if self.migration_data is None. if self.migration_data is None: return None return self.migration_data.version
[ "def", "database_current_migration", "(", "self", ")", ":", "# If the table doesn't even exist, return None.", "if", "not", "self", ".", "migration_table", ".", "exists", "(", "self", ".", "session", ".", "bind", ")", ":", "return", "None", "# Also return None if self.migration_data is None.", "if", "self", ".", "migration_data", "is", "None", ":", "return", "None", "return", "self", ".", "migration_data", ".", "version" ]
Return the current migration in the database.
[ "Return", "the", "current", "migration", "in", "the", "database", "." ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L108-L120
246,878
joar/mig
mig/__init__.py
MigrationManager.migrations_to_run
def migrations_to_run(self): """ Get a list of migrations to run still, if any. Note that this will fail if there's no migration record for this class! """ assert self.database_current_migration is not None db_current_migration = self.database_current_migration return [ (migration_number, migration_func) for migration_number, migration_func in self.sorted_migrations if migration_number > db_current_migration]
python
def migrations_to_run(self): """ Get a list of migrations to run still, if any. Note that this will fail if there's no migration record for this class! """ assert self.database_current_migration is not None db_current_migration = self.database_current_migration return [ (migration_number, migration_func) for migration_number, migration_func in self.sorted_migrations if migration_number > db_current_migration]
[ "def", "migrations_to_run", "(", "self", ")", ":", "assert", "self", ".", "database_current_migration", "is", "not", "None", "db_current_migration", "=", "self", ".", "database_current_migration", "return", "[", "(", "migration_number", ",", "migration_func", ")", "for", "migration_number", ",", "migration_func", "in", "self", ".", "sorted_migrations", "if", "migration_number", ">", "db_current_migration", "]" ]
Get a list of migrations to run still, if any. Note that this will fail if there's no migration record for this class!
[ "Get", "a", "list", "of", "migrations", "to", "run", "still", "if", "any", "." ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L130-L144
246,879
joar/mig
mig/__init__.py
MigrationManager.init_tables
def init_tables(self): """ Create all tables relative to this package """ # sanity check before we proceed, none of these should be created for model in self.models: # Maybe in the future just print out a "Yikes!" or something? _log.debug('Checking for table {0}'.format(model)) assert not model.__table__.exists(self.session.bind) _log.debug('Creating {0}'.format(self.models)) self.migration_model.metadata.create_all( self.session.bind, tables=[model.__table__ for model in self.models])
python
def init_tables(self): """ Create all tables relative to this package """ # sanity check before we proceed, none of these should be created for model in self.models: # Maybe in the future just print out a "Yikes!" or something? _log.debug('Checking for table {0}'.format(model)) assert not model.__table__.exists(self.session.bind) _log.debug('Creating {0}'.format(self.models)) self.migration_model.metadata.create_all( self.session.bind, tables=[model.__table__ for model in self.models])
[ "def", "init_tables", "(", "self", ")", ":", "# sanity check before we proceed, none of these should be created", "for", "model", "in", "self", ".", "models", ":", "# Maybe in the future just print out a \"Yikes!\" or something?", "_log", ".", "debug", "(", "'Checking for table {0}'", ".", "format", "(", "model", ")", ")", "assert", "not", "model", ".", "__table__", ".", "exists", "(", "self", ".", "session", ".", "bind", ")", "_log", ".", "debug", "(", "'Creating {0}'", ".", "format", "(", "self", ".", "models", ")", ")", "self", ".", "migration_model", ".", "metadata", ".", "create_all", "(", "self", ".", "session", ".", "bind", ",", "tables", "=", "[", "model", ".", "__table__", "for", "model", "in", "self", ".", "models", "]", ")" ]
Create all tables relative to this package
[ "Create", "all", "tables", "relative", "to", "this", "package" ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L146-L159
246,880
joar/mig
mig/__init__.py
MigrationManager.create_new_migration_record
def create_new_migration_record(self): """ Create a new migration record for this migration set """ migration_record = self.migration_model( name=self.name, version=self.latest_migration) self.session.add(migration_record) self.session.commit()
python
def create_new_migration_record(self): """ Create a new migration record for this migration set """ migration_record = self.migration_model( name=self.name, version=self.latest_migration) self.session.add(migration_record) self.session.commit()
[ "def", "create_new_migration_record", "(", "self", ")", ":", "migration_record", "=", "self", ".", "migration_model", "(", "name", "=", "self", ".", "name", ",", "version", "=", "self", ".", "latest_migration", ")", "self", ".", "session", ".", "add", "(", "migration_record", ")", "self", ".", "session", ".", "commit", "(", ")" ]
Create a new migration record for this migration set
[ "Create", "a", "new", "migration", "record", "for", "this", "migration", "set" ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L161-L169
246,881
joar/mig
mig/__init__.py
MigrationManager.dry_run
def dry_run(self): """ Print out a dry run of what we would have upgraded. """ if self.database_current_migration is None: self.printer( u'~> Woulda initialized: %s\n' % self.name_for_printing()) return u'inited' migrations_to_run = self.migrations_to_run() if migrations_to_run: self.printer( u'~> Woulda updated %s:\n' % self.name_for_printing()) for migration_number, migration_func in migrations_to_run(): self.printer( u' + Would update %s, "%s"\n' % ( migration_number, migration_func.func_name)) return u'migrated'
python
def dry_run(self): """ Print out a dry run of what we would have upgraded. """ if self.database_current_migration is None: self.printer( u'~> Woulda initialized: %s\n' % self.name_for_printing()) return u'inited' migrations_to_run = self.migrations_to_run() if migrations_to_run: self.printer( u'~> Woulda updated %s:\n' % self.name_for_printing()) for migration_number, migration_func in migrations_to_run(): self.printer( u' + Would update %s, "%s"\n' % ( migration_number, migration_func.func_name)) return u'migrated'
[ "def", "dry_run", "(", "self", ")", ":", "if", "self", ".", "database_current_migration", "is", "None", ":", "self", ".", "printer", "(", "u'~> Woulda initialized: %s\\n'", "%", "self", ".", "name_for_printing", "(", ")", ")", "return", "u'inited'", "migrations_to_run", "=", "self", ".", "migrations_to_run", "(", ")", "if", "migrations_to_run", ":", "self", ".", "printer", "(", "u'~> Woulda updated %s:\\n'", "%", "self", ".", "name_for_printing", "(", ")", ")", "for", "migration_number", ",", "migration_func", "in", "migrations_to_run", "(", ")", ":", "self", ".", "printer", "(", "u' + Would update %s, \"%s\"\\n'", "%", "(", "migration_number", ",", "migration_func", ".", "func_name", ")", ")", "return", "u'migrated'" ]
Print out a dry run of what we would have upgraded.
[ "Print", "out", "a", "dry", "run", "of", "what", "we", "would", "have", "upgraded", "." ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L171-L190
246,882
joar/mig
mig/__init__.py
MigrationManager.init_or_migrate
def init_or_migrate(self): """ Initialize the database or migrate if appropriate. Returns information about whether or not we initialized ('inited'), migrated ('migrated'), or did nothing (None) """ assure_migrations_table_setup(self.session) # Find out what migration number, if any, this database data is at, # and what the latest is. migration_number = self.database_current_migration # Is this our first time? Is there even a table entry for # this identifier? # If so: # - create all tables # - create record in migrations registry # - print / inform the user # - return 'inited' if migration_number is None: self.printer(u"-> Initializing %s... " % self.name_for_printing()) self.init_tables() # auto-set at latest migration number self.create_new_migration_record() self.printer(u"done.\n") self.set_current_migration() return u'inited' # Run migrations, if appropriate. migrations_to_run = self.migrations_to_run() if migrations_to_run: self.printer( u'-> Updating %s:\n' % self.name_for_printing()) for migration_number, migration_func in migrations_to_run: self.printer( u' + Running migration %s, "%s"... ' % ( migration_number, migration_func.func_name)) migration_func(self.session) self.printer('done.\n') self.set_current_migration() return u'migrated' # Otherwise return None. Well it would do this anyway, but # for clarity... ;) return None
python
def init_or_migrate(self): """ Initialize the database or migrate if appropriate. Returns information about whether or not we initialized ('inited'), migrated ('migrated'), or did nothing (None) """ assure_migrations_table_setup(self.session) # Find out what migration number, if any, this database data is at, # and what the latest is. migration_number = self.database_current_migration # Is this our first time? Is there even a table entry for # this identifier? # If so: # - create all tables # - create record in migrations registry # - print / inform the user # - return 'inited' if migration_number is None: self.printer(u"-> Initializing %s... " % self.name_for_printing()) self.init_tables() # auto-set at latest migration number self.create_new_migration_record() self.printer(u"done.\n") self.set_current_migration() return u'inited' # Run migrations, if appropriate. migrations_to_run = self.migrations_to_run() if migrations_to_run: self.printer( u'-> Updating %s:\n' % self.name_for_printing()) for migration_number, migration_func in migrations_to_run: self.printer( u' + Running migration %s, "%s"... ' % ( migration_number, migration_func.func_name)) migration_func(self.session) self.printer('done.\n') self.set_current_migration() return u'migrated' # Otherwise return None. Well it would do this anyway, but # for clarity... ;) return None
[ "def", "init_or_migrate", "(", "self", ")", ":", "assure_migrations_table_setup", "(", "self", ".", "session", ")", "# Find out what migration number, if any, this database data is at,", "# and what the latest is.", "migration_number", "=", "self", ".", "database_current_migration", "# Is this our first time? Is there even a table entry for", "# this identifier?", "# If so:", "# - create all tables", "# - create record in migrations registry", "# - print / inform the user", "# - return 'inited'", "if", "migration_number", "is", "None", ":", "self", ".", "printer", "(", "u\"-> Initializing %s... \"", "%", "self", ".", "name_for_printing", "(", ")", ")", "self", ".", "init_tables", "(", ")", "# auto-set at latest migration number", "self", ".", "create_new_migration_record", "(", ")", "self", ".", "printer", "(", "u\"done.\\n\"", ")", "self", ".", "set_current_migration", "(", ")", "return", "u'inited'", "# Run migrations, if appropriate.", "migrations_to_run", "=", "self", ".", "migrations_to_run", "(", ")", "if", "migrations_to_run", ":", "self", ".", "printer", "(", "u'-> Updating %s:\\n'", "%", "self", ".", "name_for_printing", "(", ")", ")", "for", "migration_number", ",", "migration_func", "in", "migrations_to_run", ":", "self", ".", "printer", "(", "u' + Running migration %s, \"%s\"... '", "%", "(", "migration_number", ",", "migration_func", ".", "func_name", ")", ")", "migration_func", "(", "self", ".", "session", ")", "self", ".", "printer", "(", "'done.\\n'", ")", "self", ".", "set_current_migration", "(", ")", "return", "u'migrated'", "# Otherwise return None. Well it would do this anyway, but", "# for clarity... ;)", "return", "None" ]
Initialize the database or migrate if appropriate. Returns information about whether or not we initialized ('inited'), migrated ('migrated'), or did nothing (None)
[ "Initialize", "the", "database", "or", "migrate", "if", "appropriate", "." ]
e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5
https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L199-L247
246,883
jmgilman/Neolib
neolib/pyamf/remoting/amf0.py
RequestProcessor.authenticateRequest
def authenticateRequest(self, request, service_request, *args, **kwargs): """ Authenticates the request against the service. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} """ username = password = None if 'Credentials' in request.headers: cred = request.headers['Credentials'] username = cred['userid'] password = cred['password'] return self.gateway.authenticateRequest(service_request, username, password, *args, **kwargs)
python
def authenticateRequest(self, request, service_request, *args, **kwargs): """ Authenticates the request against the service. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} """ username = password = None if 'Credentials' in request.headers: cred = request.headers['Credentials'] username = cred['userid'] password = cred['password'] return self.gateway.authenticateRequest(service_request, username, password, *args, **kwargs)
[ "def", "authenticateRequest", "(", "self", ",", "request", ",", "service_request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "username", "=", "password", "=", "None", "if", "'Credentials'", "in", "request", ".", "headers", ":", "cred", "=", "request", ".", "headers", "[", "'Credentials'", "]", "username", "=", "cred", "[", "'userid'", "]", "password", "=", "cred", "[", "'password'", "]", "return", "self", ".", "gateway", ".", "authenticateRequest", "(", "service_request", ",", "username", ",", "password", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Authenticates the request against the service. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>}
[ "Authenticates", "the", "request", "against", "the", "service", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/amf0.py#L21-L37
246,884
KnowledgeLinks/rdfframework
rdfframework/utilities/debug.py
dumpable_obj
def dumpable_obj(obj): ''' takes an object that fails with json.dumps and converts it to a json.dumps dumpable object. This is useful for debuging code when you want to dump an object for easy reading''' if isinstance(obj, list): _return_list = [] for item in obj: if isinstance(item, list): _return_list.append(dumpable_obj(item)) elif isinstance(item, set): _return_list.append(list(item)) elif isinstance(item, dict): _return_list.append(dumpable_obj(item)) else: try: json.dumps(item) _return_list.append(item) except: _return_list.append(str(type(item))) return _return_list elif isinstance(obj, set): return list(obj) elif isinstance(obj, dict): _return_obj = {} for key, item in obj.items(): if isinstance(item, list): _return_obj[key] = dumpable_obj(item) elif isinstance(item, set): _return_obj[key] = list(item) elif isinstance(item, dict): _return_obj[key] = dumpable_obj(item) else: try: json.dumps(item) _return_obj[key] = item except: _return_obj[key] = str(type(item)) return _return_obj else: try: json.dumps(obj) return obj except: return str(type(obj))
python
def dumpable_obj(obj): ''' takes an object that fails with json.dumps and converts it to a json.dumps dumpable object. This is useful for debuging code when you want to dump an object for easy reading''' if isinstance(obj, list): _return_list = [] for item in obj: if isinstance(item, list): _return_list.append(dumpable_obj(item)) elif isinstance(item, set): _return_list.append(list(item)) elif isinstance(item, dict): _return_list.append(dumpable_obj(item)) else: try: json.dumps(item) _return_list.append(item) except: _return_list.append(str(type(item))) return _return_list elif isinstance(obj, set): return list(obj) elif isinstance(obj, dict): _return_obj = {} for key, item in obj.items(): if isinstance(item, list): _return_obj[key] = dumpable_obj(item) elif isinstance(item, set): _return_obj[key] = list(item) elif isinstance(item, dict): _return_obj[key] = dumpable_obj(item) else: try: json.dumps(item) _return_obj[key] = item except: _return_obj[key] = str(type(item)) return _return_obj else: try: json.dumps(obj) return obj except: return str(type(obj))
[ "def", "dumpable_obj", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "_return_list", "=", "[", "]", "for", "item", "in", "obj", ":", "if", "isinstance", "(", "item", ",", "list", ")", ":", "_return_list", ".", "append", "(", "dumpable_obj", "(", "item", ")", ")", "elif", "isinstance", "(", "item", ",", "set", ")", ":", "_return_list", ".", "append", "(", "list", "(", "item", ")", ")", "elif", "isinstance", "(", "item", ",", "dict", ")", ":", "_return_list", ".", "append", "(", "dumpable_obj", "(", "item", ")", ")", "else", ":", "try", ":", "json", ".", "dumps", "(", "item", ")", "_return_list", ".", "append", "(", "item", ")", "except", ":", "_return_list", ".", "append", "(", "str", "(", "type", "(", "item", ")", ")", ")", "return", "_return_list", "elif", "isinstance", "(", "obj", ",", "set", ")", ":", "return", "list", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "_return_obj", "=", "{", "}", "for", "key", ",", "item", "in", "obj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "item", ",", "list", ")", ":", "_return_obj", "[", "key", "]", "=", "dumpable_obj", "(", "item", ")", "elif", "isinstance", "(", "item", ",", "set", ")", ":", "_return_obj", "[", "key", "]", "=", "list", "(", "item", ")", "elif", "isinstance", "(", "item", ",", "dict", ")", ":", "_return_obj", "[", "key", "]", "=", "dumpable_obj", "(", "item", ")", "else", ":", "try", ":", "json", ".", "dumps", "(", "item", ")", "_return_obj", "[", "key", "]", "=", "item", "except", ":", "_return_obj", "[", "key", "]", "=", "str", "(", "type", "(", "item", ")", ")", "return", "_return_obj", "else", ":", "try", ":", "json", ".", "dumps", "(", "obj", ")", "return", "obj", "except", ":", "return", "str", "(", "type", "(", "obj", ")", ")" ]
takes an object that fails with json.dumps and converts it to a json.dumps dumpable object. This is useful for debuging code when you want to dump an object for easy reading
[ "takes", "an", "object", "that", "fails", "with", "json", ".", "dumps", "and", "converts", "it", "to", "a", "json", ".", "dumps", "dumpable", "object", ".", "This", "is", "useful", "for", "debuging", "code", "when", "you", "want", "to", "dump", "an", "object", "for", "easy", "reading" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/debug.py#L13-L57
246,885
svasilev94/GraphLibrary
graphlibrary/paths.py
find_all_paths
def find_all_paths(G, start, end, path=[]): """ Find all paths between vertices start and end in graph. """ path = path + [start] if start == end: return [path] if start not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (start,)) if end not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (end,)) paths = [] for vertex in G.vertices[start]: if vertex not in path: newpaths = find_all_paths(G, vertex, end, path) for newpath in newpaths: paths.append(newpath) return paths
python
def find_all_paths(G, start, end, path=[]): """ Find all paths between vertices start and end in graph. """ path = path + [start] if start == end: return [path] if start not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (start,)) if end not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (end,)) paths = [] for vertex in G.vertices[start]: if vertex not in path: newpaths = find_all_paths(G, vertex, end, path) for newpath in newpaths: paths.append(newpath) return paths
[ "def", "find_all_paths", "(", "G", ",", "start", ",", "end", ",", "path", "=", "[", "]", ")", ":", "path", "=", "path", "+", "[", "start", "]", "if", "start", "==", "end", ":", "return", "[", "path", "]", "if", "start", "not", "in", "G", ".", "vertices", ":", "raise", "GraphInsertError", "(", "\"Vertex %s doesn't exist.\"", "%", "(", "start", ",", ")", ")", "if", "end", "not", "in", "G", ".", "vertices", ":", "raise", "GraphInsertError", "(", "\"Vertex %s doesn't exist.\"", "%", "(", "end", ",", ")", ")", "paths", "=", "[", "]", "for", "vertex", "in", "G", ".", "vertices", "[", "start", "]", ":", "if", "vertex", "not", "in", "path", ":", "newpaths", "=", "find_all_paths", "(", "G", ",", "vertex", ",", "end", ",", "path", ")", "for", "newpath", "in", "newpaths", ":", "paths", ".", "append", "(", "newpath", ")", "return", "paths" ]
Find all paths between vertices start and end in graph.
[ "Find", "all", "paths", "between", "vertices", "start", "and", "end", "in", "graph", "." ]
bf979a80bdea17eeb25955f0c119ca8f711ef62b
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/paths.py#L6-L23
246,886
unixorn/haze
setup.py
system_call
def system_call(command): """Run a command and return stdout. Would be better to use subprocess.check_output, but this works on 2.6, which is still the system Python on CentOS 7.""" p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) return p.stdout.read()
python
def system_call(command): """Run a command and return stdout. Would be better to use subprocess.check_output, but this works on 2.6, which is still the system Python on CentOS 7.""" p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) return p.stdout.read()
[ "def", "system_call", "(", "command", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "command", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ")", "return", "p", ".", "stdout", ".", "read", "(", ")" ]
Run a command and return stdout. Would be better to use subprocess.check_output, but this works on 2.6, which is still the system Python on CentOS 7.
[ "Run", "a", "command", "and", "return", "stdout", "." ]
77692b18e6574ac356e3e16659b96505c733afff
https://github.com/unixorn/haze/blob/77692b18e6574ac356e3e16659b96505c733afff/setup.py#L30-L36
246,887
lduchesne/python-openstacksdk-hubic
hubic/hubic.py
HubiCAuthenticator.get_headers
def get_headers(self, session, **kwargs): """Get the authentication header. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The headers used for authenticating requests. :rtype: dict """ if self.auth_token is None: try: self._refresh_tokens(session) self._fetch_credentials(session) except: raise AuthorizationFailure() return { 'X-Auth-Token': self.auth_token, }
python
def get_headers(self, session, **kwargs): """Get the authentication header. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The headers used for authenticating requests. :rtype: dict """ if self.auth_token is None: try: self._refresh_tokens(session) self._fetch_credentials(session) except: raise AuthorizationFailure() return { 'X-Auth-Token': self.auth_token, }
[ "def", "get_headers", "(", "self", ",", "session", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "auth_token", "is", "None", ":", "try", ":", "self", ".", "_refresh_tokens", "(", "session", ")", "self", ".", "_fetch_credentials", "(", "session", ")", "except", ":", "raise", "AuthorizationFailure", "(", ")", "return", "{", "'X-Auth-Token'", ":", "self", ".", "auth_token", ",", "}" ]
Get the authentication header. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The headers used for authenticating requests. :rtype: dict
[ "Get", "the", "authentication", "header", "." ]
25e752f847613bb7e068c05e094a8abadaa7925a
https://github.com/lduchesne/python-openstacksdk-hubic/blob/25e752f847613bb7e068c05e094a8abadaa7925a/hubic/hubic.py#L66-L91
246,888
lduchesne/python-openstacksdk-hubic
hubic/hubic.py
HubiCAuthenticator.get_endpoint
def get_endpoint(self, session, **kwargs): """Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The uri to use for object-storage v1 requests. :rtype: string """ if self.endpoint is None: try: self._refresh_tokens(session) self._fetch_credentials(session) except: raise AuthorizationFailure() return self.endpoint
python
def get_endpoint(self, session, **kwargs): """Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The uri to use for object-storage v1 requests. :rtype: string """ if self.endpoint is None: try: self._refresh_tokens(session) self._fetch_credentials(session) except: raise AuthorizationFailure() return self.endpoint
[ "def", "get_endpoint", "(", "self", ",", "session", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "endpoint", "is", "None", ":", "try", ":", "self", ".", "_refresh_tokens", "(", "session", ")", "self", ".", "_fetch_credentials", "(", "session", ")", "except", ":", "raise", "AuthorizationFailure", "(", ")", "return", "self", ".", "endpoint" ]
Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The uri to use for object-storage v1 requests. :rtype: string
[ "Get", "the", "HubiC", "storage", "endpoint", "uri", "." ]
25e752f847613bb7e068c05e094a8abadaa7925a
https://github.com/lduchesne/python-openstacksdk-hubic/blob/25e752f847613bb7e068c05e094a8abadaa7925a/hubic/hubic.py#L94-L117
246,889
lduchesne/python-openstacksdk-hubic
hubic/hubic.py
HubiCAuthenticator._refresh_tokens
def _refresh_tokens(self, session): """Request an access and a refresh token from the HubiC API. Those tokens are mandatory and will be used for subsequent file operations. They are not returned and will be stored internaly. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. """ params = { 'client_id': self.client_id, 'client_secret': self.client_secret, } payload = { 'client_id': self.client_id, 'client_secret': self.client_secret, } if self.refresh_token is None: # if we don't have a refresh token, we need an authorization token # first payload['grant_type'] = 'authorization_code' payload['code'] = self._get_authorization_token(session) payload['redirect_uri'] = self.redirect_uri else: # when we have a refresh token, we DON'T need an authorization # token to request a new one payload['grant_type'] = 'refresh_token' payload['refresh_token'] = self.refresh_token r = session.post("https://api.hubic.com/oauth/token", params=params, data=payload, authenticated=False) if r.status_code != 200 and self.refresh_token is not None: # if we had a refresh token, try again without it # (might be expired) payload['grant_type'] = 'authorization_code' payload['code'] = self._get_authorization_token(session) payload['redirect_uri'] = self.redirect_uri r = session.post("https://api.hubic.com/oauth/token", params=params, data=payload, authenticated=False) if r.status_code != 200: raise AuthorizationFailure() response = r.json() if 'error' in response: raise AuthorizationFailure() self.access_token = response['access_token'] # refresh_token entry will not be there is we are just refreshing an # old token. if 'refresh_token' in response: self.refresh_token = response['refresh_token']
python
def _refresh_tokens(self, session): """Request an access and a refresh token from the HubiC API. Those tokens are mandatory and will be used for subsequent file operations. They are not returned and will be stored internaly. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. """ params = { 'client_id': self.client_id, 'client_secret': self.client_secret, } payload = { 'client_id': self.client_id, 'client_secret': self.client_secret, } if self.refresh_token is None: # if we don't have a refresh token, we need an authorization token # first payload['grant_type'] = 'authorization_code' payload['code'] = self._get_authorization_token(session) payload['redirect_uri'] = self.redirect_uri else: # when we have a refresh token, we DON'T need an authorization # token to request a new one payload['grant_type'] = 'refresh_token' payload['refresh_token'] = self.refresh_token r = session.post("https://api.hubic.com/oauth/token", params=params, data=payload, authenticated=False) if r.status_code != 200 and self.refresh_token is not None: # if we had a refresh token, try again without it # (might be expired) payload['grant_type'] = 'authorization_code' payload['code'] = self._get_authorization_token(session) payload['redirect_uri'] = self.redirect_uri r = session.post("https://api.hubic.com/oauth/token", params=params, data=payload, authenticated=False) if r.status_code != 200: raise AuthorizationFailure() response = r.json() if 'error' in response: raise AuthorizationFailure() self.access_token = response['access_token'] # refresh_token entry will not be there is we are just refreshing an # old token. if 'refresh_token' in response: self.refresh_token = response['refresh_token']
[ "def", "_refresh_tokens", "(", "self", ",", "session", ")", ":", "params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "}", "payload", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "}", "if", "self", ".", "refresh_token", "is", "None", ":", "# if we don't have a refresh token, we need an authorization token", "# first", "payload", "[", "'grant_type'", "]", "=", "'authorization_code'", "payload", "[", "'code'", "]", "=", "self", ".", "_get_authorization_token", "(", "session", ")", "payload", "[", "'redirect_uri'", "]", "=", "self", ".", "redirect_uri", "else", ":", "# when we have a refresh token, we DON'T need an authorization", "# token to request a new one", "payload", "[", "'grant_type'", "]", "=", "'refresh_token'", "payload", "[", "'refresh_token'", "]", "=", "self", ".", "refresh_token", "r", "=", "session", ".", "post", "(", "\"https://api.hubic.com/oauth/token\"", ",", "params", "=", "params", ",", "data", "=", "payload", ",", "authenticated", "=", "False", ")", "if", "r", ".", "status_code", "!=", "200", "and", "self", ".", "refresh_token", "is", "not", "None", ":", "# if we had a refresh token, try again without it", "# (might be expired)", "payload", "[", "'grant_type'", "]", "=", "'authorization_code'", "payload", "[", "'code'", "]", "=", "self", ".", "_get_authorization_token", "(", "session", ")", "payload", "[", "'redirect_uri'", "]", "=", "self", ".", "redirect_uri", "r", "=", "session", ".", "post", "(", "\"https://api.hubic.com/oauth/token\"", ",", "params", "=", "params", ",", "data", "=", "payload", ",", "authenticated", "=", "False", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "AuthorizationFailure", "(", ")", "response", "=", "r", ".", "json", "(", ")", "if", "'error'", "in", "response", ":", "raise", "AuthorizationFailure", "(", ")", "self", ".", "access_token", "=", "response", "[", "'access_token'", "]", "# refresh_token entry will not be there is we are just refreshing an", "# old token.", "if", "'refresh_token'", "in", "response", ":", "self", ".", "refresh_token", "=", "response", "[", "'refresh_token'", "]" ]
Request an access and a refresh token from the HubiC API. Those tokens are mandatory and will be used for subsequent file operations. They are not returned and will be stored internaly. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong.
[ "Request", "an", "access", "and", "a", "refresh", "token", "from", "the", "HubiC", "API", "." ]
25e752f847613bb7e068c05e094a8abadaa7925a
https://github.com/lduchesne/python-openstacksdk-hubic/blob/25e752f847613bb7e068c05e094a8abadaa7925a/hubic/hubic.py#L141-L203
246,890
lduchesne/python-openstacksdk-hubic
hubic/hubic.py
HubiCAuthenticator._fetch_credentials
def _fetch_credentials(self, session): """Fetch the endpoint URI and authorization token for this session. Those two information are the basis for all future calls to the Swift (OpenStack) API for the storage container. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. """ headers = { 'Authorization': 'Bearer {0}'.format(self.access_token), } r = session.get("https://api.hubic.com/1.0/account/credentials", headers=headers, authenticated=False) response = r.json() # if we get an error here, the OpenStack SDK will take care to try # again for us. if 'error' in response: raise AuthorizationFailure() self.endpoint = response['endpoint'] self.auth_token = response['token']
python
def _fetch_credentials(self, session): """Fetch the endpoint URI and authorization token for this session. Those two information are the basis for all future calls to the Swift (OpenStack) API for the storage container. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. """ headers = { 'Authorization': 'Bearer {0}'.format(self.access_token), } r = session.get("https://api.hubic.com/1.0/account/credentials", headers=headers, authenticated=False) response = r.json() # if we get an error here, the OpenStack SDK will take care to try # again for us. if 'error' in response: raise AuthorizationFailure() self.endpoint = response['endpoint'] self.auth_token = response['token']
[ "def", "_fetch_credentials", "(", "self", ",", "session", ")", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer {0}'", ".", "format", "(", "self", ".", "access_token", ")", ",", "}", "r", "=", "session", ".", "get", "(", "\"https://api.hubic.com/1.0/account/credentials\"", ",", "headers", "=", "headers", ",", "authenticated", "=", "False", ")", "response", "=", "r", ".", "json", "(", ")", "# if we get an error here, the OpenStack SDK will take care to try", "# again for us.", "if", "'error'", "in", "response", ":", "raise", "AuthorizationFailure", "(", ")", "self", ".", "endpoint", "=", "response", "[", "'endpoint'", "]", "self", ".", "auth_token", "=", "response", "[", "'token'", "]" ]
Fetch the endpoint URI and authorization token for this session. Those two information are the basis for all future calls to the Swift (OpenStack) API for the storage container. :param keystoneclient.Session session: The session object to use for queries. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong.
[ "Fetch", "the", "endpoint", "URI", "and", "authorization", "token", "for", "this", "session", "." ]
25e752f847613bb7e068c05e094a8abadaa7925a
https://github.com/lduchesne/python-openstacksdk-hubic/blob/25e752f847613bb7e068c05e094a8abadaa7925a/hubic/hubic.py#L206-L234
246,891
lduchesne/python-openstacksdk-hubic
hubic/hubic.py
HubiCAuthenticator._get_authorization_token
def _get_authorization_token(self, session): """Load the HubiC form, submit it and return an authorization token. This will load the HTML form to accept if the application can access the user account and submit the form using the user's credentials. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The (short lived) authorization code to use to get the refresh token. :rtype: string """ request_scope = 'account.r,credentials.r' params = { 'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'response_type': 'code', 'scope': request_scope, 'state': random_str_generator(), } r = session.get("https://api.hubic.com/oauth/auth", params=params, authenticated=False) if r.status_code != 200: raise AuthorizationFailure() oauth_match = re.search(r'name="oauth" value="([0-9]+)"', r.text) if oauth_match is None: raise AuthorizationFailure() oauth_value = oauth_match.group(1) if oauth_value is None: AuthorizationFailure() payload = { 'oauth': oauth_value, 'action': 'accepted', 'account': 'r', 'credentials': 'r', 'login': self.email, 'user_pwd': self.password, } # this is necessary because the API will return a 509 error # (bandwidth exceeded) if we don't wait a little time.sleep(2) headers = { 'Referer': r.url, 'Content-Type': 'application/x-www-form-urlencoded', } r = session.post("https://api.hubic.com/oauth/auth", headers=headers, data=payload, redirect=False, authenticated=False) if r.status_code != 302: raise AuthorizationFailure() # location looks like this, and we need the code: # http://localhost/?code=...&scope=account.r&state=randomstring location_info = dict( map(lambda item: item.split('='), r.headers['location'].split('?')[1].split('&') ) ) assert ( 'code' in location_info and 'scope' in location_info and location_info['scope'] == request_scope and 'state' in location_info and location_info['state'] == params['state'] ) return location_info['code']
python
def _get_authorization_token(self, session): """Load the HubiC form, submit it and return an authorization token. This will load the HTML form to accept if the application can access the user account and submit the form using the user's credentials. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The (short lived) authorization code to use to get the refresh token. :rtype: string """ request_scope = 'account.r,credentials.r' params = { 'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'response_type': 'code', 'scope': request_scope, 'state': random_str_generator(), } r = session.get("https://api.hubic.com/oauth/auth", params=params, authenticated=False) if r.status_code != 200: raise AuthorizationFailure() oauth_match = re.search(r'name="oauth" value="([0-9]+)"', r.text) if oauth_match is None: raise AuthorizationFailure() oauth_value = oauth_match.group(1) if oauth_value is None: AuthorizationFailure() payload = { 'oauth': oauth_value, 'action': 'accepted', 'account': 'r', 'credentials': 'r', 'login': self.email, 'user_pwd': self.password, } # this is necessary because the API will return a 509 error # (bandwidth exceeded) if we don't wait a little time.sleep(2) headers = { 'Referer': r.url, 'Content-Type': 'application/x-www-form-urlencoded', } r = session.post("https://api.hubic.com/oauth/auth", headers=headers, data=payload, redirect=False, authenticated=False) if r.status_code != 302: raise AuthorizationFailure() # location looks like this, and we need the code: # http://localhost/?code=...&scope=account.r&state=randomstring location_info = dict( map(lambda item: item.split('='), r.headers['location'].split('?')[1].split('&') ) ) assert ( 'code' in location_info and 'scope' in location_info and location_info['scope'] == request_scope and 'state' in location_info and location_info['state'] == params['state'] ) return location_info['code']
[ "def", "_get_authorization_token", "(", "self", ",", "session", ")", ":", "request_scope", "=", "'account.r,credentials.r'", "params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "'response_type'", ":", "'code'", ",", "'scope'", ":", "request_scope", ",", "'state'", ":", "random_str_generator", "(", ")", ",", "}", "r", "=", "session", ".", "get", "(", "\"https://api.hubic.com/oauth/auth\"", ",", "params", "=", "params", ",", "authenticated", "=", "False", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "AuthorizationFailure", "(", ")", "oauth_match", "=", "re", ".", "search", "(", "r'name=\"oauth\" value=\"([0-9]+)\"'", ",", "r", ".", "text", ")", "if", "oauth_match", "is", "None", ":", "raise", "AuthorizationFailure", "(", ")", "oauth_value", "=", "oauth_match", ".", "group", "(", "1", ")", "if", "oauth_value", "is", "None", ":", "AuthorizationFailure", "(", ")", "payload", "=", "{", "'oauth'", ":", "oauth_value", ",", "'action'", ":", "'accepted'", ",", "'account'", ":", "'r'", ",", "'credentials'", ":", "'r'", ",", "'login'", ":", "self", ".", "email", ",", "'user_pwd'", ":", "self", ".", "password", ",", "}", "# this is necessary because the API will return a 509 error", "# (bandwidth exceeded) if we don't wait a little", "time", ".", "sleep", "(", "2", ")", "headers", "=", "{", "'Referer'", ":", "r", ".", "url", ",", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", ",", "}", "r", "=", "session", ".", "post", "(", "\"https://api.hubic.com/oauth/auth\"", ",", "headers", "=", "headers", ",", "data", "=", "payload", ",", "redirect", "=", "False", ",", "authenticated", "=", "False", ")", "if", "r", ".", "status_code", "!=", "302", ":", "raise", "AuthorizationFailure", "(", ")", "# location looks like this, and we need the code:", "# http://localhost/?code=...&scope=account.r&state=randomstring", "location_info", "=", "dict", "(", "map", "(", "lambda", "item", ":", "item", ".", "split", "(", "'='", ")", ",", "r", ".", "headers", "[", "'location'", "]", ".", "split", "(", "'?'", ")", "[", "1", "]", ".", "split", "(", "'&'", ")", ")", ")", "assert", "(", "'code'", "in", "location_info", "and", "'scope'", "in", "location_info", "and", "location_info", "[", "'scope'", "]", "==", "request_scope", "and", "'state'", "in", "location_info", "and", "location_info", "[", "'state'", "]", "==", "params", "[", "'state'", "]", ")", "return", "location_info", "[", "'code'", "]" ]
Load the HubiC form, submit it and return an authorization token. This will load the HTML form to accept if the application can access the user account and submit the form using the user's credentials. :raises keystoneclient.exceptions.AuthorizationFailure: if something goes wrong. :returns: The (short lived) authorization code to use to get the refresh token. :rtype: string
[ "Load", "the", "HubiC", "form", "submit", "it", "and", "return", "an", "authorization", "token", "." ]
25e752f847613bb7e068c05e094a8abadaa7925a
https://github.com/lduchesne/python-openstacksdk-hubic/blob/25e752f847613bb7e068c05e094a8abadaa7925a/hubic/hubic.py#L237-L314
246,892
jmgilman/Neolib
neolib/pyamf/codec.py
Context.getStringForBytes
def getStringForBytes(self, s): """ Returns the corresponding string for the supplied utf-8 encoded bytes. If there is no string object, one is created. @since: 0.6 """ h = hash(s) u = self._unicodes.get(h, None) if u is not None: return u u = self._unicodes[h] = s.decode('utf-8') return u
python
def getStringForBytes(self, s): """ Returns the corresponding string for the supplied utf-8 encoded bytes. If there is no string object, one is created. @since: 0.6 """ h = hash(s) u = self._unicodes.get(h, None) if u is not None: return u u = self._unicodes[h] = s.decode('utf-8') return u
[ "def", "getStringForBytes", "(", "self", ",", "s", ")", ":", "h", "=", "hash", "(", "s", ")", "u", "=", "self", ".", "_unicodes", ".", "get", "(", "h", ",", "None", ")", "if", "u", "is", "not", "None", ":", "return", "u", "u", "=", "self", ".", "_unicodes", "[", "h", "]", "=", "s", ".", "decode", "(", "'utf-8'", ")", "return", "u" ]
Returns the corresponding string for the supplied utf-8 encoded bytes. If there is no string object, one is created. @since: 0.6
[ "Returns", "the", "corresponding", "string", "for", "the", "supplied", "utf", "-", "8", "encoded", "bytes", ".", "If", "there", "is", "no", "string", "object", "one", "is", "created", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/codec.py#L211-L226
246,893
jmgilman/Neolib
neolib/pyamf/codec.py
Context.getBytesForString
def getBytesForString(self, u): """ Returns the corresponding utf-8 encoded string for a given unicode object. If there is no string, one is encoded. @since: 0.6 """ h = hash(u) s = self._unicodes.get(h, None) if s is not None: return s s = self._unicodes[h] = u.encode('utf-8') return s
python
def getBytesForString(self, u): """ Returns the corresponding utf-8 encoded string for a given unicode object. If there is no string, one is encoded. @since: 0.6 """ h = hash(u) s = self._unicodes.get(h, None) if s is not None: return s s = self._unicodes[h] = u.encode('utf-8') return s
[ "def", "getBytesForString", "(", "self", ",", "u", ")", ":", "h", "=", "hash", "(", "u", ")", "s", "=", "self", ".", "_unicodes", ".", "get", "(", "h", ",", "None", ")", "if", "s", "is", "not", "None", ":", "return", "s", "s", "=", "self", ".", "_unicodes", "[", "h", "]", "=", "u", ".", "encode", "(", "'utf-8'", ")", "return", "s" ]
Returns the corresponding utf-8 encoded string for a given unicode object. If there is no string, one is encoded. @since: 0.6
[ "Returns", "the", "corresponding", "utf", "-", "8", "encoded", "string", "for", "a", "given", "unicode", "object", ".", "If", "there", "is", "no", "string", "one", "is", "encoded", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/codec.py#L228-L243
246,894
jmgilman/Neolib
neolib/pyamf/codec.py
Decoder.readElement
def readElement(self): """ Reads an AMF3 element from the data stream. @raise DecodeError: The ActionScript type is unsupported. @raise EOStream: No more data left to decode. """ pos = self.stream.tell() try: t = self.stream.read(1) except IOError: raise pyamf.EOStream try: func = self._func_cache[t] except KeyError: func = self.getTypeFunc(t) if not func: raise pyamf.DecodeError("Unsupported ActionScript type %s" % ( hex(ord(t)),)) self._func_cache[t] = func try: return func() except IOError: self.stream.seek(pos) raise
python
def readElement(self): """ Reads an AMF3 element from the data stream. @raise DecodeError: The ActionScript type is unsupported. @raise EOStream: No more data left to decode. """ pos = self.stream.tell() try: t = self.stream.read(1) except IOError: raise pyamf.EOStream try: func = self._func_cache[t] except KeyError: func = self.getTypeFunc(t) if not func: raise pyamf.DecodeError("Unsupported ActionScript type %s" % ( hex(ord(t)),)) self._func_cache[t] = func try: return func() except IOError: self.stream.seek(pos) raise
[ "def", "readElement", "(", "self", ")", ":", "pos", "=", "self", ".", "stream", ".", "tell", "(", ")", "try", ":", "t", "=", "self", ".", "stream", ".", "read", "(", "1", ")", "except", "IOError", ":", "raise", "pyamf", ".", "EOStream", "try", ":", "func", "=", "self", ".", "_func_cache", "[", "t", "]", "except", "KeyError", ":", "func", "=", "self", ".", "getTypeFunc", "(", "t", ")", "if", "not", "func", ":", "raise", "pyamf", ".", "DecodeError", "(", "\"Unsupported ActionScript type %s\"", "%", "(", "hex", "(", "ord", "(", "t", ")", ")", ",", ")", ")", "self", ".", "_func_cache", "[", "t", "]", "=", "func", "try", ":", "return", "func", "(", ")", "except", "IOError", ":", "self", ".", "stream", ".", "seek", "(", "pos", ")", "raise" ]
Reads an AMF3 element from the data stream. @raise DecodeError: The ActionScript type is unsupported. @raise EOStream: No more data left to decode.
[ "Reads", "an", "AMF3", "element", "from", "the", "data", "stream", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/codec.py#L312-L342
246,895
jmgilman/Neolib
neolib/pyamf/codec.py
Encoder.writeSequence
def writeSequence(self, iterable): """ Encodes an iterable. The default is to write If the iterable has an al """ try: alias = self.context.getClassAlias(iterable.__class__) except (AttributeError, pyamf.UnknownClassAlias): self.writeList(iterable) return if alias.external: # a is a subclassed list with a registered alias - push to the # correct method self.writeObject(iterable) return self.writeList(iterable)
python
def writeSequence(self, iterable): """ Encodes an iterable. The default is to write If the iterable has an al """ try: alias = self.context.getClassAlias(iterable.__class__) except (AttributeError, pyamf.UnknownClassAlias): self.writeList(iterable) return if alias.external: # a is a subclassed list with a registered alias - push to the # correct method self.writeObject(iterable) return self.writeList(iterable)
[ "def", "writeSequence", "(", "self", ",", "iterable", ")", ":", "try", ":", "alias", "=", "self", ".", "context", ".", "getClassAlias", "(", "iterable", ".", "__class__", ")", "except", "(", "AttributeError", ",", "pyamf", ".", "UnknownClassAlias", ")", ":", "self", ".", "writeList", "(", "iterable", ")", "return", "if", "alias", ".", "external", ":", "# a is a subclassed list with a registered alias - push to the", "# correct method", "self", ".", "writeObject", "(", "iterable", ")", "return", "self", ".", "writeList", "(", "iterable", ")" ]
Encodes an iterable. The default is to write If the iterable has an al
[ "Encodes", "an", "iterable", ".", "The", "default", "is", "to", "write", "If", "the", "iterable", "has", "an", "al" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/codec.py#L391-L409
246,896
jmgilman/Neolib
neolib/pyamf/codec.py
Encoder.writeGenerator
def writeGenerator(self, gen): """ Iterates over a generator object and encodes all that is returned. """ n = getattr(gen, 'next') while True: try: self.writeElement(n()) except StopIteration: break
python
def writeGenerator(self, gen): """ Iterates over a generator object and encodes all that is returned. """ n = getattr(gen, 'next') while True: try: self.writeElement(n()) except StopIteration: break
[ "def", "writeGenerator", "(", "self", ",", "gen", ")", ":", "n", "=", "getattr", "(", "gen", ",", "'next'", ")", "while", "True", ":", "try", ":", "self", ".", "writeElement", "(", "n", "(", ")", ")", "except", "StopIteration", ":", "break" ]
Iterates over a generator object and encodes all that is returned.
[ "Iterates", "over", "a", "generator", "object", "and", "encodes", "all", "that", "is", "returned", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/codec.py#L411-L421
246,897
SmartDeveloperHub/agora-service-provider
agora/provider/jobs/collect.py
collect_fragment
def collect_fragment(event, agora_host): """ Execute a search plan for the declared graph pattern and sends all obtained triples to the corresponding collector functions (config """ agora = Agora(agora_host) graph_pattern = "" for tp in __triple_patterns: graph_pattern += '{} . '.format(tp) fragment, _, graph = agora.get_fragment_generator('{%s}' % graph_pattern, stop_event=event, workers=4) __extract_pattern_nodes(graph) log.info('querying { %s}' % graph_pattern) for (t, s, p, o) in fragment: collectors = __triple_patterns[str(__plan_patterns[t])] for c, args in collectors: log.debug('Sending triple {} {} {} to {}'.format(s.n3(graph.namespace_manager), graph.qname(p), o.n3(graph.namespace_manager), c)) c((s, p, o)) if event.isSet(): raise Exception('Abort collecting fragment') yield (c.func_name, (t, s, p, o))
python
def collect_fragment(event, agora_host): """ Execute a search plan for the declared graph pattern and sends all obtained triples to the corresponding collector functions (config """ agora = Agora(agora_host) graph_pattern = "" for tp in __triple_patterns: graph_pattern += '{} . '.format(tp) fragment, _, graph = agora.get_fragment_generator('{%s}' % graph_pattern, stop_event=event, workers=4) __extract_pattern_nodes(graph) log.info('querying { %s}' % graph_pattern) for (t, s, p, o) in fragment: collectors = __triple_patterns[str(__plan_patterns[t])] for c, args in collectors: log.debug('Sending triple {} {} {} to {}'.format(s.n3(graph.namespace_manager), graph.qname(p), o.n3(graph.namespace_manager), c)) c((s, p, o)) if event.isSet(): raise Exception('Abort collecting fragment') yield (c.func_name, (t, s, p, o))
[ "def", "collect_fragment", "(", "event", ",", "agora_host", ")", ":", "agora", "=", "Agora", "(", "agora_host", ")", "graph_pattern", "=", "\"\"", "for", "tp", "in", "__triple_patterns", ":", "graph_pattern", "+=", "'{} . '", ".", "format", "(", "tp", ")", "fragment", ",", "_", ",", "graph", "=", "agora", ".", "get_fragment_generator", "(", "'{%s}'", "%", "graph_pattern", ",", "stop_event", "=", "event", ",", "workers", "=", "4", ")", "__extract_pattern_nodes", "(", "graph", ")", "log", ".", "info", "(", "'querying { %s}'", "%", "graph_pattern", ")", "for", "(", "t", ",", "s", ",", "p", ",", "o", ")", "in", "fragment", ":", "collectors", "=", "__triple_patterns", "[", "str", "(", "__plan_patterns", "[", "t", "]", ")", "]", "for", "c", ",", "args", "in", "collectors", ":", "log", ".", "debug", "(", "'Sending triple {} {} {} to {}'", ".", "format", "(", "s", ".", "n3", "(", "graph", ".", "namespace_manager", ")", ",", "graph", ".", "qname", "(", "p", ")", ",", "o", ".", "n3", "(", "graph", ".", "namespace_manager", ")", ",", "c", ")", ")", "c", "(", "(", "s", ",", "p", ",", "o", ")", ")", "if", "event", ".", "isSet", "(", ")", ":", "raise", "Exception", "(", "'Abort collecting fragment'", ")", "yield", "(", "c", ".", "func_name", ",", "(", "t", ",", "s", ",", "p", ",", "o", ")", ")" ]
Execute a search plan for the declared graph pattern and sends all obtained triples to the corresponding collector functions (config
[ "Execute", "a", "search", "plan", "for", "the", "declared", "graph", "pattern", "and", "sends", "all", "obtained", "triples", "to", "the", "corresponding", "collector", "functions", "(", "config" ]
3962207e5701c659c74c8cfffcbc4b0a63eac4b4
https://github.com/SmartDeveloperHub/agora-service-provider/blob/3962207e5701c659c74c8cfffcbc4b0a63eac4b4/agora/provider/jobs/collect.py#L88-L108
246,898
opinkerfi/nago
nago/extensions/settings.py
get
def get(key, section='main'): """ Get a single option from """ return nago.settings.get_option(option_name=key, section_name=section)
python
def get(key, section='main'): """ Get a single option from """ return nago.settings.get_option(option_name=key, section_name=section)
[ "def", "get", "(", "key", ",", "section", "=", "'main'", ")", ":", "return", "nago", ".", "settings", ".", "get_option", "(", "option_name", "=", "key", ",", "section_name", "=", "section", ")" ]
Get a single option from
[ "Get", "a", "single", "option", "from" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/settings.py#L16-L18
246,899
nicktgr15/sac
sac/methods/vad.py
Vad._frame_generator
def _frame_generator(self, frame_duration_ms, audio, sample_rate): """Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. """ n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) offset = 0 timestamp = 0.0 duration = (float(n) / sample_rate) / 2.0 while offset + n < len(audio): yield self.Frame(audio[offset:offset + n], timestamp, duration) timestamp += duration offset += n
python
def _frame_generator(self, frame_duration_ms, audio, sample_rate): """Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. """ n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) offset = 0 timestamp = 0.0 duration = (float(n) / sample_rate) / 2.0 while offset + n < len(audio): yield self.Frame(audio[offset:offset + n], timestamp, duration) timestamp += duration offset += n
[ "def", "_frame_generator", "(", "self", ",", "frame_duration_ms", ",", "audio", ",", "sample_rate", ")", ":", "n", "=", "int", "(", "sample_rate", "*", "(", "frame_duration_ms", "/", "1000.0", ")", "*", "2", ")", "offset", "=", "0", "timestamp", "=", "0.0", "duration", "=", "(", "float", "(", "n", ")", "/", "sample_rate", ")", "/", "2.0", "while", "offset", "+", "n", "<", "len", "(", "audio", ")", ":", "yield", "self", ".", "Frame", "(", "audio", "[", "offset", ":", "offset", "+", "n", "]", ",", "timestamp", ",", "duration", ")", "timestamp", "+=", "duration", "offset", "+=", "n" ]
Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration.
[ "Generates", "audio", "frames", "from", "PCM", "audio", "data", ".", "Takes", "the", "desired", "frame", "duration", "in", "milliseconds", "the", "PCM", "data", "and", "the", "sample", "rate", ".", "Yields", "Frames", "of", "the", "requested", "duration", "." ]
4b1d5d8e6ca2c437972db34ddc72990860865159
https://github.com/nicktgr15/sac/blob/4b1d5d8e6ca2c437972db34ddc72990860865159/sac/methods/vad.py#L32-L45