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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
40,400
inveniosoftware-attic/invenio-comments
invenio_comments/utils.py
comments_nb_counts
def comments_nb_counts(): """Get number of comments for the record `recid`.""" recid = request.view_args.get('recid') if recid is None: return elif recid == 0: return 0 else: return CmtRECORDCOMMENT.count(*[ CmtRECORDCOMMENT.id_bibrec == recid, CmtREC...
python
def comments_nb_counts(): """Get number of comments for the record `recid`.""" recid = request.view_args.get('recid') if recid is None: return elif recid == 0: return 0 else: return CmtRECORDCOMMENT.count(*[ CmtRECORDCOMMENT.id_bibrec == recid, CmtREC...
[ "def", "comments_nb_counts", "(", ")", ":", "recid", "=", "request", ".", "view_args", ".", "get", "(", "'recid'", ")", "if", "recid", "is", "None", ":", "return", "elif", "recid", "==", "0", ":", "return", "0", "else", ":", "return", "CmtRECORDCOMMENT",...
Get number of comments for the record `recid`.
[ "Get", "number", "of", "comments", "for", "the", "record", "recid", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/utils.py#L27-L40
40,401
adamfast/faadata
faadata/airports/utils.py
decide_k
def decide_k(airport_code): """A function to decide if a leading 'K' is throwing off an airport match and return the correct code.""" if airport_code[:1].upper() == 'K': try: # if there's a match without the K that's likely what it is. return Airport.objects.get(location_identifier__iexact=...
python
def decide_k(airport_code): """A function to decide if a leading 'K' is throwing off an airport match and return the correct code.""" if airport_code[:1].upper() == 'K': try: # if there's a match without the K that's likely what it is. return Airport.objects.get(location_identifier__iexact=...
[ "def", "decide_k", "(", "airport_code", ")", ":", "if", "airport_code", "[", ":", "1", "]", ".", "upper", "(", ")", "==", "'K'", ":", "try", ":", "# if there's a match without the K that's likely what it is.", "return", "Airport", ".", "objects", ".", "get", "...
A function to decide if a leading 'K' is throwing off an airport match and return the correct code.
[ "A", "function", "to", "decide", "if", "a", "leading", "K", "is", "throwing", "off", "an", "airport", "match", "and", "return", "the", "correct", "code", "." ]
3c7d651b28160b7cb24724f67ebffd6bd0b490b9
https://github.com/adamfast/faadata/blob/3c7d651b28160b7cb24724f67ebffd6bd0b490b9/faadata/airports/utils.py#L3-L12
40,402
slickqa/python-client
slickqa/micromodels/packages/PySO8601/datetimestamps.py
parse_date
def parse_date(datestring): """Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object. """ datestring = str(datestring).strip() if not datestring[0].isdigit(): raise ParseError() if 'W' in datestring.upper(): try: datestring =...
python
def parse_date(datestring): """Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object. """ datestring = str(datestring).strip() if not datestring[0].isdigit(): raise ParseError() if 'W' in datestring.upper(): try: datestring =...
[ "def", "parse_date", "(", "datestring", ")", ":", "datestring", "=", "str", "(", "datestring", ")", ".", "strip", "(", ")", "if", "not", "datestring", "[", "0", "]", ".", "isdigit", "(", ")", ":", "raise", "ParseError", "(", ")", "if", "'W'", "in", ...
Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object.
[ "Attepmts", "to", "parse", "an", "ISO8601", "formatted", "datestring", "." ]
1d36b4977cd4140d7d24917cab2b3f82b60739c2
https://github.com/slickqa/python-client/blob/1d36b4977cd4140d7d24917cab2b3f82b60739c2/slickqa/micromodels/packages/PySO8601/datetimestamps.py#L91-L120
40,403
slickqa/python-client
slickqa/micromodels/packages/PySO8601/datetimestamps.py
parse_time
def parse_time(timestring): """Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object. """ timestring = str(timestring).strip() for regex, pattern in TIME_FORMATS: if regex.match(timestring): found = regex.search(timestring).groupdict() ...
python
def parse_time(timestring): """Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object. """ timestring = str(timestring).strip() for regex, pattern in TIME_FORMATS: if regex.match(timestring): found = regex.search(timestring).groupdict() ...
[ "def", "parse_time", "(", "timestring", ")", ":", "timestring", "=", "str", "(", "timestring", ")", ".", "strip", "(", ")", "for", "regex", ",", "pattern", "in", "TIME_FORMATS", ":", "if", "regex", ".", "match", "(", "timestring", ")", ":", "found", "=...
Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object.
[ "Attepmts", "to", "parse", "an", "ISO8601", "formatted", "timestring", "." ]
1d36b4977cd4140d7d24917cab2b3f82b60739c2
https://github.com/slickqa/python-client/blob/1d36b4977cd4140d7d24917cab2b3f82b60739c2/slickqa/micromodels/packages/PySO8601/datetimestamps.py#L123-L145
40,404
thespacedoctor/fundamentals
fundamentals/mysql/database.py
database.connect
def connect(self): """connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage """ self.log.debug('starting the ``get`` method') dbSettings = self.dbSettings port = False if "tunnel" in d...
python
def connect(self): """connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage """ self.log.debug('starting the ``get`` method') dbSettings = self.dbSettings port = False if "tunnel" in d...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``get`` method'", ")", "dbSettings", "=", "self", ".", "dbSettings", "port", "=", "False", "if", "\"tunnel\"", "in", "dbSettings", "and", "dbSettings", "[", "\"tun...
connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage
[ "connect", "to", "the", "database" ]
1d2c007ac74442ec2eabde771cfcacdb9c1ab382
https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/mysql/database.py#L85-L125
40,405
lycantropos/paradigm
paradigm/cached.py
map_
def map_(cache: Mapping[Domain, Range]) -> Operator[Map[Domain, Range]]: """ Returns decorator that calls wrapped function if nothing was found in cache for its argument. Wrapped function arguments should be hashable. """ def wrapper(function: Map[Domain, Range]) -> Map[Domain, Range]: ...
python
def map_(cache: Mapping[Domain, Range]) -> Operator[Map[Domain, Range]]: """ Returns decorator that calls wrapped function if nothing was found in cache for its argument. Wrapped function arguments should be hashable. """ def wrapper(function: Map[Domain, Range]) -> Map[Domain, Range]: ...
[ "def", "map_", "(", "cache", ":", "Mapping", "[", "Domain", ",", "Range", "]", ")", "->", "Operator", "[", "Map", "[", "Domain", ",", "Range", "]", "]", ":", "def", "wrapper", "(", "function", ":", "Map", "[", "Domain", ",", "Range", "]", ")", "-...
Returns decorator that calls wrapped function if nothing was found in cache for its argument. Wrapped function arguments should be hashable.
[ "Returns", "decorator", "that", "calls", "wrapped", "function", "if", "nothing", "was", "found", "in", "cache", "for", "its", "argument", "." ]
70415f77964dbb1b6d444f890a5d988174194ff0
https://github.com/lycantropos/paradigm/blob/70415f77964dbb1b6d444f890a5d988174194ff0/paradigm/cached.py#L15-L33
40,406
lycantropos/paradigm
paradigm/cached.py
updatable_map
def updatable_map(cache: MutableMapping[Domain, Range]) -> Operator[Map]: """ Returns decorator that calls wrapped function if nothing was found in cache for its argument and reuses result afterwards. Wrapped function arguments should be hashable. """ def wrapper(function: Map[Domain, Rang...
python
def updatable_map(cache: MutableMapping[Domain, Range]) -> Operator[Map]: """ Returns decorator that calls wrapped function if nothing was found in cache for its argument and reuses result afterwards. Wrapped function arguments should be hashable. """ def wrapper(function: Map[Domain, Rang...
[ "def", "updatable_map", "(", "cache", ":", "MutableMapping", "[", "Domain", ",", "Range", "]", ")", "->", "Operator", "[", "Map", "]", ":", "def", "wrapper", "(", "function", ":", "Map", "[", "Domain", ",", "Range", "]", ")", "->", "Map", "[", "Domai...
Returns decorator that calls wrapped function if nothing was found in cache for its argument and reuses result afterwards. Wrapped function arguments should be hashable.
[ "Returns", "decorator", "that", "calls", "wrapped", "function", "if", "nothing", "was", "found", "in", "cache", "for", "its", "argument", "and", "reuses", "result", "afterwards", "." ]
70415f77964dbb1b6d444f890a5d988174194ff0
https://github.com/lycantropos/paradigm/blob/70415f77964dbb1b6d444f890a5d988174194ff0/paradigm/cached.py#L37-L58
40,407
lycantropos/paradigm
paradigm/cached.py
property_
def property_(getter: Map[Domain, Range]) -> property: """ Returns property that calls given getter on the first access and reuses result afterwards. Class instances should be hashable and weak referenceable. """ return property(map_(WeakKeyDictionary())(getter))
python
def property_(getter: Map[Domain, Range]) -> property: """ Returns property that calls given getter on the first access and reuses result afterwards. Class instances should be hashable and weak referenceable. """ return property(map_(WeakKeyDictionary())(getter))
[ "def", "property_", "(", "getter", ":", "Map", "[", "Domain", ",", "Range", "]", ")", "->", "property", ":", "return", "property", "(", "map_", "(", "WeakKeyDictionary", "(", ")", ")", "(", "getter", ")", ")" ]
Returns property that calls given getter on the first access and reuses result afterwards. Class instances should be hashable and weak referenceable.
[ "Returns", "property", "that", "calls", "given", "getter", "on", "the", "first", "access", "and", "reuses", "result", "afterwards", "." ]
70415f77964dbb1b6d444f890a5d988174194ff0
https://github.com/lycantropos/paradigm/blob/70415f77964dbb1b6d444f890a5d988174194ff0/paradigm/cached.py#L61-L68
40,408
clinicedc/edc-auth
edc_auth/views/login_view.py
LoginView.get_context_data
def get_context_data(self, **kwargs): """Tests cookies. """ self.request.session.set_test_cookie() if not self.request.session.test_cookie_worked(): messages.add_message( self.request, messages.ERROR, "Please enable cookies.") self.request.session.dele...
python
def get_context_data(self, **kwargs): """Tests cookies. """ self.request.session.set_test_cookie() if not self.request.session.test_cookie_worked(): messages.add_message( self.request, messages.ERROR, "Please enable cookies.") self.request.session.dele...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", ".", "session", ".", "set_test_cookie", "(", ")", "if", "not", "self", ".", "request", ".", "session", ".", "test_cookie_worked", "(", ")", ":", "messages"...
Tests cookies.
[ "Tests", "cookies", "." ]
e633a5461139d3799f389f7bed0e02c9d2c1e103
https://github.com/clinicedc/edc-auth/blob/e633a5461139d3799f389f7bed0e02c9d2c1e103/edc_auth/views/login_view.py#L13-L21
40,409
PatrikValkovic/grammpy
grammpy/transforms/Traversing.py
Traversing.print
def print(root): # type: (Union[Nonterminal,Terminal,Rule])-> str """ Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | ...
python
def print(root): # type: (Union[Nonterminal,Terminal,Rule])-> str """ Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | ...
[ "def", "print", "(", "root", ")", ":", "# type: (Union[Nonterminal,Terminal,Rule])-> str", "# print the part before the element", "def", "print_before", "(", "previous", "=", "0", ",", "defined", "=", "None", ",", "is_last", "=", "False", ")", ":", "defined", "=", ...
Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | `--(R)SplitRules4 | `--(T)e `--(N)Concat `--(R)Split...
[ "Transform", "the", "parsed", "tree", "to", "the", "string", ".", "Expects", "tree", "like", "structure", ".", "You", "can", "see", "example", "output", "below", "." ]
879ce0ef794ac2823acc19314fcd7a8aba53e50f
https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/transforms/Traversing.py#L143-L209
40,410
freevoid/django-datafilters
datafilters/views.py
FilterFormMixin.get_filter
def get_filter(self): """ Get FilterForm instance. """ return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining)
python
def get_filter(self): """ Get FilterForm instance. """ return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining)
[ "def", "get_filter", "(", "self", ")", ":", "return", "self", ".", "filter_form_cls", "(", "self", ".", "request", ".", "GET", ",", "runtime_context", "=", "self", ".", "get_runtime_context", "(", ")", ",", "use_filter_chaining", "=", "self", ".", "use_filte...
Get FilterForm instance.
[ "Get", "FilterForm", "instance", "." ]
99051b3b3e97946981c0e9697576b0100093287c
https://github.com/freevoid/django-datafilters/blob/99051b3b3e97946981c0e9697576b0100093287c/datafilters/views.py#L14-L20
40,411
freevoid/django-datafilters
datafilters/views.py
FilterFormMixin.get_context_data
def get_context_data(self, **kwargs): """ Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. """ context ...
python
def get_context_data(self, **kwargs): """ Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. """ context ...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "FilterFormMixin", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", "[", "self", ".", "context_filterform_name", "]"...
Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization.
[ "Add", "filter", "form", "to", "the", "context", "." ]
99051b3b3e97946981c0e9697576b0100093287c
https://github.com/freevoid/django-datafilters/blob/99051b3b3e97946981c0e9697576b0100093287c/datafilters/views.py#L33-L43
40,412
chaosim/dao
dao/compile.py
compile_to_python
def compile_to_python(exp, env, done=None): '''assemble steps from dao expression to python code''' original_exp = exp compiler = Compiler() if done is None: done = il.Done(compiler.new_var(il.ConstLocalVar('v'))) compiler.exit_block_cont_map = {} compiler.continue_block_cont_map = {} compile...
python
def compile_to_python(exp, env, done=None): '''assemble steps from dao expression to python code''' original_exp = exp compiler = Compiler() if done is None: done = il.Done(compiler.new_var(il.ConstLocalVar('v'))) compiler.exit_block_cont_map = {} compiler.continue_block_cont_map = {} compile...
[ "def", "compile_to_python", "(", "exp", ",", "env", ",", "done", "=", "None", ")", ":", "original_exp", "=", "exp", "compiler", "=", "Compiler", "(", ")", "if", "done", "is", "None", ":", "done", "=", "il", ".", "Done", "(", "compiler", ".", "new_var...
assemble steps from dao expression to python code
[ "assemble", "steps", "from", "dao", "expression", "to", "python", "code" ]
d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa
https://github.com/chaosim/dao/blob/d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa/dao/compile.py#L41-L66
40,413
CodyKochmann/generators
generators/last.py
last
def last(pipe, items=1): ''' this function simply returns the last item in an iterable ''' if items == 1: tmp=None for i in pipe: tmp=i return tmp else: return tuple(deque(pipe, maxlen=items))
python
def last(pipe, items=1): ''' this function simply returns the last item in an iterable ''' if items == 1: tmp=None for i in pipe: tmp=i return tmp else: return tuple(deque(pipe, maxlen=items))
[ "def", "last", "(", "pipe", ",", "items", "=", "1", ")", ":", "if", "items", "==", "1", ":", "tmp", "=", "None", "for", "i", "in", "pipe", ":", "tmp", "=", "i", "return", "tmp", "else", ":", "return", "tuple", "(", "deque", "(", "pipe", ",", ...
this function simply returns the last item in an iterable
[ "this", "function", "simply", "returns", "the", "last", "item", "in", "an", "iterable" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/last.py#L9-L17
40,414
kgaughan/dbkit
examples/counters.py
print_help
def print_help(filename, table, dest=sys.stdout): """ Print help to the given destination file object. """ cmds = '|'.join(sorted(table.keys())) print >> dest, "Syntax: %s %s [args]" % (path.basename(filename), cmds)
python
def print_help(filename, table, dest=sys.stdout): """ Print help to the given destination file object. """ cmds = '|'.join(sorted(table.keys())) print >> dest, "Syntax: %s %s [args]" % (path.basename(filename), cmds)
[ "def", "print_help", "(", "filename", ",", "table", ",", "dest", "=", "sys", ".", "stdout", ")", ":", "cmds", "=", "'|'", ".", "join", "(", "sorted", "(", "table", ".", "keys", "(", ")", ")", ")", "print", ">>", "dest", ",", "\"Syntax: %s %s [args]\"...
Print help to the given destination file object.
[ "Print", "help", "to", "the", "given", "destination", "file", "object", "." ]
2aef6376a60965d7820c91692046f4bcf7d43640
https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/counters.py#L82-L87
40,415
kgaughan/dbkit
examples/counters.py
dispatch
def dispatch(table, args): """ Dispatches to a function based on the contents of `args`. """ # No arguments: print help. if len(args) == 1: print_help(args[0], table) sys.exit(0) # Bad command or incorrect number of arguments: print help to stderr. if args[1] not in table or...
python
def dispatch(table, args): """ Dispatches to a function based on the contents of `args`. """ # No arguments: print help. if len(args) == 1: print_help(args[0], table) sys.exit(0) # Bad command or incorrect number of arguments: print help to stderr. if args[1] not in table or...
[ "def", "dispatch", "(", "table", ",", "args", ")", ":", "# No arguments: print help.", "if", "len", "(", "args", ")", "==", "1", ":", "print_help", "(", "args", "[", "0", "]", ",", "table", ")", "sys", ".", "exit", "(", "0", ")", "# Bad command or inco...
Dispatches to a function based on the contents of `args`.
[ "Dispatches", "to", "a", "function", "based", "on", "the", "contents", "of", "args", "." ]
2aef6376a60965d7820c91692046f4bcf7d43640
https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/counters.py#L90-L115
40,416
consbio/parserutils
parserutils/strings.py
find_all
def find_all(s, sub, start=0, end=0, limit=-1, reverse=False): """ Find all indexes of sub in s. :param s: the string to search :param sub: the string to search for :param start: the index in s at which to begin the search (same as in ''.find) :param end: the index in s at which to stop searchi...
python
def find_all(s, sub, start=0, end=0, limit=-1, reverse=False): """ Find all indexes of sub in s. :param s: the string to search :param sub: the string to search for :param start: the index in s at which to begin the search (same as in ''.find) :param end: the index in s at which to stop searchi...
[ "def", "find_all", "(", "s", ",", "sub", ",", "start", "=", "0", ",", "end", "=", "0", ",", "limit", "=", "-", "1", ",", "reverse", "=", "False", ")", ":", "indexes", "=", "[", "]", "if", "not", "bool", "(", "s", "and", "sub", ")", ":", "re...
Find all indexes of sub in s. :param s: the string to search :param sub: the string to search for :param start: the index in s at which to begin the search (same as in ''.find) :param end: the index in s at which to stop searching (same as in ''.find) :param limit: the maximum number of matches to ...
[ "Find", "all", "indexes", "of", "sub", "in", "s", "." ]
f13f80db99ed43479336b116e38512e3566e4623
https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/strings.py#L72-L117
40,417
inveniosoftware-attic/invenio-utils
invenio_utils/container.py
get_substructure
def get_substructure(data, path): """ Tries to retrieve a sub-structure within some data. If the path does not match any sub-structure, returns None. >>> data = {'a': 5, 'b': {'c': [1, 2, [{'f': [57]}], 4], 'd': 'test'}} >>> get_substructure(island, "bc") [1, 2, [{'f': [57]}], 4] >>> get_su...
python
def get_substructure(data, path): """ Tries to retrieve a sub-structure within some data. If the path does not match any sub-structure, returns None. >>> data = {'a': 5, 'b': {'c': [1, 2, [{'f': [57]}], 4], 'd': 'test'}} >>> get_substructure(island, "bc") [1, 2, [{'f': [57]}], 4] >>> get_su...
[ "def", "get_substructure", "(", "data", ",", "path", ")", ":", "if", "not", "len", "(", "path", ")", ":", "return", "data", "try", ":", "return", "get_substructure", "(", "data", "[", "path", "[", "0", "]", "]", ",", "path", "[", "1", ":", "]", "...
Tries to retrieve a sub-structure within some data. If the path does not match any sub-structure, returns None. >>> data = {'a': 5, 'b': {'c': [1, 2, [{'f': [57]}], 4], 'd': 'test'}} >>> get_substructure(island, "bc") [1, 2, [{'f': [57]}], 4] >>> get_substructure(island, ['b', 'c']) [1, 2, [{'f...
[ "Tries", "to", "retrieve", "a", "sub", "-", "structure", "within", "some", "data", ".", "If", "the", "path", "does", "not", "match", "any", "sub", "-", "structure", "returns", "None", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/container.py#L23-L53
40,418
CodyKochmann/generators
generators/iterable.py
iterable
def iterable(target): ''' returns true if the given argument is iterable ''' if any(i in ('next', '__next__', '__iter__') for i in dir(target)): return True else: try: iter(target) return True except: return False
python
def iterable(target): ''' returns true if the given argument is iterable ''' if any(i in ('next', '__next__', '__iter__') for i in dir(target)): return True else: try: iter(target) return True except: return False
[ "def", "iterable", "(", "target", ")", ":", "if", "any", "(", "i", "in", "(", "'next'", ",", "'__next__'", ",", "'__iter__'", ")", "for", "i", "in", "dir", "(", "target", ")", ")", ":", "return", "True", "else", ":", "try", ":", "iter", "(", "tar...
returns true if the given argument is iterable
[ "returns", "true", "if", "the", "given", "argument", "is", "iterable" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/iterable.py#L11-L20
40,419
kellerza/pyqwikswitch
pyqwikswitch/threaded.py
QSUsb._thread_worker
def _thread_worker(self): """Process callbacks from the queue populated by &listen.""" while self._running: # Retrieve next cmd, or block packet = self._queue.get(True) if isinstance(packet, dict) and QS_CMD in packet: try: self._ca...
python
def _thread_worker(self): """Process callbacks from the queue populated by &listen.""" while self._running: # Retrieve next cmd, or block packet = self._queue.get(True) if isinstance(packet, dict) and QS_CMD in packet: try: self._ca...
[ "def", "_thread_worker", "(", "self", ")", ":", "while", "self", ".", "_running", ":", "# Retrieve next cmd, or block", "packet", "=", "self", ".", "_queue", ".", "get", "(", "True", ")", "if", "isinstance", "(", "packet", ",", "dict", ")", "and", "QS_CMD"...
Process callbacks from the queue populated by &listen.
[ "Process", "callbacks", "from", "the", "queue", "populated", "by", "&listen", "." ]
9d4f080048221eaee93e3eefcf641919ff1af586
https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/threaded.py#L42-L53
40,420
kellerza/pyqwikswitch
pyqwikswitch/threaded.py
QSUsb._thread_listen
def _thread_listen(self): """The main &listen loop.""" while self._running: try: rest = requests.get(URL_LISTEN.format(self._url), timeout=self._timeout) if rest.status_code == 200: self._queue.put(rest.j...
python
def _thread_listen(self): """The main &listen loop.""" while self._running: try: rest = requests.get(URL_LISTEN.format(self._url), timeout=self._timeout) if rest.status_code == 200: self._queue.put(rest.j...
[ "def", "_thread_listen", "(", "self", ")", ":", "while", "self", ".", "_running", ":", "try", ":", "rest", "=", "requests", ".", "get", "(", "URL_LISTEN", ".", "format", "(", "self", ".", "_url", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"...
The main &listen loop.
[ "The", "main", "&listen", "loop", "." ]
9d4f080048221eaee93e3eefcf641919ff1af586
https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/threaded.py#L55-L78
40,421
XRDX/pyleap
pyleap/color.py
hsla_to_rgba
def hsla_to_rgba(h, s, l, a): """ 0 <= H < 360, 0 <= s,l,a < 1 """ h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g,...
python
def hsla_to_rgba(h, s, l, a): """ 0 <= H < 360, 0 <= s,l,a < 1 """ h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g,...
[ "def", "hsla_to_rgba", "(", "h", ",", "s", ",", "l", ",", "a", ")", ":", "h", "=", "h", "%", "360", "s", "=", "max", "(", "0", ",", "min", "(", "1", ",", "s", ")", ")", "l", "=", "max", "(", "0", ",", "min", "(", "1", ",", "l", ")", ...
0 <= H < 360, 0 <= s,l,a < 1
[ "0", "<", "=", "H", "<", "360", "0", "<", "=", "s", "l", "a", "<", "1" ]
234c722cfbe66814254ab0d8f67d16b0b774f4d5
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/color.py#L40-L66
40,422
NickMonzillo/SmartCloud
SmartCloud/utils.py
dir_list
def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr)))
python
def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr)))
[ "def", "dir_list", "(", "directory", ")", ":", "try", ":", "content", "=", "listdir", "(", "directory", ")", "return", "content", "except", "WindowsError", "as", "winErr", ":", "print", "(", "\"Directory error: \"", "+", "str", "(", "(", "winErr", ")", ")"...
Returns the list of all files in the directory.
[ "Returns", "the", "list", "of", "all", "files", "in", "the", "directory", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L21-L27
40,423
NickMonzillo/SmartCloud
SmartCloud/utils.py
read_dir
def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text
python
def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text
[ "def", "read_dir", "(", "directory", ")", ":", "content", "=", "dir_list", "(", "directory", ")", "text", "=", "''", "for", "filename", "in", "content", ":", "text", "+=", "read_file", "(", "directory", "+", "'/'", "+", "filename", ")", "text", "+=", "...
Returns the text of all files in a directory.
[ "Returns", "the", "text", "of", "all", "files", "in", "a", "directory", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L29-L36
40,424
NickMonzillo/SmartCloud
SmartCloud/utils.py
colorize
def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence...
python
def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence...
[ "def", "colorize", "(", "occurence", ",", "maxoccurence", ",", "minoccurence", ")", ":", "if", "occurence", "==", "maxoccurence", ":", "color", "=", "(", "255", ",", "0", ",", "0", ")", "elif", "occurence", "==", "minoccurence", ":", "color", "=", "(", ...
A formula for determining colors.
[ "A", "formula", "for", "determining", "colors", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L50-L58
40,425
NickMonzillo/SmartCloud
SmartCloud/utils.py
fontsize
def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
python
def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
[ "def", "fontsize", "(", "count", ",", "maxsize", ",", "minsize", ",", "maxcount", ")", ":", "size", "=", "int", "(", "maxsize", "-", "(", "maxsize", ")", "*", "(", "(", "float", "(", "maxcount", "-", "count", ")", "/", "maxcount", ")", ")", ")", ...
A formula for determining font sizes.
[ "A", "formula", "for", "determining", "font", "sizes", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L77-L82
40,426
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Display/SSD1306.py
SSD1306Base._init_display
def _init_display(self): """! \~english Initialize the SSD1306 display chip \~chinese 初始化SSD1306显示芯片 """ self._command([ # 0xAE self.CMD_SSD1306_DISPLAY_OFF, #Stop Scroll self.CMD_SSD1306_SET_SCROLL_DEACTIVE, ...
python
def _init_display(self): """! \~english Initialize the SSD1306 display chip \~chinese 初始化SSD1306显示芯片 """ self._command([ # 0xAE self.CMD_SSD1306_DISPLAY_OFF, #Stop Scroll self.CMD_SSD1306_SET_SCROLL_DEACTIVE, ...
[ "def", "_init_display", "(", "self", ")", ":", "self", ".", "_command", "(", "[", "# 0xAE", "self", ".", "CMD_SSD1306_DISPLAY_OFF", ",", "#Stop Scroll", "self", ".", "CMD_SSD1306_SET_SCROLL_DEACTIVE", ",", "# 0xA8 SET MULTIPLEX 0x3F", "self", ".", "CMD_SSD1306_SET_MUL...
! \~english Initialize the SSD1306 display chip \~chinese 初始化SSD1306显示芯片
[ "!", "\\", "~english", "Initialize", "the", "SSD1306", "display", "chip" ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/SSD1306.py#L161-L212
40,427
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Display/SSD1306.py
SSD1306Base.display
def display(self, buffer = None): """! \~english Write buffer to physical display. @param buffer: Data to display,If <b>None</b> mean will use self._buffer data to display \~chinese 将缓冲区写入物理显示屏。 @param buffer: 要显示的数据,如果是 <b>None</b>(默认) 将把 self._buffer 数据写入物理显示屏...
python
def display(self, buffer = None): """! \~english Write buffer to physical display. @param buffer: Data to display,If <b>None</b> mean will use self._buffer data to display \~chinese 将缓冲区写入物理显示屏。 @param buffer: 要显示的数据,如果是 <b>None</b>(默认) 将把 self._buffer 数据写入物理显示屏...
[ "def", "display", "(", "self", ",", "buffer", "=", "None", ")", ":", "if", "buffer", "!=", "None", ":", "self", ".", "_display_buffer", "(", "buffer", ")", "else", ":", "self", ".", "_display_buffer", "(", "self", ".", "_buffer", ")" ]
! \~english Write buffer to physical display. @param buffer: Data to display,If <b>None</b> mean will use self._buffer data to display \~chinese 将缓冲区写入物理显示屏。 @param buffer: 要显示的数据,如果是 <b>None</b>(默认) 将把 self._buffer 数据写入物理显示屏
[ "!", "\\", "~english", "Write", "buffer", "to", "physical", "display", "." ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/SSD1306.py#L290-L302
40,428
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Display/SSD1306.py
SSD1306Base.scrollWith
def scrollWith(self, hStart = 0x00, hEnd=0x00, vOffset = 0x00, vStart=0x00, vEnd=0x00, int = 0x00, dire = "left" ): """! \~english Scroll screen @param hStart: Set horizontal scroll PAGE start address, value can be chosen between 0 and 7 @param hEnd: Set horizontal scroll PAGE ...
python
def scrollWith(self, hStart = 0x00, hEnd=0x00, vOffset = 0x00, vStart=0x00, vEnd=0x00, int = 0x00, dire = "left" ): """! \~english Scroll screen @param hStart: Set horizontal scroll PAGE start address, value can be chosen between 0 and 7 @param hEnd: Set horizontal scroll PAGE ...
[ "def", "scrollWith", "(", "self", ",", "hStart", "=", "0x00", ",", "hEnd", "=", "0x00", ",", "vOffset", "=", "0x00", ",", "vStart", "=", "0x00", ",", "vEnd", "=", "0x00", ",", "int", "=", "0x00", ",", "dire", "=", "\"left\"", ")", ":", "self", "....
! \~english Scroll screen @param hStart: Set horizontal scroll PAGE start address, value can be chosen between 0 and 7 @param hEnd: Set horizontal scroll PAGE end address, value can be chose between 0 and 7 @param vOffset: Vertical scroll offset row, if set to 0x00(0) means off...
[ "!", "\\", "~english", "Scroll", "screen" ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/SSD1306.py#L365-L405
40,429
praekeltfoundation/seed-scheduler
scheduler/tasks.py
QueueTasks.run
def run(self, schedule_type, lookup_id, **kwargs): """ Loads Schedule linked to provided lookup """ log = self.get_logger(**kwargs) log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id)) task_run = QueueTaskRun() task_run.task_id = self.request.id or uuid4() ...
python
def run(self, schedule_type, lookup_id, **kwargs): """ Loads Schedule linked to provided lookup """ log = self.get_logger(**kwargs) log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id)) task_run = QueueTaskRun() task_run.task_id = self.request.id or uuid4() ...
[ "def", "run", "(", "self", ",", "schedule_type", ",", "lookup_id", ",", "*", "*", "kwargs", ")", ":", "log", "=", "self", ".", "get_logger", "(", "*", "*", "kwargs", ")", "log", ".", "info", "(", "\"Queuing <%s> <%s>\"", "%", "(", "schedule_type", ",",...
Loads Schedule linked to provided lookup
[ "Loads", "Schedule", "linked", "to", "provided", "lookup" ]
cec47fe2319c28cbb1c6dcc1131fe30c835270e2
https://github.com/praekeltfoundation/seed-scheduler/blob/cec47fe2319c28cbb1c6dcc1131fe30c835270e2/scheduler/tasks.py#L128-L188
40,430
Julian/Minion
minion/renderers.py
bind
def bind(renderer, to): """ Bind a renderer to the given callable by constructing a new rendering view. """ @wraps(to) def view(request, **kwargs): try: returned = to(request, **kwargs) except Exception as error: view_error = getattr(renderer, "view_error", ...
python
def bind(renderer, to): """ Bind a renderer to the given callable by constructing a new rendering view. """ @wraps(to) def view(request, **kwargs): try: returned = to(request, **kwargs) except Exception as error: view_error = getattr(renderer, "view_error", ...
[ "def", "bind", "(", "renderer", ",", "to", ")", ":", "@", "wraps", "(", "to", ")", "def", "view", "(", "request", ",", "*", "*", "kwargs", ")", ":", "try", ":", "returned", "=", "to", "(", "request", ",", "*", "*", "kwargs", ")", "except", "Exc...
Bind a renderer to the given callable by constructing a new rendering view.
[ "Bind", "a", "renderer", "to", "the", "given", "callable", "by", "constructing", "a", "new", "rendering", "view", "." ]
518d06f9ffd38dcacc0de4d94e72d1f8452157a8
https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/minion/renderers.py#L61-L85
40,431
Formulka/django-fperms
fperms/__init__.py
get_perm_model
def get_perm_model(): """ Returns the Perm model that is active in this project. """ try: return django_apps.get_model(settings.PERM_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("PERM_MODEL must be of the form 'app_label.model_name'") except LookupErr...
python
def get_perm_model(): """ Returns the Perm model that is active in this project. """ try: return django_apps.get_model(settings.PERM_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("PERM_MODEL must be of the form 'app_label.model_name'") except LookupErr...
[ "def", "get_perm_model", "(", ")", ":", "try", ":", "return", "django_apps", ".", "get_model", "(", "settings", ".", "PERM_MODEL", ",", "require_ready", "=", "False", ")", "except", "ValueError", ":", "raise", "ImproperlyConfigured", "(", "\"PERM_MODEL must be of ...
Returns the Perm model that is active in this project.
[ "Returns", "the", "Perm", "model", "that", "is", "active", "in", "this", "project", "." ]
88b8fa3dd87075a56d8bfeb2b9993c578c22694e
https://github.com/Formulka/django-fperms/blob/88b8fa3dd87075a56d8bfeb2b9993c578c22694e/fperms/__init__.py#L9-L20
40,432
openstack/stacktach-winchester
winchester/config.py
ConfigManager._load_yaml_config
def _load_yaml_config(cls, config_data, filename="(unknown)"): """Load a yaml config file.""" try: config = yaml.safe_load(config_data) except yaml.YAMLError as err: if hasattr(err, 'problem_mark'): mark = err.problem_mark errmsg = ("Inval...
python
def _load_yaml_config(cls, config_data, filename="(unknown)"): """Load a yaml config file.""" try: config = yaml.safe_load(config_data) except yaml.YAMLError as err: if hasattr(err, 'problem_mark'): mark = err.problem_mark errmsg = ("Inval...
[ "def", "_load_yaml_config", "(", "cls", ",", "config_data", ",", "filename", "=", "\"(unknown)\"", ")", ":", "try", ":", "config", "=", "yaml", ".", "safe_load", "(", "config_data", ")", "except", "yaml", ".", "YAMLError", "as", "err", ":", "if", "hasattr"...
Load a yaml config file.
[ "Load", "a", "yaml", "config", "file", "." ]
54f3ffc4a8fd84b6fb29ad9b65adb018e8927956
https://github.com/openstack/stacktach-winchester/blob/54f3ffc4a8fd84b6fb29ad9b65adb018e8927956/winchester/config.py#L129-L150
40,433
dmaust/rounding
rounding/stochastic.py
sround
def sround(x, precision=0): """ Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round. """ sr = StochasticRound(precision=precision) return sr.round(x)
python
def sround(x, precision=0): """ Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round. """ sr = StochasticRound(precision=precision) return sr.round(x)
[ "def", "sround", "(", "x", ",", "precision", "=", "0", ")", ":", "sr", "=", "StochasticRound", "(", "precision", "=", "precision", ")", "return", "sr", ".", "round", "(", "x", ")" ]
Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round.
[ "Round", "a", "single", "number", "using", "default", "non", "-", "deterministic", "generator", "." ]
06731dff803c30c0741e3199888e7e5266ad99cc
https://github.com/dmaust/rounding/blob/06731dff803c30c0741e3199888e7e5266ad99cc/rounding/stochastic.py#L58-L66
40,434
pignacio/chorddb
chorddb/tab/parser.py
_parse_chord_line
def _parse_chord_line(line): ''' Parse a chord line into a `ChordLineData` object. ''' chords = [ TabChord(position=position, chord=chord) for chord, position in Chord.extract_chordpos(line) ] return ChordLineData(chords=chords)
python
def _parse_chord_line(line): ''' Parse a chord line into a `ChordLineData` object. ''' chords = [ TabChord(position=position, chord=chord) for chord, position in Chord.extract_chordpos(line) ] return ChordLineData(chords=chords)
[ "def", "_parse_chord_line", "(", "line", ")", ":", "chords", "=", "[", "TabChord", "(", "position", "=", "position", ",", "chord", "=", "chord", ")", "for", "chord", ",", "position", "in", "Chord", ".", "extract_chordpos", "(", "line", ")", "]", "return"...
Parse a chord line into a `ChordLineData` object.
[ "Parse", "a", "chord", "line", "into", "a", "ChordLineData", "object", "." ]
e386e1f9251a01810f41f794eefa73151adca630
https://github.com/pignacio/chorddb/blob/e386e1f9251a01810f41f794eefa73151adca630/chorddb/tab/parser.py#L16-L22
40,435
pignacio/chorddb
chorddb/tab/parser.py
_get_line_type
def _get_line_type(line): ''' Decide the line type in function of its contents ''' stripped = line.strip() if not stripped: return 'empty' remainder = re.sub(r"\s+", " ", re.sub(CHORD_RE, "", stripped)) if len(remainder) * 2 < len(re.sub(r"\s+", " ", stripped)): return 'chord' re...
python
def _get_line_type(line): ''' Decide the line type in function of its contents ''' stripped = line.strip() if not stripped: return 'empty' remainder = re.sub(r"\s+", " ", re.sub(CHORD_RE, "", stripped)) if len(remainder) * 2 < len(re.sub(r"\s+", " ", stripped)): return 'chord' re...
[ "def", "_get_line_type", "(", "line", ")", ":", "stripped", "=", "line", ".", "strip", "(", ")", "if", "not", "stripped", ":", "return", "'empty'", "remainder", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "\" \"", ",", "re", ".", "sub", "(", "CHORD...
Decide the line type in function of its contents
[ "Decide", "the", "line", "type", "in", "function", "of", "its", "contents" ]
e386e1f9251a01810f41f794eefa73151adca630
https://github.com/pignacio/chorddb/blob/e386e1f9251a01810f41f794eefa73151adca630/chorddb/tab/parser.py#L37-L45
40,436
pignacio/chorddb
chorddb/tab/parser.py
parse_line
def parse_line(line): ''' Parse a line into a `TabLine` object. ''' line = line.rstrip() line_type = _get_line_type(line) return TabLine( type=line_type, data=_DATA_PARSERS[line_type](line), original=line, )
python
def parse_line(line): ''' Parse a line into a `TabLine` object. ''' line = line.rstrip() line_type = _get_line_type(line) return TabLine( type=line_type, data=_DATA_PARSERS[line_type](line), original=line, )
[ "def", "parse_line", "(", "line", ")", ":", "line", "=", "line", ".", "rstrip", "(", ")", "line_type", "=", "_get_line_type", "(", "line", ")", "return", "TabLine", "(", "type", "=", "line_type", ",", "data", "=", "_DATA_PARSERS", "[", "line_type", "]", ...
Parse a line into a `TabLine` object.
[ "Parse", "a", "line", "into", "a", "TabLine", "object", "." ]
e386e1f9251a01810f41f794eefa73151adca630
https://github.com/pignacio/chorddb/blob/e386e1f9251a01810f41f794eefa73151adca630/chorddb/tab/parser.py#L48-L56
40,437
pignacio/chorddb
chorddb/tab/parser.py
parse_tablature
def parse_tablature(lines): ''' Parse a list of lines into a `Tablature`. ''' lines = [parse_line(l) for l in lines] return Tablature(lines=lines)
python
def parse_tablature(lines): ''' Parse a list of lines into a `Tablature`. ''' lines = [parse_line(l) for l in lines] return Tablature(lines=lines)
[ "def", "parse_tablature", "(", "lines", ")", ":", "lines", "=", "[", "parse_line", "(", "l", ")", "for", "l", "in", "lines", "]", "return", "Tablature", "(", "lines", "=", "lines", ")" ]
Parse a list of lines into a `Tablature`.
[ "Parse", "a", "list", "of", "lines", "into", "a", "Tablature", "." ]
e386e1f9251a01810f41f794eefa73151adca630
https://github.com/pignacio/chorddb/blob/e386e1f9251a01810f41f794eefa73151adca630/chorddb/tab/parser.py#L59-L62
40,438
a2liu/mr-clean
mr_clean/_utils/io.py
preview
def preview(df,preview_rows = 20):#,preview_max_cols = 0): """ Returns a preview of a dataframe, which contains both header rows and tail rows. """ if preview_rows < 4: preview_rows = 4 preview_rows = min(preview_rows,df.shape[0]) outer = math.floor(preview_rows / 4) return pd.concat...
python
def preview(df,preview_rows = 20):#,preview_max_cols = 0): """ Returns a preview of a dataframe, which contains both header rows and tail rows. """ if preview_rows < 4: preview_rows = 4 preview_rows = min(preview_rows,df.shape[0]) outer = math.floor(preview_rows / 4) return pd.concat...
[ "def", "preview", "(", "df", ",", "preview_rows", "=", "20", ")", ":", "#,preview_max_cols = 0):", "if", "preview_rows", "<", "4", ":", "preview_rows", "=", "4", "preview_rows", "=", "min", "(", "preview_rows", ",", "df", ".", "shape", "[", "0", "]", ")"...
Returns a preview of a dataframe, which contains both header rows and tail rows.
[ "Returns", "a", "preview", "of", "a", "dataframe", "which", "contains", "both", "header", "rows", "and", "tail", "rows", "." ]
0ee4ee5639f834dec4b59b94442fa84373f3c176
https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/_utils/io.py#L26-L36
40,439
a2liu/mr-clean
mr_clean/_utils/io.py
title_line
def title_line(text): """Returns a string that represents the text as a title blurb """ columns = shutil.get_terminal_size()[0] start = columns // 2 - len(text) // 2 output = '='*columns + '\n\n' + \ ' ' * start + str(text) + "\n\n" + \ '='*columns + '\n' return outpu...
python
def title_line(text): """Returns a string that represents the text as a title blurb """ columns = shutil.get_terminal_size()[0] start = columns // 2 - len(text) // 2 output = '='*columns + '\n\n' + \ ' ' * start + str(text) + "\n\n" + \ '='*columns + '\n' return outpu...
[ "def", "title_line", "(", "text", ")", ":", "columns", "=", "shutil", ".", "get_terminal_size", "(", ")", "[", "0", "]", "start", "=", "columns", "//", "2", "-", "len", "(", "text", ")", "//", "2", "output", "=", "'='", "*", "columns", "+", "'\\n\\...
Returns a string that represents the text as a title blurb
[ "Returns", "a", "string", "that", "represents", "the", "text", "as", "a", "title", "blurb" ]
0ee4ee5639f834dec4b59b94442fa84373f3c176
https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/_utils/io.py#L46-L55
40,440
dbuscher/pois
pois/__init__.py
RadiusGrid
def RadiusGrid(gridSize): """ Return a square grid with values of the distance from the centre of the grid to each gridpoint """ x,y=np.mgrid[0:gridSize,0:gridSize] x = x-(gridSize-1.0)/2.0 y = y-(gridSize-1.0)/2.0 return np.abs(x+1j*y)
python
def RadiusGrid(gridSize): """ Return a square grid with values of the distance from the centre of the grid to each gridpoint """ x,y=np.mgrid[0:gridSize,0:gridSize] x = x-(gridSize-1.0)/2.0 y = y-(gridSize-1.0)/2.0 return np.abs(x+1j*y)
[ "def", "RadiusGrid", "(", "gridSize", ")", ":", "x", ",", "y", "=", "np", ".", "mgrid", "[", "0", ":", "gridSize", ",", "0", ":", "gridSize", "]", "x", "=", "x", "-", "(", "gridSize", "-", "1.0", ")", "/", "2.0", "y", "=", "y", "-", "(", "g...
Return a square grid with values of the distance from the centre of the grid to each gridpoint
[ "Return", "a", "square", "grid", "with", "values", "of", "the", "distance", "from", "the", "centre", "of", "the", "grid", "to", "each", "gridpoint" ]
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L30-L38
40,441
dbuscher/pois
pois/__init__.py
CircularMaskGrid
def CircularMaskGrid(gridSize, diameter=None): """ Return a square grid with ones inside and zeros outside a given diameter circle """ if diameter is None: diameter=gridSize return np.less_equal(RadiusGrid(gridSize),diameter/2.0)
python
def CircularMaskGrid(gridSize, diameter=None): """ Return a square grid with ones inside and zeros outside a given diameter circle """ if diameter is None: diameter=gridSize return np.less_equal(RadiusGrid(gridSize),diameter/2.0)
[ "def", "CircularMaskGrid", "(", "gridSize", ",", "diameter", "=", "None", ")", ":", "if", "diameter", "is", "None", ":", "diameter", "=", "gridSize", "return", "np", ".", "less_equal", "(", "RadiusGrid", "(", "gridSize", ")", ",", "diameter", "/", "2.0", ...
Return a square grid with ones inside and zeros outside a given diameter circle
[ "Return", "a", "square", "grid", "with", "ones", "inside", "and", "zeros", "outside", "a", "given", "diameter", "circle" ]
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L41-L47
40,442
dbuscher/pois
pois/__init__.py
AdaptiveOpticsCorrect
def AdaptiveOpticsCorrect(pupils,diameter,maxRadial,numRemove=None): """ Correct a wavefront using Zernike rejection up to some maximal order. Can operate on multiple telescopes in parallel. Note that this version removes the piston mode as well """ gridSize=pupils.shape[-1] pupilsVector=np...
python
def AdaptiveOpticsCorrect(pupils,diameter,maxRadial,numRemove=None): """ Correct a wavefront using Zernike rejection up to some maximal order. Can operate on multiple telescopes in parallel. Note that this version removes the piston mode as well """ gridSize=pupils.shape[-1] pupilsVector=np...
[ "def", "AdaptiveOpticsCorrect", "(", "pupils", ",", "diameter", ",", "maxRadial", ",", "numRemove", "=", "None", ")", ":", "gridSize", "=", "pupils", ".", "shape", "[", "-", "1", "]", "pupilsVector", "=", "np", ".", "reshape", "(", "pupils", ",", "(", ...
Correct a wavefront using Zernike rejection up to some maximal order. Can operate on multiple telescopes in parallel. Note that this version removes the piston mode as well
[ "Correct", "a", "wavefront", "using", "Zernike", "rejection", "up", "to", "some", "maximal", "order", ".", "Can", "operate", "on", "multiple", "telescopes", "in", "parallel", ".", "Note", "that", "this", "version", "removes", "the", "piston", "mode", "as", "...
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L53-L69
40,443
dbuscher/pois
pois/__init__.py
FibreCouple
def FibreCouple(pupils,modeDiameter): """ Return the complex amplitudes coupled into a set of fibers """ gridSize=pupils.shape[-1] pupilsVector=np.reshape(pupils,(-1,gridSize**2)) mode=np.reshape(FibreMode(gridSize,modeDiameter),(gridSize**2,)) return np.inner(pupilsVector,mode)
python
def FibreCouple(pupils,modeDiameter): """ Return the complex amplitudes coupled into a set of fibers """ gridSize=pupils.shape[-1] pupilsVector=np.reshape(pupils,(-1,gridSize**2)) mode=np.reshape(FibreMode(gridSize,modeDiameter),(gridSize**2,)) return np.inner(pupilsVector,mode)
[ "def", "FibreCouple", "(", "pupils", ",", "modeDiameter", ")", ":", "gridSize", "=", "pupils", ".", "shape", "[", "-", "1", "]", "pupilsVector", "=", "np", ".", "reshape", "(", "pupils", ",", "(", "-", "1", ",", "gridSize", "**", "2", ")", ")", "mo...
Return the complex amplitudes coupled into a set of fibers
[ "Return", "the", "complex", "amplitudes", "coupled", "into", "a", "set", "of", "fibers" ]
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L81-L88
40,444
dbuscher/pois
pois/__init__.py
SingleModeCombine
def SingleModeCombine(pupils,modeDiameter=None): """ Return the instantaneous coherent fluxes and photometric fluxes for a multiway single-mode fibre combiner """ if modeDiameter is None: modeDiameter=0.9*pupils.shape[-1] amplitudes=FibreCouple(pupils,modeDiameter) cc=np.conj(amplitu...
python
def SingleModeCombine(pupils,modeDiameter=None): """ Return the instantaneous coherent fluxes and photometric fluxes for a multiway single-mode fibre combiner """ if modeDiameter is None: modeDiameter=0.9*pupils.shape[-1] amplitudes=FibreCouple(pupils,modeDiameter) cc=np.conj(amplitu...
[ "def", "SingleModeCombine", "(", "pupils", ",", "modeDiameter", "=", "None", ")", ":", "if", "modeDiameter", "is", "None", ":", "modeDiameter", "=", "0.9", "*", "pupils", ".", "shape", "[", "-", "1", "]", "amplitudes", "=", "FibreCouple", "(", "pupils", ...
Return the instantaneous coherent fluxes and photometric fluxes for a multiway single-mode fibre combiner
[ "Return", "the", "instantaneous", "coherent", "fluxes", "and", "photometric", "fluxes", "for", "a", "multiway", "single", "-", "mode", "fibre", "combiner" ]
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L90-L103
40,445
TimSC/python-oauth10a
oauth10a/__init__.py
to_unicode
def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, TEXT): if not isinstance(s, bytes): raise TypeError('You are required to pass either unicode or ' 'bytes he...
python
def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, TEXT): if not isinstance(s, bytes): raise TypeError('You are required to pass either unicode or ' 'bytes he...
[ "def", "to_unicode", "(", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "TEXT", ")", ":", "if", "not", "isinstance", "(", "s", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'You are required to pass either unicode or '", "'bytes here, not: %r ...
Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8.
[ "Convert", "to", "unicode", "raise", "exception", "with", "instructive", "error", "message", "if", "s", "is", "not", "unicode", "ascii", "or", "utf", "-", "8", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L95-L112
40,446
TimSC/python-oauth10a
oauth10a/__init__.py
Request.to_postdata
def to_postdata(self): """Serialize as post data for a POST request.""" items = [] for k, v in sorted(self.items()): # predictable for testing items.append((k.encode('utf-8'), to_utf8_optional_iterator(v))) # tell urlencode to deal with sequence values and map them correctl...
python
def to_postdata(self): """Serialize as post data for a POST request.""" items = [] for k, v in sorted(self.items()): # predictable for testing items.append((k.encode('utf-8'), to_utf8_optional_iterator(v))) # tell urlencode to deal with sequence values and map them correctl...
[ "def", "to_postdata", "(", "self", ")", ":", "items", "=", "[", "]", "for", "k", ",", "v", "in", "sorted", "(", "self", ".", "items", "(", ")", ")", ":", "# predictable for testing", "items", ".", "append", "(", "(", "k", ".", "encode", "(", "'utf-...
Serialize as post data for a POST request.
[ "Serialize", "as", "post", "data", "for", "a", "POST", "request", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L419-L428
40,447
TimSC/python-oauth10a
oauth10a/__init__.py
Server.fetch_request_token
def fetch_request_token(self, oauth_request): """Processes a request_token request and returns the request token on success. """ try: # Get the request token for authorization. token = self._get_token(oauth_request, 'request') except Error: # N...
python
def fetch_request_token(self, oauth_request): """Processes a request_token request and returns the request token on success. """ try: # Get the request token for authorization. token = self._get_token(oauth_request, 'request') except Error: # N...
[ "def", "fetch_request_token", "(", "self", ",", "oauth_request", ")", ":", "try", ":", "# Get the request token for authorization.", "token", "=", "self", ".", "_get_token", "(", "oauth_request", ",", "'request'", ")", "except", "Error", ":", "# No token required for ...
Processes a request_token request and returns the request token on success.
[ "Processes", "a", "request_token", "request", "and", "returns", "the", "request", "token", "on", "success", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L734-L752
40,448
TimSC/python-oauth10a
oauth10a/__init__.py
Server.fetch_access_token
def fetch_access_token(self, oauth_request): """Processes an access_token request and returns the access token on success. """ version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) try: verifier = self._get_verifier(oauth_requ...
python
def fetch_access_token(self, oauth_request): """Processes an access_token request and returns the access token on success. """ version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) try: verifier = self._get_verifier(oauth_requ...
[ "def", "fetch_access_token", "(", "self", ",", "oauth_request", ")", ":", "version", "=", "self", ".", "_get_version", "(", "oauth_request", ")", "consumer", "=", "self", ".", "_get_consumer", "(", "oauth_request", ")", "try", ":", "verifier", "=", "self", "...
Processes an access_token request and returns the access token on success.
[ "Processes", "an", "access_token", "request", "and", "returns", "the", "access", "token", "on", "success", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L754-L768
40,449
TimSC/python-oauth10a
oauth10a/__init__.py
Server._get_token
def _get_token(self, oauth_request, token_type='access'): """Try to find the token for the provided request token key.""" token_field = oauth_request.get_parameter('oauth_token') token = self.data_store.lookup_token(token_type, token_field) if not token: raise OAuthError('Inv...
python
def _get_token(self, oauth_request, token_type='access'): """Try to find the token for the provided request token key.""" token_field = oauth_request.get_parameter('oauth_token') token = self.data_store.lookup_token(token_type, token_field) if not token: raise OAuthError('Inv...
[ "def", "_get_token", "(", "self", ",", "oauth_request", ",", "token_type", "=", "'access'", ")", ":", "token_field", "=", "oauth_request", ".", "get_parameter", "(", "'oauth_token'", ")", "token", "=", "self", ".", "data_store", ".", "lookup_token", "(", "toke...
Try to find the token for the provided request token key.
[ "Try", "to", "find", "the", "token", "for", "the", "provided", "request", "token", "key", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L812-L818
40,450
jkitzes/macroeco
macroeco/models/_curves.py
mete_upscale_iterative_alt
def mete_upscale_iterative_alt(S, N, doublings): """ This function is used to upscale from the anchor area. Parameters ---------- S : int or float Number of species at anchor scale N : int or float Number of individuals at anchor scale doublings : int Number of doubl...
python
def mete_upscale_iterative_alt(S, N, doublings): """ This function is used to upscale from the anchor area. Parameters ---------- S : int or float Number of species at anchor scale N : int or float Number of individuals at anchor scale doublings : int Number of doubl...
[ "def", "mete_upscale_iterative_alt", "(", "S", ",", "N", ",", "doublings", ")", ":", "# Arrays to store N and S at all doublings", "n_arr", "=", "np", ".", "empty", "(", "doublings", "+", "1", ")", "s_arr", "=", "np", ".", "empty", "(", "doublings", "+", "1"...
This function is used to upscale from the anchor area. Parameters ---------- S : int or float Number of species at anchor scale N : int or float Number of individuals at anchor scale doublings : int Number of doublings of A. Result vector will be length doublings + 1. R...
[ "This", "function", "is", "used", "to", "upscale", "from", "the", "anchor", "area", "." ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_curves.py#L576-L647
40,451
jkitzes/macroeco
macroeco/models/_curves.py
curve.fit_lsq
def fit_lsq(self, x, y_obs, params_start=None): """ Fit curve by method of least squares. Parameters ---------- x : iterable Independent variable y_obs : iterable Dependent variable (values observed at x) params_start : iterable ...
python
def fit_lsq(self, x, y_obs, params_start=None): """ Fit curve by method of least squares. Parameters ---------- x : iterable Independent variable y_obs : iterable Dependent variable (values observed at x) params_start : iterable ...
[ "def", "fit_lsq", "(", "self", ",", "x", ",", "y_obs", ",", "params_start", "=", "None", ")", ":", "# Set up variables", "x", "=", "np", ".", "atleast_1d", "(", "x", ")", "y_obs", "=", "np", ".", "atleast_1d", "(", "y_obs", ")", "if", "not", "params_...
Fit curve by method of least squares. Parameters ---------- x : iterable Independent variable y_obs : iterable Dependent variable (values observed at x) params_start : iterable Optional start values for all parameters. Default 1. Retu...
[ "Fit", "curve", "by", "method", "of", "least", "squares", "." ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_curves.py#L61-L111
40,452
jkitzes/macroeco
macroeco/models/_curves.py
mete_sar_gen.fit_lsq
def fit_lsq(self, df): """ Parameterize generic SAR curve from empirical data set Parameters ---------- df : DataFrame Result data frame from empirical SAR analysis Notes ----- Simply returns S0 and N0 from empirical SAR output, which are two...
python
def fit_lsq(self, df): """ Parameterize generic SAR curve from empirical data set Parameters ---------- df : DataFrame Result data frame from empirical SAR analysis Notes ----- Simply returns S0 and N0 from empirical SAR output, which are two...
[ "def", "fit_lsq", "(", "self", ",", "df", ")", ":", "tdf", "=", "df", ".", "set_index", "(", "'div'", ")", "return", "tdf", ".", "ix", "[", "'1,1'", "]", "[", "'n_spp'", "]", ",", "tdf", ".", "ix", "[", "'1,1'", "]", "[", "'n_individs'", "]" ]
Parameterize generic SAR curve from empirical data set Parameters ---------- df : DataFrame Result data frame from empirical SAR analysis Notes ----- Simply returns S0 and N0 from empirical SAR output, which are two fixed parameters of METE SAR and E...
[ "Parameterize", "generic", "SAR", "curve", "from", "empirical", "data", "set" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_curves.py#L548-L567
40,453
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
after_insert
def after_insert(mapper, connection, target): """Update reply order cache and send record-after-update signal.""" record_after_update.send(CmtRECORDCOMMENT, recid=target.id_bibrec) from .api import get_reply_order_cache_data if target.in_reply_to_id_cmtRECORDCOMMENT > 0: parent = CmtRECORDCOMM...
python
def after_insert(mapper, connection, target): """Update reply order cache and send record-after-update signal.""" record_after_update.send(CmtRECORDCOMMENT, recid=target.id_bibrec) from .api import get_reply_order_cache_data if target.in_reply_to_id_cmtRECORDCOMMENT > 0: parent = CmtRECORDCOMM...
[ "def", "after_insert", "(", "mapper", ",", "connection", ",", "target", ")", ":", "record_after_update", ".", "send", "(", "CmtRECORDCOMMENT", ",", "recid", "=", "target", ".", "id_bibrec", ")", "from", ".", "api", "import", "get_reply_order_cache_data", "if", ...
Update reply order cache and send record-after-update signal.
[ "Update", "reply", "order", "cache", "and", "send", "record", "-", "after", "-", "update", "signal", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L109-L126
40,454
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
CmtRECORDCOMMENT.is_collapsed
def is_collapsed(self, id_user): """Return true if the comment is collapsed by user.""" return CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).count() > 0
python
def is_collapsed(self, id_user): """Return true if the comment is collapsed by user.""" return CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).count() > 0
[ "def", "is_collapsed", "(", "self", ",", "id_user", ")", ":", "return", "CmtCOLLAPSED", ".", "query", ".", "filter", "(", "db", ".", "and_", "(", "CmtCOLLAPSED", ".", "id_bibrec", "==", "self", ".", "id_bibrec", ",", "CmtCOLLAPSED", ".", "id_cmtRECORDCOMMENT...
Return true if the comment is collapsed by user.
[ "Return", "true", "if", "the", "comment", "is", "collapsed", "by", "user", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L76-L81
40,455
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
CmtRECORDCOMMENT.collapse
def collapse(self, id_user): """Collapse comment beloging to user.""" c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id, id_user=id_user) db.session.add(c) db.session.commit()
python
def collapse(self, id_user): """Collapse comment beloging to user.""" c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id, id_user=id_user) db.session.add(c) db.session.commit()
[ "def", "collapse", "(", "self", ",", "id_user", ")", ":", "c", "=", "CmtCOLLAPSED", "(", "id_bibrec", "=", "self", ".", "id_bibrec", ",", "id_cmtRECORDCOMMENT", "=", "self", ".", "id", ",", "id_user", "=", "id_user", ")", "db", ".", "session", ".", "ad...
Collapse comment beloging to user.
[ "Collapse", "comment", "beloging", "to", "user", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L84-L89
40,456
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
CmtRECORDCOMMENT.expand
def expand(self, id_user): """Expand comment beloging to user.""" CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).delete(synchronize_session=False)
python
def expand(self, id_user): """Expand comment beloging to user.""" CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).delete(synchronize_session=False)
[ "def", "expand", "(", "self", ",", "id_user", ")", ":", "CmtCOLLAPSED", ".", "query", ".", "filter", "(", "db", ".", "and_", "(", "CmtCOLLAPSED", ".", "id_bibrec", "==", "self", ".", "id_bibrec", ",", "CmtCOLLAPSED", ".", "id_cmtRECORDCOMMENT", "==", "self...
Expand comment beloging to user.
[ "Expand", "comment", "beloging", "to", "user", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L91-L96
40,457
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
CmtRECORDCOMMENT.count
def count(cls, *criteria, **filters): """Count how many comments.""" return cls.query.filter(*criteria).filter_by(**filters).count()
python
def count(cls, *criteria, **filters): """Count how many comments.""" return cls.query.filter(*criteria).filter_by(**filters).count()
[ "def", "count", "(", "cls", ",", "*", "criteria", ",", "*", "*", "filters", ")", ":", "return", "cls", ".", "query", ".", "filter", "(", "*", "criteria", ")", ".", "filter_by", "(", "*", "*", "filters", ")", ".", "count", "(", ")" ]
Count how many comments.
[ "Count", "how", "many", "comments", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L103-L105
40,458
aumayr/beancount-pygments-lexer
beancount_pygments_lexer/util/version.py
get_version
def get_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version[4] > 0: # 0.2.1-alpha.1 return "%s.%s.%s-%s.%s" % (version[0], version[1], version[2], version[3], version[4]) elif v...
python
def get_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version[4] > 0: # 0.2.1-alpha.1 return "%s.%s.%s-%s.%s" % (version[0], version[1], version[2], version[3], version[4]) elif v...
[ "def", "get_version", "(", "version", "=", "None", ")", ":", "if", "version", "[", "4", "]", ">", "0", ":", "# 0.2.1-alpha.1", "return", "\"%s.%s.%s-%s.%s\"", "%", "(", "version", "[", "0", "]", ",", "version", "[", "1", "]", ",", "version", "[", "2"...
Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided.
[ "Returns", "a", "tuple", "of", "the", "django", "version", ".", "If", "version", "argument", "is", "non", "-", "empty", "then", "checks", "for", "correctness", "of", "the", "tuple", "provided", "." ]
49ab7754a41fe850ebe88cb879ec0a78e1e06ef0
https://github.com/aumayr/beancount-pygments-lexer/blob/49ab7754a41fe850ebe88cb879ec0a78e1e06ef0/beancount_pygments_lexer/util/version.py#L1-L13
40,459
mixer/beam-interactive-python
beam_interactive/connection.py
Connection._push_packet
def _push_packet(self, packet): """ Appends a packet to the internal read queue, or notifies a waiting listener that a packet just came in. """ self._read_queue.append((decode(packet), packet)) if self._read_waiter is not None: w, self._read_waiter = self._re...
python
def _push_packet(self, packet): """ Appends a packet to the internal read queue, or notifies a waiting listener that a packet just came in. """ self._read_queue.append((decode(packet), packet)) if self._read_waiter is not None: w, self._read_waiter = self._re...
[ "def", "_push_packet", "(", "self", ",", "packet", ")", ":", "self", ".", "_read_queue", ".", "append", "(", "(", "decode", "(", "packet", ")", ",", "packet", ")", ")", "if", "self", ".", "_read_waiter", "is", "not", "None", ":", "w", ",", "self", ...
Appends a packet to the internal read queue, or notifies a waiting listener that a packet just came in.
[ "Appends", "a", "packet", "to", "the", "internal", "read", "queue", "or", "notifies", "a", "waiting", "listener", "that", "a", "packet", "just", "came", "in", "." ]
e035bc45515dea9315b77648a24b5ae8685aa5cf
https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/connection.py#L40-L49
40,460
mixer/beam-interactive-python
beam_interactive/connection.py
Connection._read_data
def _read_data(self): """ Reads data from the connection and adds it to _push_packet, until the connection is closed or the task in cancelled. """ while True: try: data = yield from self._socket.recv() except asyncio.CancelledError: ...
python
def _read_data(self): """ Reads data from the connection and adds it to _push_packet, until the connection is closed or the task in cancelled. """ while True: try: data = yield from self._socket.recv() except asyncio.CancelledError: ...
[ "def", "_read_data", "(", "self", ")", ":", "while", "True", ":", "try", ":", "data", "=", "yield", "from", "self", ".", "_socket", ".", "recv", "(", ")", "except", "asyncio", ".", "CancelledError", ":", "break", "except", "ConnectionClosed", ":", "break...
Reads data from the connection and adds it to _push_packet, until the connection is closed or the task in cancelled.
[ "Reads", "data", "from", "the", "connection", "and", "adds", "it", "to", "_push_packet", "until", "the", "connection", "is", "closed", "or", "the", "task", "in", "cancelled", "." ]
e035bc45515dea9315b77648a24b5ae8685aa5cf
https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/connection.py#L52-L67
40,461
mixer/beam-interactive-python
beam_interactive/connection.py
Connection.wait_message
def wait_message(self): """ Waits until a connection is available on the wire, or until the connection is in a state that it can't accept messages. It returns True if a message is available, False otherwise. """ if self._state != states['open']: return False ...
python
def wait_message(self): """ Waits until a connection is available on the wire, or until the connection is in a state that it can't accept messages. It returns True if a message is available, False otherwise. """ if self._state != states['open']: return False ...
[ "def", "wait_message", "(", "self", ")", ":", "if", "self", ".", "_state", "!=", "states", "[", "'open'", "]", ":", "return", "False", "if", "len", "(", "self", ".", "_read_queue", ")", ">", "0", ":", "return", "True", "assert", "self", ".", "_read_w...
Waits until a connection is available on the wire, or until the connection is in a state that it can't accept messages. It returns True if a message is available, False otherwise.
[ "Waits", "until", "a", "connection", "is", "available", "on", "the", "wire", "or", "until", "the", "connection", "is", "in", "a", "state", "that", "it", "can", "t", "accept", "messages", ".", "It", "returns", "True", "if", "a", "message", "is", "availabl...
e035bc45515dea9315b77648a24b5ae8685aa5cf
https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/connection.py#L70-L86
40,462
QualiSystems/CloudShell-Traffic
cloudshell/traffic/tg_helper.py
get_reservation_ports
def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'): """ Get all Generic Traffic Generator Port in reservation. :return: list of all Generic Traffic Generator Port resource objects in reservation """ reservation_ports = [] reservation = session.GetReserv...
python
def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'): """ Get all Generic Traffic Generator Port in reservation. :return: list of all Generic Traffic Generator Port resource objects in reservation """ reservation_ports = [] reservation = session.GetReserv...
[ "def", "get_reservation_ports", "(", "session", ",", "reservation_id", ",", "model_name", "=", "'Generic Traffic Generator Port'", ")", ":", "reservation_ports", "=", "[", "]", "reservation", "=", "session", ".", "GetReservationDetails", "(", "reservation_id", ")", "....
Get all Generic Traffic Generator Port in reservation. :return: list of all Generic Traffic Generator Port resource objects in reservation
[ "Get", "all", "Generic", "Traffic", "Generator", "Port", "in", "reservation", "." ]
4579d42e359fa9d5736dc4ceb8d86547f0e7120d
https://github.com/QualiSystems/CloudShell-Traffic/blob/4579d42e359fa9d5736dc4ceb8d86547f0e7120d/cloudshell/traffic/tg_helper.py#L24-L35
40,463
QualiSystems/CloudShell-Traffic
cloudshell/traffic/tg_helper.py
get_reservation_resources
def get_reservation_resources(session, reservation_id, *models): """ Get all resources of given models in reservation. :param session: CloudShell session :type session: cloudshell.api.cloudshell_api.CloudShellAPISession :param reservation_id: active reservation ID :param models: list of requested m...
python
def get_reservation_resources(session, reservation_id, *models): """ Get all resources of given models in reservation. :param session: CloudShell session :type session: cloudshell.api.cloudshell_api.CloudShellAPISession :param reservation_id: active reservation ID :param models: list of requested m...
[ "def", "get_reservation_resources", "(", "session", ",", "reservation_id", ",", "*", "models", ")", ":", "models_resources", "=", "[", "]", "reservation", "=", "session", ".", "GetReservationDetails", "(", "reservation_id", ")", ".", "ReservationDescription", "for",...
Get all resources of given models in reservation. :param session: CloudShell session :type session: cloudshell.api.cloudshell_api.CloudShellAPISession :param reservation_id: active reservation ID :param models: list of requested models :return: list of all resources of models in reservation
[ "Get", "all", "resources", "of", "given", "models", "in", "reservation", "." ]
4579d42e359fa9d5736dc4ceb8d86547f0e7120d
https://github.com/QualiSystems/CloudShell-Traffic/blob/4579d42e359fa9d5736dc4ceb8d86547f0e7120d/cloudshell/traffic/tg_helper.py#L38-L53
40,464
rycus86/docker_helper
docker_helper/__init__.py
get_current_container_id
def get_current_container_id(read_from='/proc/self/cgroup'): """ Get the ID of the container the application is currently running in, otherwise return `None` if not running in a container. This is a best-effort guess, based on cgroups. :param read_from: the cgroups file to read from (default: `/pr...
python
def get_current_container_id(read_from='/proc/self/cgroup'): """ Get the ID of the container the application is currently running in, otherwise return `None` if not running in a container. This is a best-effort guess, based on cgroups. :param read_from: the cgroups file to read from (default: `/pr...
[ "def", "get_current_container_id", "(", "read_from", "=", "'/proc/self/cgroup'", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "read_from", ")", ":", "return", "with", "open", "(", "read_from", ",", "'r'", ")", "as", "cgroup", ":", "for", ...
Get the ID of the container the application is currently running in, otherwise return `None` if not running in a container. This is a best-effort guess, based on cgroups. :param read_from: the cgroups file to read from (default: `/proc/self/cgroup`)
[ "Get", "the", "ID", "of", "the", "container", "the", "application", "is", "currently", "running", "in", "otherwise", "return", "None", "if", "not", "running", "in", "a", "container", "." ]
8198560052fe61ceeb0616974097046acba3940f
https://github.com/rycus86/docker_helper/blob/8198560052fe61ceeb0616974097046acba3940f/docker_helper/__init__.py#L5-L21
40,465
rycus86/docker_helper
docker_helper/__init__.py
read_configuration
def read_configuration(key, path=None, default=None, single_config=False, fallback_to_env=True): """ Read configuration from a file, Docker config or secret or from the environment variables. :param key: the configuration key :param path: the path of the configuration file (regular file or Docker confi...
python
def read_configuration(key, path=None, default=None, single_config=False, fallback_to_env=True): """ Read configuration from a file, Docker config or secret or from the environment variables. :param key: the configuration key :param path: the path of the configuration file (regular file or Docker confi...
[ "def", "read_configuration", "(", "key", ",", "path", "=", "None", ",", "default", "=", "None", ",", "single_config", "=", "False", ",", "fallback_to_env", "=", "True", ")", ":", "if", "path", "and", "os", ".", "path", ".", "exists", "(", "path", ")", ...
Read configuration from a file, Docker config or secret or from the environment variables. :param key: the configuration key :param path: the path of the configuration file (regular file or Docker config or secret) :param default: the default value when not found elsewhere (default: `None`) :param sing...
[ "Read", "configuration", "from", "a", "file", "Docker", "config", "or", "secret", "or", "from", "the", "environment", "variables", "." ]
8198560052fe61ceeb0616974097046acba3940f
https://github.com/rycus86/docker_helper/blob/8198560052fe61ceeb0616974097046acba3940f/docker_helper/__init__.py#L24-L50
40,466
dmwilcox/vcard-tools
vcardtools/vcf_splitter.py
CleanString
def CleanString(s): """Cleans up string. Doesn't catch everything, appears to sometimes allow double underscores to occur as a result of replacements. """ punc = (' ', '-', '\'', '.', '&amp;', '&', '+', '@') pieces = [] for part in s.split(): part = part.strip() for p in pun...
python
def CleanString(s): """Cleans up string. Doesn't catch everything, appears to sometimes allow double underscores to occur as a result of replacements. """ punc = (' ', '-', '\'', '.', '&amp;', '&', '+', '@') pieces = [] for part in s.split(): part = part.strip() for p in pun...
[ "def", "CleanString", "(", "s", ")", ":", "punc", "=", "(", "' '", ",", "'-'", ",", "'\\''", ",", "'.'", ",", "'&amp;'", ",", "'&'", ",", "'+'", ",", "'@'", ")", "pieces", "=", "[", "]", "for", "part", "in", "s", ".", "split", "(", ")", ":", ...
Cleans up string. Doesn't catch everything, appears to sometimes allow double underscores to occur as a result of replacements.
[ "Cleans", "up", "string", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_splitter.py#L76-L91
40,467
dmwilcox/vcard-tools
vcardtools/vcf_splitter.py
DedupVcardFilenames
def DedupVcardFilenames(vcard_dict): """Make sure every vCard in the dictionary has a unique filename.""" remove_keys = [] add_pairs = [] for k, v in vcard_dict.items(): if not len(v) > 1: continue for idx, vcard in enumerate(v): fname, ext = os.path.splitext(k) ...
python
def DedupVcardFilenames(vcard_dict): """Make sure every vCard in the dictionary has a unique filename.""" remove_keys = [] add_pairs = [] for k, v in vcard_dict.items(): if not len(v) > 1: continue for idx, vcard in enumerate(v): fname, ext = os.path.splitext(k) ...
[ "def", "DedupVcardFilenames", "(", "vcard_dict", ")", ":", "remove_keys", "=", "[", "]", "add_pairs", "=", "[", "]", "for", "k", ",", "v", "in", "vcard_dict", ".", "items", "(", ")", ":", "if", "not", "len", "(", "v", ")", ">", "1", ":", "continue"...
Make sure every vCard in the dictionary has a unique filename.
[ "Make", "sure", "every", "vCard", "in", "the", "dictionary", "has", "a", "unique", "filename", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_splitter.py#L114-L135
40,468
dmwilcox/vcard-tools
vcardtools/vcf_splitter.py
WriteVcard
def WriteVcard(filename, vcard, fopen=codecs.open): """Writes a vCard into the given filename.""" if os.access(filename, os.F_OK): logger.warning('File exists at "{}", skipping.'.format(filename)) return False try: with fopen(filename, 'w', encoding='utf-8') as f: logger....
python
def WriteVcard(filename, vcard, fopen=codecs.open): """Writes a vCard into the given filename.""" if os.access(filename, os.F_OK): logger.warning('File exists at "{}", skipping.'.format(filename)) return False try: with fopen(filename, 'w', encoding='utf-8') as f: logger....
[ "def", "WriteVcard", "(", "filename", ",", "vcard", ",", "fopen", "=", "codecs", ".", "open", ")", ":", "if", "os", ".", "access", "(", "filename", ",", "os", ".", "F_OK", ")", ":", "logger", ".", "warning", "(", "'File exists at \"{}\", skipping.'", "."...
Writes a vCard into the given filename.
[ "Writes", "a", "vCard", "into", "the", "given", "filename", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_splitter.py#L138-L150
40,469
robinagist/ezo
ezo/core/lib.py
EZO.dial
def dial(self, target): ''' connects to a node :param url: string (optional) - resource in which to connect. if not provided, will use default for the stage :returns: provider, error ''' if not target: return None, "target network must be specified w...
python
def dial(self, target): ''' connects to a node :param url: string (optional) - resource in which to connect. if not provided, will use default for the stage :returns: provider, error ''' if not target: return None, "target network must be specified w...
[ "def", "dial", "(", "self", ",", "target", ")", ":", "if", "not", "target", ":", "return", "None", ",", "\"target network must be specified with -t or --target\"", "url", "=", "get_url", "(", "self", ".", "config", ",", "target", ")", "try", ":", "if", "url"...
connects to a node :param url: string (optional) - resource in which to connect. if not provided, will use default for the stage :returns: provider, error
[ "connects", "to", "a", "node" ]
fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986
https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/lib.py#L41-L70
40,470
robinagist/ezo
ezo/core/lib.py
Contract.load
def load(filepath): ''' loads a contract file :param filepath: (string) - contract filename :return: source, err ''' try: with open(filepath, "r") as fh: source = fh.read() except Exception as e: return None, e ret...
python
def load(filepath): ''' loads a contract file :param filepath: (string) - contract filename :return: source, err ''' try: with open(filepath, "r") as fh: source = fh.read() except Exception as e: return None, e ret...
[ "def", "load", "(", "filepath", ")", ":", "try", ":", "with", "open", "(", "filepath", ",", "\"r\"", ")", "as", "fh", ":", "source", "=", "fh", ".", "read", "(", ")", "except", "Exception", "as", "e", ":", "return", "None", ",", "e", "return", "s...
loads a contract file :param filepath: (string) - contract filename :return: source, err
[ "loads", "a", "contract", "file" ]
fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986
https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/lib.py#L586-L599
40,471
robinagist/ezo
ezo/core/lib.py
Contract.compile
def compile(source, ezo): ''' compiles the source code :param source: (string) - contract source code :param ezo: - ezo reference for Contract object creation :return: (list) compiled source ''' try: compiled = compile_source(source) compi...
python
def compile(source, ezo): ''' compiles the source code :param source: (string) - contract source code :param ezo: - ezo reference for Contract object creation :return: (list) compiled source ''' try: compiled = compile_source(source) compi...
[ "def", "compile", "(", "source", ",", "ezo", ")", ":", "try", ":", "compiled", "=", "compile_source", "(", "source", ")", "compiled_list", "=", "[", "]", "for", "name", "in", "compiled", ":", "c", "=", "Contract", "(", "name", ",", "ezo", ")", "inter...
compiles the source code :param source: (string) - contract source code :param ezo: - ezo reference for Contract object creation :return: (list) compiled source
[ "compiles", "the", "source", "code" ]
fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986
https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/lib.py#L602-L622
40,472
robinagist/ezo
ezo/core/lib.py
Contract.get_address
def get_address(name, hash, db, target=None): ''' fetches the contract address of deployment :param hash: the contract file hash :return: (string) address of the contract error, if any ''' key = DB.pkey([EZO.DEPLOYED, name, target, hash]) d, er...
python
def get_address(name, hash, db, target=None): ''' fetches the contract address of deployment :param hash: the contract file hash :return: (string) address of the contract error, if any ''' key = DB.pkey([EZO.DEPLOYED, name, target, hash]) d, er...
[ "def", "get_address", "(", "name", ",", "hash", ",", "db", ",", "target", "=", "None", ")", ":", "key", "=", "DB", ".", "pkey", "(", "[", "EZO", ".", "DEPLOYED", ",", "name", ",", "target", ",", "hash", "]", ")", "d", ",", "err", "=", "db", "...
fetches the contract address of deployment :param hash: the contract file hash :return: (string) address of the contract error, if any
[ "fetches", "the", "contract", "address", "of", "deployment" ]
fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986
https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/lib.py#L625-L641
40,473
robinagist/ezo
ezo/core/lib.py
Catalog.put
def put(contract_name, abi): ''' save the contract's ABI :param contract_name: string - name of the contract :param abi: the contract's abi JSON file :return: None, None if saved okay None, error is an error ''' if not Catalog.path: ...
python
def put(contract_name, abi): ''' save the contract's ABI :param contract_name: string - name of the contract :param abi: the contract's abi JSON file :return: None, None if saved okay None, error is an error ''' if not Catalog.path: ...
[ "def", "put", "(", "contract_name", ",", "abi", ")", ":", "if", "not", "Catalog", ".", "path", ":", "return", "None", ",", "\"path to catalog must be set before saving to it\"", "if", "not", "contract_name", ":", "return", "None", ",", "\"contract name must be provi...
save the contract's ABI :param contract_name: string - name of the contract :param abi: the contract's abi JSON file :return: None, None if saved okay None, error is an error
[ "save", "the", "contract", "s", "ABI" ]
fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986
https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/lib.py#L658-L682
40,474
inveniosoftware-attic/invenio-utils
invenio_utils/datacite.py
DataciteMetadata.get_creators
def get_creators(self, attribute='creatorName'): """Get DataCite creators.""" if 'creators' in self.xml: if isinstance(self.xml['creators']['creator'], list): return [c[attribute] for c in self.xml['creators']['creator']] else: return self.xml['cre...
python
def get_creators(self, attribute='creatorName'): """Get DataCite creators.""" if 'creators' in self.xml: if isinstance(self.xml['creators']['creator'], list): return [c[attribute] for c in self.xml['creators']['creator']] else: return self.xml['cre...
[ "def", "get_creators", "(", "self", ",", "attribute", "=", "'creatorName'", ")", ":", "if", "'creators'", "in", "self", ".", "xml", ":", "if", "isinstance", "(", "self", ".", "xml", "[", "'creators'", "]", "[", "'creator'", "]", ",", "list", ")", ":", ...
Get DataCite creators.
[ "Get", "DataCite", "creators", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/datacite.py#L58-L66
40,475
inveniosoftware-attic/invenio-utils
invenio_utils/datacite.py
DataciteMetadata.get_dates
def get_dates(self): """Get DataCite dates.""" if 'dates' in self.xml: if isinstance(self.xml['dates']['date'], dict): return self.xml['dates']['date'].values()[0] return self.xml['dates']['date'] return None
python
def get_dates(self): """Get DataCite dates.""" if 'dates' in self.xml: if isinstance(self.xml['dates']['date'], dict): return self.xml['dates']['date'].values()[0] return self.xml['dates']['date'] return None
[ "def", "get_dates", "(", "self", ")", ":", "if", "'dates'", "in", "self", ".", "xml", ":", "if", "isinstance", "(", "self", ".", "xml", "[", "'dates'", "]", "[", "'date'", "]", ",", "dict", ")", ":", "return", "self", ".", "xml", "[", "'dates'", ...
Get DataCite dates.
[ "Get", "DataCite", "dates", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/datacite.py#L80-L86
40,476
inveniosoftware-attic/invenio-utils
invenio_utils/datacite.py
DataciteMetadata.get_description
def get_description(self, description_type='Abstract'): """Get DataCite description.""" if 'descriptions' in self.xml: if isinstance(self.xml['descriptions']['description'], list): for description in self.xml['descriptions']['description']: if description_...
python
def get_description(self, description_type='Abstract'): """Get DataCite description.""" if 'descriptions' in self.xml: if isinstance(self.xml['descriptions']['description'], list): for description in self.xml['descriptions']['description']: if description_...
[ "def", "get_description", "(", "self", ",", "description_type", "=", "'Abstract'", ")", ":", "if", "'descriptions'", "in", "self", ".", "xml", ":", "if", "isinstance", "(", "self", ".", "xml", "[", "'descriptions'", "]", "[", "'description'", "]", ",", "li...
Get DataCite description.
[ "Get", "DataCite", "description", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/datacite.py#L104-L119
40,477
CodyKochmann/generators
generators/itemgetter.py
itemgetter
def itemgetter(iterable, indexes): ''' same functionality as operator.itemgetter except, this one supports both positive and negative indexing of generators as well ''' indexes = indexes if isinstance(indexes, tuple) else tuple(indexes) assert all(isinstance(i, int) for i in indexes), 'indexes needs...
python
def itemgetter(iterable, indexes): ''' same functionality as operator.itemgetter except, this one supports both positive and negative indexing of generators as well ''' indexes = indexes if isinstance(indexes, tuple) else tuple(indexes) assert all(isinstance(i, int) for i in indexes), 'indexes needs...
[ "def", "itemgetter", "(", "iterable", ",", "indexes", ")", ":", "indexes", "=", "indexes", "if", "isinstance", "(", "indexes", ",", "tuple", ")", "else", "tuple", "(", "indexes", ")", "assert", "all", "(", "isinstance", "(", "i", ",", "int", ")", "for"...
same functionality as operator.itemgetter except, this one supports both positive and negative indexing of generators as well
[ "same", "functionality", "as", "operator", ".", "itemgetter", "except", "this", "one", "supports", "both", "positive", "and", "negative", "indexing", "of", "generators", "as", "well" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/itemgetter.py#L6-L25
40,478
mypebble/django-feature-flipper
feature_flipper/templatetags/feature_flipper.py
FlipperNode.render
def render(self, context): """Handle the actual rendering. """ user = self._get_value(self.user_key, context) feature = self._get_value(self.feature, context) if feature is None: return '' allowed = show_feature(user, feature) return self.nodelist.re...
python
def render(self, context): """Handle the actual rendering. """ user = self._get_value(self.user_key, context) feature = self._get_value(self.feature, context) if feature is None: return '' allowed = show_feature(user, feature) return self.nodelist.re...
[ "def", "render", "(", "self", ",", "context", ")", ":", "user", "=", "self", ".", "_get_value", "(", "self", ".", "user_key", ",", "context", ")", "feature", "=", "self", ".", "_get_value", "(", "self", ".", "feature", ",", "context", ")", "if", "fea...
Handle the actual rendering.
[ "Handle", "the", "actual", "rendering", "." ]
53ff52296955f2ff8b5b6ae4ea426b3f0665960e
https://github.com/mypebble/django-feature-flipper/blob/53ff52296955f2ff8b5b6ae4ea426b3f0665960e/feature_flipper/templatetags/feature_flipper.py#L41-L51
40,479
mypebble/django-feature-flipper
feature_flipper/templatetags/feature_flipper.py
FlipperNode._get_value
def _get_value(self, key, context): """Works out whether key is a value or if it's a variable referencing a value in context and returns the correct value. """ string_quotes = ('"', "'") if key[0] in string_quotes and key[-1] in string_quotes: return key[1:-1] ...
python
def _get_value(self, key, context): """Works out whether key is a value or if it's a variable referencing a value in context and returns the correct value. """ string_quotes = ('"', "'") if key[0] in string_quotes and key[-1] in string_quotes: return key[1:-1] ...
[ "def", "_get_value", "(", "self", ",", "key", ",", "context", ")", ":", "string_quotes", "=", "(", "'\"'", ",", "\"'\"", ")", "if", "key", "[", "0", "]", "in", "string_quotes", "and", "key", "[", "-", "1", "]", "in", "string_quotes", ":", "return", ...
Works out whether key is a value or if it's a variable referencing a value in context and returns the correct value.
[ "Works", "out", "whether", "key", "is", "a", "value", "or", "if", "it", "s", "a", "variable", "referencing", "a", "value", "in", "context", "and", "returns", "the", "correct", "value", "." ]
53ff52296955f2ff8b5b6ae4ea426b3f0665960e
https://github.com/mypebble/django-feature-flipper/blob/53ff52296955f2ff8b5b6ae4ea426b3f0665960e/feature_flipper/templatetags/feature_flipper.py#L53-L63
40,480
klen/muffin-oauth
muffin_oauth.py
Plugin.client
def client(self, client_name, **params): """Initialize OAuth client from registry.""" if client_name not in self.cfg.clients: raise OAuthException('Unconfigured client: %s' % client_name) if client_name not in ClientRegistry.clients: raise OAuthException('Unsupported ser...
python
def client(self, client_name, **params): """Initialize OAuth client from registry.""" if client_name not in self.cfg.clients: raise OAuthException('Unconfigured client: %s' % client_name) if client_name not in ClientRegistry.clients: raise OAuthException('Unsupported ser...
[ "def", "client", "(", "self", ",", "client_name", ",", "*", "*", "params", ")", ":", "if", "client_name", "not", "in", "self", ".", "cfg", ".", "clients", ":", "raise", "OAuthException", "(", "'Unconfigured client: %s'", "%", "client_name", ")", "if", "cli...
Initialize OAuth client from registry.
[ "Initialize", "OAuth", "client", "from", "registry", "." ]
2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6
https://github.com/klen/muffin-oauth/blob/2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6/muffin_oauth.py#L40-L49
40,481
klen/muffin-oauth
muffin_oauth.py
Plugin.login
async def login(self, client_name, request, redirect_uri=None, **params): """Process login with OAuth. :param client_name: A name one of configured clients :param request: Web request :param redirect_uri: An URI for authorization redirect """ client = self.client(client_...
python
async def login(self, client_name, request, redirect_uri=None, **params): """Process login with OAuth. :param client_name: A name one of configured clients :param request: Web request :param redirect_uri: An URI for authorization redirect """ client = self.client(client_...
[ "async", "def", "login", "(", "self", ",", "client_name", ",", "request", ",", "redirect_uri", "=", "None", ",", "*", "*", "params", ")", ":", "client", "=", "self", ".", "client", "(", "client_name", ",", "logger", "=", "self", ".", "app", ".", "log...
Process login with OAuth. :param client_name: A name one of configured clients :param request: Web request :param redirect_uri: An URI for authorization redirect
[ "Process", "login", "with", "OAuth", "." ]
2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6
https://github.com/klen/muffin-oauth/blob/2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6/muffin_oauth.py#L51-L110
40,482
klen/muffin-oauth
muffin_oauth.py
Plugin.refresh
def refresh(self, client_name, refresh_token, **params): """Get refresh token. :param client_name: A name one of configured clients :param redirect_uri: An URI for authorization redirect :returns: a coroutine """ client = self.client(client_name, logger=self.app.logger) ...
python
def refresh(self, client_name, refresh_token, **params): """Get refresh token. :param client_name: A name one of configured clients :param redirect_uri: An URI for authorization redirect :returns: a coroutine """ client = self.client(client_name, logger=self.app.logger) ...
[ "def", "refresh", "(", "self", ",", "client_name", ",", "refresh_token", ",", "*", "*", "params", ")", ":", "client", "=", "self", ".", "client", "(", "client_name", ",", "logger", "=", "self", ".", "app", ".", "logger", ")", "return", "client", ".", ...
Get refresh token. :param client_name: A name one of configured clients :param redirect_uri: An URI for authorization redirect :returns: a coroutine
[ "Get", "refresh", "token", "." ]
2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6
https://github.com/klen/muffin-oauth/blob/2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6/muffin_oauth.py#L112-L120
40,483
CodyKochmann/generators
generators/chain.py
chain
def chain(*args): """itertools.chain, just better""" has_iter = partial(hasattr, name='__iter__') # check if a single iterable is being passed for # the case that it's a generator of generators if len(args) == 1 and hasattr(args[0], '__iter__'): args = args[0] for arg in args: #...
python
def chain(*args): """itertools.chain, just better""" has_iter = partial(hasattr, name='__iter__') # check if a single iterable is being passed for # the case that it's a generator of generators if len(args) == 1 and hasattr(args[0], '__iter__'): args = args[0] for arg in args: #...
[ "def", "chain", "(", "*", "args", ")", ":", "has_iter", "=", "partial", "(", "hasattr", ",", "name", "=", "'__iter__'", ")", "# check if a single iterable is being passed for", "# the case that it's a generator of generators", "if", "len", "(", "args", ")", "==", "1...
itertools.chain, just better
[ "itertools", ".", "chain", "just", "better" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/chain.py#L11-L28
40,484
claymcleod/celcius
lib/celcius/utils/cron_utils.py
get_all_celcius_commands
def get_all_celcius_commands(): """Query cron for all celcius commands""" p = subprocess.Popen(["crontab", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return [x for x in out.split('\n') if 'CJOBID' in x]
python
def get_all_celcius_commands(): """Query cron for all celcius commands""" p = subprocess.Popen(["crontab", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return [x for x in out.split('\n') if 'CJOBID' in x]
[ "def", "get_all_celcius_commands", "(", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "\"crontab\"", ",", "\"-l\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "...
Query cron for all celcius commands
[ "Query", "cron", "for", "all", "celcius", "commands" ]
e46a3c1ba112af9de23360d1455ab1e037a38ea1
https://github.com/claymcleod/celcius/blob/e46a3c1ba112af9de23360d1455ab1e037a38ea1/lib/celcius/utils/cron_utils.py#L3-L7
40,485
dmwilcox/vcard-tools
vcardtools/vcf_merge.py
VcardFieldsEqual
def VcardFieldsEqual(field1, field2): """Handle comparing vCard fields where inputs are lists of components. Handle parameters? Are any used aside from 'TYPE'? Note: force cast to string to compare sub-objects like Name and Address """ field1_vals = set([ str(f.value) for f in field1 ]) field2...
python
def VcardFieldsEqual(field1, field2): """Handle comparing vCard fields where inputs are lists of components. Handle parameters? Are any used aside from 'TYPE'? Note: force cast to string to compare sub-objects like Name and Address """ field1_vals = set([ str(f.value) for f in field1 ]) field2...
[ "def", "VcardFieldsEqual", "(", "field1", ",", "field2", ")", ":", "field1_vals", "=", "set", "(", "[", "str", "(", "f", ".", "value", ")", "for", "f", "in", "field1", "]", ")", "field2_vals", "=", "set", "(", "[", "str", "(", "f", ".", "value", ...
Handle comparing vCard fields where inputs are lists of components. Handle parameters? Are any used aside from 'TYPE'? Note: force cast to string to compare sub-objects like Name and Address
[ "Handle", "comparing", "vCard", "fields", "where", "inputs", "are", "lists", "of", "components", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_merge.py#L33-L44
40,486
dmwilcox/vcard-tools
vcardtools/vcf_merge.py
VcardMergeListFields
def VcardMergeListFields(field1, field2): """Handle merging list fields that may include some overlap.""" field_dict = {} for f in field1 + field2: field_dict[str(f)] = f return list(field_dict.values())
python
def VcardMergeListFields(field1, field2): """Handle merging list fields that may include some overlap.""" field_dict = {} for f in field1 + field2: field_dict[str(f)] = f return list(field_dict.values())
[ "def", "VcardMergeListFields", "(", "field1", ",", "field2", ")", ":", "field_dict", "=", "{", "}", "for", "f", "in", "field1", "+", "field2", ":", "field_dict", "[", "str", "(", "f", ")", "]", "=", "f", "return", "list", "(", "field_dict", ".", "val...
Handle merging list fields that may include some overlap.
[ "Handle", "merging", "list", "fields", "that", "may", "include", "some", "overlap", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_merge.py#L47-L52
40,487
dmwilcox/vcard-tools
vcardtools/vcf_merge.py
SetVcardField
def SetVcardField(new_vcard, field_name, values): """Set vCard field values and parameters on a new vCard.""" for val in values: new_field = new_vcard.add(field_name) new_field.value = val.value if val.params: new_field.params = val.params return new_vcard
python
def SetVcardField(new_vcard, field_name, values): """Set vCard field values and parameters on a new vCard.""" for val in values: new_field = new_vcard.add(field_name) new_field.value = val.value if val.params: new_field.params = val.params return new_vcard
[ "def", "SetVcardField", "(", "new_vcard", ",", "field_name", ",", "values", ")", ":", "for", "val", "in", "values", ":", "new_field", "=", "new_vcard", ".", "add", "(", "field_name", ")", "new_field", ".", "value", "=", "val", ".", "value", "if", "val", ...
Set vCard field values and parameters on a new vCard.
[ "Set", "vCard", "field", "values", "and", "parameters", "on", "a", "new", "vCard", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_merge.py#L55-L62
40,488
dmwilcox/vcard-tools
vcardtools/vcf_merge.py
CopyVcardFields
def CopyVcardFields(new_vcard, auth_vcard, field_names): """Copy vCard field values from an authoritative vCard into a new one.""" for field in field_names: value_list = auth_vcard.contents.get(field) new_vcard = SetVcardField(new_vcard, field, value_list) return new_vcard
python
def CopyVcardFields(new_vcard, auth_vcard, field_names): """Copy vCard field values from an authoritative vCard into a new one.""" for field in field_names: value_list = auth_vcard.contents.get(field) new_vcard = SetVcardField(new_vcard, field, value_list) return new_vcard
[ "def", "CopyVcardFields", "(", "new_vcard", ",", "auth_vcard", ",", "field_names", ")", ":", "for", "field", "in", "field_names", ":", "value_list", "=", "auth_vcard", ".", "contents", ".", "get", "(", "field", ")", "new_vcard", "=", "SetVcardField", "(", "n...
Copy vCard field values from an authoritative vCard into a new one.
[ "Copy", "vCard", "field", "values", "from", "an", "authoritative", "vCard", "into", "a", "new", "one", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_merge.py#L65-L70
40,489
dmwilcox/vcard-tools
vcardtools/vcf_merge.py
MergeVcards
def MergeVcards(vcard1, vcard2): """Create a new vCard and populate it.""" new_vcard = vobject.vCard() vcard1_fields = set(vcard1.contents.keys()) vcard2_fields = set(vcard2.contents.keys()) mutual_fields = vcard1_fields.intersection(vcard2_fields) logger.debug('Potentially conflicting fields: {...
python
def MergeVcards(vcard1, vcard2): """Create a new vCard and populate it.""" new_vcard = vobject.vCard() vcard1_fields = set(vcard1.contents.keys()) vcard2_fields = set(vcard2.contents.keys()) mutual_fields = vcard1_fields.intersection(vcard2_fields) logger.debug('Potentially conflicting fields: {...
[ "def", "MergeVcards", "(", "vcard1", ",", "vcard2", ")", ":", "new_vcard", "=", "vobject", ".", "vCard", "(", ")", "vcard1_fields", "=", "set", "(", "vcard1", ".", "contents", ".", "keys", "(", ")", ")", "vcard2_fields", "=", "set", "(", "vcard2", ".",...
Create a new vCard and populate it.
[ "Create", "a", "new", "vCard", "and", "populate", "it", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_merge.py#L73-L110
40,490
dmwilcox/vcard-tools
vcardtools/vcf_merge.py
SelectFieldPrompt
def SelectFieldPrompt(field_name, context_str, *options): """Prompts user to pick from provided options. It is possible to provide a function as an option although it is not yet tested. This could allow a user to be prompted to provide their own value rather than the listed options. Args: f...
python
def SelectFieldPrompt(field_name, context_str, *options): """Prompts user to pick from provided options. It is possible to provide a function as an option although it is not yet tested. This could allow a user to be prompted to provide their own value rather than the listed options. Args: f...
[ "def", "SelectFieldPrompt", "(", "field_name", ",", "context_str", ",", "*", "options", ")", ":", "option_format_str", "=", "'[ {} ] \"{}\"'", "option_dict", "=", "{", "}", "print", "(", "context_str", ")", "print", "(", "'Please select one of the following options fo...
Prompts user to pick from provided options. It is possible to provide a function as an option although it is not yet tested. This could allow a user to be prompted to provide their own value rather than the listed options. Args: field_name (string): Name of the field. context_str (string)...
[ "Prompts", "user", "to", "pick", "from", "provided", "options", "." ]
1b0f62a0f4c128c7a212ecdca34ff2acb746b262
https://github.com/dmwilcox/vcard-tools/blob/1b0f62a0f4c128c7a212ecdca34ff2acb746b262/vcardtools/vcf_merge.py#L113-L148
40,491
agamdua/mixtures
mixtures/mixtures.py
make_fixture
def make_fixture(model_class, **kwargs): """ Take the model_klass and generate a fixure for it Args: model_class (MongoEngine Document): model for which a fixture is needed kwargs (dict): any overrides instead of random values Returns: dict for now, other fixture ty...
python
def make_fixture(model_class, **kwargs): """ Take the model_klass and generate a fixure for it Args: model_class (MongoEngine Document): model for which a fixture is needed kwargs (dict): any overrides instead of random values Returns: dict for now, other fixture ty...
[ "def", "make_fixture", "(", "model_class", ",", "*", "*", "kwargs", ")", ":", "all_fields", "=", "get_fields", "(", "model_class", ")", "fields_for_random_generation", "=", "map", "(", "lambda", "x", ":", "getattr", "(", "model_class", ",", "x", ")", ",", ...
Take the model_klass and generate a fixure for it Args: model_class (MongoEngine Document): model for which a fixture is needed kwargs (dict): any overrides instead of random values Returns: dict for now, other fixture types are not implemented yet
[ "Take", "the", "model_klass", "and", "generate", "a", "fixure", "for", "it" ]
9c67f3684ddac53d8a636a4353a266e98d09e54c
https://github.com/agamdua/mixtures/blob/9c67f3684ddac53d8a636a4353a266e98d09e54c/mixtures/mixtures.py#L11-L47
40,492
agamdua/mixtures
mixtures/mixtures.py
get_fields
def get_fields(model_class): """ Pass in a mongo model class and extract all the attributes which are mongoengine fields Returns: list of strings of field attributes """ return [ attr for attr, value in model_class.__dict__.items() if issubclass(type(value), (mongo.base....
python
def get_fields(model_class): """ Pass in a mongo model class and extract all the attributes which are mongoengine fields Returns: list of strings of field attributes """ return [ attr for attr, value in model_class.__dict__.items() if issubclass(type(value), (mongo.base....
[ "def", "get_fields", "(", "model_class", ")", ":", "return", "[", "attr", "for", "attr", ",", "value", "in", "model_class", ".", "__dict__", ".", "items", "(", ")", "if", "issubclass", "(", "type", "(", "value", ")", ",", "(", "mongo", ".", "base", "...
Pass in a mongo model class and extract all the attributes which are mongoengine fields Returns: list of strings of field attributes
[ "Pass", "in", "a", "mongo", "model", "class", "and", "extract", "all", "the", "attributes", "which", "are", "mongoengine", "fields" ]
9c67f3684ddac53d8a636a4353a266e98d09e54c
https://github.com/agamdua/mixtures/blob/9c67f3684ddac53d8a636a4353a266e98d09e54c/mixtures/mixtures.py#L50-L61
40,493
mardix/Yass
yass/yass.py
Yass._get_page_meta
def _get_page_meta(self, page): """ Cache the page meta from the frontmatter and assign new keys The cache data will be used to build links or other properties """ meta = self._pages_meta.get(page) if not meta: src_file = os.path.join(self.pages_dir, page) ...
python
def _get_page_meta(self, page): """ Cache the page meta from the frontmatter and assign new keys The cache data will be used to build links or other properties """ meta = self._pages_meta.get(page) if not meta: src_file = os.path.join(self.pages_dir, page) ...
[ "def", "_get_page_meta", "(", "self", ",", "page", ")", ":", "meta", "=", "self", ".", "_pages_meta", ".", "get", "(", "page", ")", "if", "not", "meta", ":", "src_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "pages_dir", ",", "page...
Cache the page meta from the frontmatter and assign new keys The cache data will be used to build links or other properties
[ "Cache", "the", "page", "meta", "from", "the", "frontmatter", "and", "assign", "new", "keys", "The", "cache", "data", "will", "be", "used", "to", "build", "links", "or", "other", "properties" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L136-L158
40,494
mardix/Yass
yass/yass.py
Yass._get_page_content
def _get_page_content(self, page): """ Get the page content without the frontmatter """ src_file = os.path.join(self.pages_dir, page) with open(src_file) as f: _meta, content = frontmatter.parse(f.read()) return content
python
def _get_page_content(self, page): """ Get the page content without the frontmatter """ src_file = os.path.join(self.pages_dir, page) with open(src_file) as f: _meta, content = frontmatter.parse(f.read()) return content
[ "def", "_get_page_content", "(", "self", ",", "page", ")", ":", "src_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "pages_dir", ",", "page", ")", "with", "open", "(", "src_file", ")", "as", "f", ":", "_meta", ",", "content", "=", "f...
Get the page content without the frontmatter
[ "Get", "the", "page", "content", "without", "the", "frontmatter" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L160-L165
40,495
mardix/Yass
yass/yass.py
Yass._link_to
def _link_to(self, page, text=None, title=None, _class="", id="", alt="", **kwargs): """ Build the A HREF LINK To a page.""" anchor = "" if "#" in page: page, anchor = page.split("#") anchor = "#" + anchor meta = self._get_page_meta(page) return "<a href='...
python
def _link_to(self, page, text=None, title=None, _class="", id="", alt="", **kwargs): """ Build the A HREF LINK To a page.""" anchor = "" if "#" in page: page, anchor = page.split("#") anchor = "#" + anchor meta = self._get_page_meta(page) return "<a href='...
[ "def", "_link_to", "(", "self", ",", "page", ",", "text", "=", "None", ",", "title", "=", "None", ",", "_class", "=", "\"\"", ",", "id", "=", "\"\"", ",", "alt", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "anchor", "=", "\"\"", "if", "\"#\...
Build the A HREF LINK To a page.
[ "Build", "the", "A", "HREF", "LINK", "To", "a", "page", "." ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L167-L180
40,496
mardix/Yass
yass/yass.py
Yass._url_to
def _url_to(self, page): """ Get the url of a page """ anchor = "" if "#" in page: page, anchor = page.split("#") anchor = "#" + anchor meta = self._get_page_meta(page) return meta.get("url")
python
def _url_to(self, page): """ Get the url of a page """ anchor = "" if "#" in page: page, anchor = page.split("#") anchor = "#" + anchor meta = self._get_page_meta(page) return meta.get("url")
[ "def", "_url_to", "(", "self", ",", "page", ")", ":", "anchor", "=", "\"\"", "if", "\"#\"", "in", "page", ":", "page", ",", "anchor", "=", "page", ".", "split", "(", "\"#\"", ")", "anchor", "=", "\"#\"", "+", "anchor", "meta", "=", "self", ".", "...
Get the url of a page
[ "Get", "the", "url", "of", "a", "page" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L182-L189
40,497
mardix/Yass
yass/yass.py
Yass._get_dest_file_and_url
def _get_dest_file_and_url(self, filepath, page_meta={}): """ Return tuple of the file destination and url """ filename = filepath.split("/")[-1] filepath_base = filepath.replace(filename, "").rstrip("/") slug = page_meta.get("slug") fname = slugify(slug) if slug else filename \...
python
def _get_dest_file_and_url(self, filepath, page_meta={}): """ Return tuple of the file destination and url """ filename = filepath.split("/")[-1] filepath_base = filepath.replace(filename, "").rstrip("/") slug = page_meta.get("slug") fname = slugify(slug) if slug else filename \...
[ "def", "_get_dest_file_and_url", "(", "self", ",", "filepath", ",", "page_meta", "=", "{", "}", ")", ":", "filename", "=", "filepath", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "filepath_base", "=", "filepath", ".", "replace", "(", "filename",...
Return tuple of the file destination and url
[ "Return", "tuple", "of", "the", "file", "destination", "and", "url" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L191-L211
40,498
mardix/Yass
yass/yass.py
Yass.build_static
def build_static(self): """ Build static files """ if not os.path.isdir(self.build_static_dir): os.makedirs(self.build_static_dir) copy_tree(self.static_dir, self.build_static_dir) if self.webassets_cmd: self.webassets_cmd.build()
python
def build_static(self): """ Build static files """ if not os.path.isdir(self.build_static_dir): os.makedirs(self.build_static_dir) copy_tree(self.static_dir, self.build_static_dir) if self.webassets_cmd: self.webassets_cmd.build()
[ "def", "build_static", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "build_static_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "build_static_dir", ")", "copy_tree", "(", "self", ".", "static_dir", "...
Build static files
[ "Build", "static", "files" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L272-L278
40,499
mardix/Yass
yass/yass.py
Yass.build_pages
def build_pages(self): """Iterate over the pages_dir and build the pages """ for root, _, files in os.walk(self.pages_dir): base_dir = root.replace(self.pages_dir, "").lstrip("/") if not base_dir.startswith("_"): for f in files: src_file = os.p...
python
def build_pages(self): """Iterate over the pages_dir and build the pages """ for root, _, files in os.walk(self.pages_dir): base_dir = root.replace(self.pages_dir, "").lstrip("/") if not base_dir.startswith("_"): for f in files: src_file = os.p...
[ "def", "build_pages", "(", "self", ")", ":", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "self", ".", "pages_dir", ")", ":", "base_dir", "=", "root", ".", "replace", "(", "self", ".", "pages_dir", ",", "\"\"", ")", ".", "...
Iterate over the pages_dir and build the pages
[ "Iterate", "over", "the", "pages_dir", "and", "build", "the", "pages" ]
32f804c1a916f5b0a13d13fa750e52be3b6d666d
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L280-L287