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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
240,000
|
armstrong/armstrong.apps.related_content
|
armstrong/apps/related_content/admin.py
|
formfield_for_foreignkey_helper
|
def formfield_for_foreignkey_helper(inline, *args, **kwargs):
"""
The implementation for ``RelatedContentInline.formfield_for_foreignkey``
This takes the takes all of the ``args`` and ``kwargs`` from the call to
``formfield_for_foreignkey`` and operates on this. It returns the updated
``args`` and ``kwargs`` to be passed on to ``super``.
This is solely an implementation detail as it's easier to test a function
than to provide all of the expectations that the ``GenericTabularInline``
has.
"""
db_field = args[0]
if db_field.name != "related_type":
return args, kwargs
initial_filter = getattr(settings, RELATED_TYPE_INITIAL_FILTER,
False)
if "initial" not in kwargs and initial_filter:
# TODO: handle gracefully if unable to load and in non-debug
initial = RelatedType.objects.get(**initial_filter).pk
kwargs["initial"] = initial
return args, kwargs
|
python
|
def formfield_for_foreignkey_helper(inline, *args, **kwargs):
"""
The implementation for ``RelatedContentInline.formfield_for_foreignkey``
This takes the takes all of the ``args`` and ``kwargs`` from the call to
``formfield_for_foreignkey`` and operates on this. It returns the updated
``args`` and ``kwargs`` to be passed on to ``super``.
This is solely an implementation detail as it's easier to test a function
than to provide all of the expectations that the ``GenericTabularInline``
has.
"""
db_field = args[0]
if db_field.name != "related_type":
return args, kwargs
initial_filter = getattr(settings, RELATED_TYPE_INITIAL_FILTER,
False)
if "initial" not in kwargs and initial_filter:
# TODO: handle gracefully if unable to load and in non-debug
initial = RelatedType.objects.get(**initial_filter).pk
kwargs["initial"] = initial
return args, kwargs
|
[
"def",
"formfield_for_foreignkey_helper",
"(",
"inline",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"db_field",
"=",
"args",
"[",
"0",
"]",
"if",
"db_field",
".",
"name",
"!=",
"\"related_type\"",
":",
"return",
"args",
",",
"kwargs",
"initial_filter",
"=",
"getattr",
"(",
"settings",
",",
"RELATED_TYPE_INITIAL_FILTER",
",",
"False",
")",
"if",
"\"initial\"",
"not",
"in",
"kwargs",
"and",
"initial_filter",
":",
"# TODO: handle gracefully if unable to load and in non-debug",
"initial",
"=",
"RelatedType",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"initial_filter",
")",
".",
"pk",
"kwargs",
"[",
"\"initial\"",
"]",
"=",
"initial",
"return",
"args",
",",
"kwargs"
] |
The implementation for ``RelatedContentInline.formfield_for_foreignkey``
This takes the takes all of the ``args`` and ``kwargs`` from the call to
``formfield_for_foreignkey`` and operates on this. It returns the updated
``args`` and ``kwargs`` to be passed on to ``super``.
This is solely an implementation detail as it's easier to test a function
than to provide all of the expectations that the ``GenericTabularInline``
has.
|
[
"The",
"implementation",
"for",
"RelatedContentInline",
".",
"formfield_for_foreignkey"
] |
f57b6908d3c76c4a44b2241c676ab5d86391106c
|
https://github.com/armstrong/armstrong.apps.related_content/blob/f57b6908d3c76c4a44b2241c676ab5d86391106c/armstrong/apps/related_content/admin.py#L46-L68
|
240,001
|
DasIch/argvard
|
argvard/signature.py
|
Signature.usage
|
def usage(self):
"""
A usage string that describes the signature.
"""
return u' '.join(u'<%s>' % pattern.usage for pattern in self.patterns)
|
python
|
def usage(self):
"""
A usage string that describes the signature.
"""
return u' '.join(u'<%s>' % pattern.usage for pattern in self.patterns)
|
[
"def",
"usage",
"(",
"self",
")",
":",
"return",
"u' '",
".",
"join",
"(",
"u'<%s>'",
"%",
"pattern",
".",
"usage",
"for",
"pattern",
"in",
"self",
".",
"patterns",
")"
] |
A usage string that describes the signature.
|
[
"A",
"usage",
"string",
"that",
"describes",
"the",
"signature",
"."
] |
2603e323a995e0915ce41fcf49e2a82519556195
|
https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/signature.py#L165-L169
|
240,002
|
DasIch/argvard
|
argvard/signature.py
|
Signature.parse
|
def parse(self, argv):
"""
Parses the given `argv` and returns a dictionary mapping argument names
to the values found in `argv`.
"""
rv = {}
for pattern in self.patterns:
pattern.apply(rv, argv)
return rv
|
python
|
def parse(self, argv):
"""
Parses the given `argv` and returns a dictionary mapping argument names
to the values found in `argv`.
"""
rv = {}
for pattern in self.patterns:
pattern.apply(rv, argv)
return rv
|
[
"def",
"parse",
"(",
"self",
",",
"argv",
")",
":",
"rv",
"=",
"{",
"}",
"for",
"pattern",
"in",
"self",
".",
"patterns",
":",
"pattern",
".",
"apply",
"(",
"rv",
",",
"argv",
")",
"return",
"rv"
] |
Parses the given `argv` and returns a dictionary mapping argument names
to the values found in `argv`.
|
[
"Parses",
"the",
"given",
"argv",
"and",
"returns",
"a",
"dictionary",
"mapping",
"argument",
"names",
"to",
"the",
"values",
"found",
"in",
"argv",
"."
] |
2603e323a995e0915ce41fcf49e2a82519556195
|
https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/signature.py#L171-L179
|
240,003
|
almcc/cinder-data
|
cinder_data/cache.py
|
MemoryCache.get_record
|
def get_record(self, name, record_id):
"""Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`: The cached model.
"""
if name in self._cache:
if record_id in self._cache[name]:
return self._cache[name][record_id]
|
python
|
def get_record(self, name, record_id):
"""Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`: The cached model.
"""
if name in self._cache:
if record_id in self._cache[name]:
return self._cache[name][record_id]
|
[
"def",
"get_record",
"(",
"self",
",",
"name",
",",
"record_id",
")",
":",
"if",
"name",
"in",
"self",
".",
"_cache",
":",
"if",
"record_id",
"in",
"self",
".",
"_cache",
"[",
"name",
"]",
":",
"return",
"self",
".",
"_cache",
"[",
"name",
"]",
"[",
"record_id",
"]"
] |
Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`: The cached model.
|
[
"Retrieve",
"a",
"record",
"with",
"a",
"given",
"type",
"name",
"and",
"record",
"id",
"."
] |
4159a5186c4b4fc32354749892e86130530f6ec5
|
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/cache.py#L55-L67
|
240,004
|
almcc/cinder-data
|
cinder_data/cache.py
|
MemoryCache.get_records
|
def get_records(self, name):
"""Return all the records for the given name in the cache.
Args:
name (string): The name which the required models are stored under.
Returns:
list: A list of :class:`cinder_data.model.CinderModel` models.
"""
if name in self._cache:
return self._cache[name].values()
else:
return []
|
python
|
def get_records(self, name):
"""Return all the records for the given name in the cache.
Args:
name (string): The name which the required models are stored under.
Returns:
list: A list of :class:`cinder_data.model.CinderModel` models.
"""
if name in self._cache:
return self._cache[name].values()
else:
return []
|
[
"def",
"get_records",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_cache",
":",
"return",
"self",
".",
"_cache",
"[",
"name",
"]",
".",
"values",
"(",
")",
"else",
":",
"return",
"[",
"]"
] |
Return all the records for the given name in the cache.
Args:
name (string): The name which the required models are stored under.
Returns:
list: A list of :class:`cinder_data.model.CinderModel` models.
|
[
"Return",
"all",
"the",
"records",
"for",
"the",
"given",
"name",
"in",
"the",
"cache",
"."
] |
4159a5186c4b4fc32354749892e86130530f6ec5
|
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/cache.py#L69-L81
|
240,005
|
almcc/cinder-data
|
cinder_data/cache.py
|
MemoryCache.set_record
|
def set_record(self, name, record_id, record):
"""Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model
"""
if name not in self._cache:
self._cache[name] = {}
self._cache[name][record_id] = record
|
python
|
def set_record(self, name, record_id, record):
"""Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model
"""
if name not in self._cache:
self._cache[name] = {}
self._cache[name][record_id] = record
|
[
"def",
"set_record",
"(",
"self",
",",
"name",
",",
"record_id",
",",
"record",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_cache",
":",
"self",
".",
"_cache",
"[",
"name",
"]",
"=",
"{",
"}",
"self",
".",
"_cache",
"[",
"name",
"]",
"[",
"record_id",
"]",
"=",
"record"
] |
Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model
|
[
"Save",
"a",
"record",
"into",
"the",
"cache",
"."
] |
4159a5186c4b4fc32354749892e86130530f6ec5
|
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/cache.py#L83-L93
|
240,006
|
mayfield/shellish
|
shellish/data.py
|
hone_cache
|
def hone_cache(maxsize=128, maxage=None, refineby='startswith',
store_partials=False):
""" A caching decorator that follows after the style of lru_cache. Calls
that are sharper than previous requests are returned from the cache after
honing in on the requested results using the `refineby` technique.
The `refineby` technique can be `startswith`, `container` or a user
defined function used to provide a subset of results.
Eg.
@hone_cache()
def completer(prefix):
print("MISS")
return set(x for x in {'foo', 'foobar', 'baz'}
if x.startswith(prefix))
completer('f') # -> {'foo', 'foobar'}
MISS
completer('fo') # -> {'foo', 'foobar'}
completer('foob') # -> {'foobar'}
completer('') # -> {'foo', 'foobar', 'baz'}
MISS
completer('ba') # -> {'baz'}
If while trying to hone a cache hit there is an exception the wrapped
function will be called as if it was a full miss.
The `maxage` argument is an option time-to-live in seconds for each cache
result. Any cache entries over the maxage are lazily replaced. """
if not callable(refineby):
finder = hone_cache_finders[refineby]
else:
finder = refineby
def decorator(inner_func):
wrapper = make_hone_cache_wrapper(inner_func, maxsize, maxage, finder,
store_partials)
return functools.update_wrapper(wrapper, inner_func)
return decorator
|
python
|
def hone_cache(maxsize=128, maxage=None, refineby='startswith',
store_partials=False):
""" A caching decorator that follows after the style of lru_cache. Calls
that are sharper than previous requests are returned from the cache after
honing in on the requested results using the `refineby` technique.
The `refineby` technique can be `startswith`, `container` or a user
defined function used to provide a subset of results.
Eg.
@hone_cache()
def completer(prefix):
print("MISS")
return set(x for x in {'foo', 'foobar', 'baz'}
if x.startswith(prefix))
completer('f') # -> {'foo', 'foobar'}
MISS
completer('fo') # -> {'foo', 'foobar'}
completer('foob') # -> {'foobar'}
completer('') # -> {'foo', 'foobar', 'baz'}
MISS
completer('ba') # -> {'baz'}
If while trying to hone a cache hit there is an exception the wrapped
function will be called as if it was a full miss.
The `maxage` argument is an option time-to-live in seconds for each cache
result. Any cache entries over the maxage are lazily replaced. """
if not callable(refineby):
finder = hone_cache_finders[refineby]
else:
finder = refineby
def decorator(inner_func):
wrapper = make_hone_cache_wrapper(inner_func, maxsize, maxage, finder,
store_partials)
return functools.update_wrapper(wrapper, inner_func)
return decorator
|
[
"def",
"hone_cache",
"(",
"maxsize",
"=",
"128",
",",
"maxage",
"=",
"None",
",",
"refineby",
"=",
"'startswith'",
",",
"store_partials",
"=",
"False",
")",
":",
"if",
"not",
"callable",
"(",
"refineby",
")",
":",
"finder",
"=",
"hone_cache_finders",
"[",
"refineby",
"]",
"else",
":",
"finder",
"=",
"refineby",
"def",
"decorator",
"(",
"inner_func",
")",
":",
"wrapper",
"=",
"make_hone_cache_wrapper",
"(",
"inner_func",
",",
"maxsize",
",",
"maxage",
",",
"finder",
",",
"store_partials",
")",
"return",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"inner_func",
")",
"return",
"decorator"
] |
A caching decorator that follows after the style of lru_cache. Calls
that are sharper than previous requests are returned from the cache after
honing in on the requested results using the `refineby` technique.
The `refineby` technique can be `startswith`, `container` or a user
defined function used to provide a subset of results.
Eg.
@hone_cache()
def completer(prefix):
print("MISS")
return set(x for x in {'foo', 'foobar', 'baz'}
if x.startswith(prefix))
completer('f') # -> {'foo', 'foobar'}
MISS
completer('fo') # -> {'foo', 'foobar'}
completer('foob') # -> {'foobar'}
completer('') # -> {'foo', 'foobar', 'baz'}
MISS
completer('ba') # -> {'baz'}
If while trying to hone a cache hit there is an exception the wrapped
function will be called as if it was a full miss.
The `maxage` argument is an option time-to-live in seconds for each cache
result. Any cache entries over the maxage are lazily replaced.
|
[
"A",
"caching",
"decorator",
"that",
"follows",
"after",
"the",
"style",
"of",
"lru_cache",
".",
"Calls",
"that",
"are",
"sharper",
"than",
"previous",
"requests",
"are",
"returned",
"from",
"the",
"cache",
"after",
"honing",
"in",
"on",
"the",
"requested",
"results",
"using",
"the",
"refineby",
"technique",
"."
] |
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
|
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/data.py#L96-L133
|
240,007
|
mayfield/shellish
|
shellish/data.py
|
make_hone_cache_wrapper
|
def make_hone_cache_wrapper(inner_func, maxsize, maxage, finder,
store_partials):
""" Keeps a cache of requests we've already made and use that for
generating results if possible. If the user asked for a root prior
to this call we can use it to skip a new lookup using `finder`. A
top-level lookup will effectively serves as a global cache. """
hits = misses = partials = 0
cache = TTLMapping(maxsize, maxage)
def wrapper(*args):
nonlocal hits, misses, partials
radix = args[-1]
# Attempt fast cache hit first.
try:
r = cache[radix]
except KeyError:
pass
else:
hits += 1
return r
for i in range(len(radix) - 1, -1, -1):
partial_radix = radix[:i]
try:
partial = cache[partial_radix]
except KeyError:
continue
try:
r = finder(radix, partial_radix, partial)
except:
break # Treat any exception as a miss.
partials += 1
if store_partials:
cache[radix] = r
return r
misses += 1
cache[radix] = r = inner_func(*args)
return r
def cache_info():
""" Emulate lru_cache so this is a low touch replacement. """
return HoneCacheInfo(hits, misses, maxsize, len(cache), maxage,
partials, finder)
def cache_clear():
""" Clear cache and stats. """
nonlocal hits, misses, partials
hits = misses = partials = 0
cache.clear()
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return functools.update_wrapper(wrapper, inner_func)
|
python
|
def make_hone_cache_wrapper(inner_func, maxsize, maxage, finder,
store_partials):
""" Keeps a cache of requests we've already made and use that for
generating results if possible. If the user asked for a root prior
to this call we can use it to skip a new lookup using `finder`. A
top-level lookup will effectively serves as a global cache. """
hits = misses = partials = 0
cache = TTLMapping(maxsize, maxage)
def wrapper(*args):
nonlocal hits, misses, partials
radix = args[-1]
# Attempt fast cache hit first.
try:
r = cache[radix]
except KeyError:
pass
else:
hits += 1
return r
for i in range(len(radix) - 1, -1, -1):
partial_radix = radix[:i]
try:
partial = cache[partial_radix]
except KeyError:
continue
try:
r = finder(radix, partial_radix, partial)
except:
break # Treat any exception as a miss.
partials += 1
if store_partials:
cache[radix] = r
return r
misses += 1
cache[radix] = r = inner_func(*args)
return r
def cache_info():
""" Emulate lru_cache so this is a low touch replacement. """
return HoneCacheInfo(hits, misses, maxsize, len(cache), maxage,
partials, finder)
def cache_clear():
""" Clear cache and stats. """
nonlocal hits, misses, partials
hits = misses = partials = 0
cache.clear()
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return functools.update_wrapper(wrapper, inner_func)
|
[
"def",
"make_hone_cache_wrapper",
"(",
"inner_func",
",",
"maxsize",
",",
"maxage",
",",
"finder",
",",
"store_partials",
")",
":",
"hits",
"=",
"misses",
"=",
"partials",
"=",
"0",
"cache",
"=",
"TTLMapping",
"(",
"maxsize",
",",
"maxage",
")",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"nonlocal",
"hits",
",",
"misses",
",",
"partials",
"radix",
"=",
"args",
"[",
"-",
"1",
"]",
"# Attempt fast cache hit first.",
"try",
":",
"r",
"=",
"cache",
"[",
"radix",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"hits",
"+=",
"1",
"return",
"r",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"radix",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"partial_radix",
"=",
"radix",
"[",
":",
"i",
"]",
"try",
":",
"partial",
"=",
"cache",
"[",
"partial_radix",
"]",
"except",
"KeyError",
":",
"continue",
"try",
":",
"r",
"=",
"finder",
"(",
"radix",
",",
"partial_radix",
",",
"partial",
")",
"except",
":",
"break",
"# Treat any exception as a miss.",
"partials",
"+=",
"1",
"if",
"store_partials",
":",
"cache",
"[",
"radix",
"]",
"=",
"r",
"return",
"r",
"misses",
"+=",
"1",
"cache",
"[",
"radix",
"]",
"=",
"r",
"=",
"inner_func",
"(",
"*",
"args",
")",
"return",
"r",
"def",
"cache_info",
"(",
")",
":",
"\"\"\" Emulate lru_cache so this is a low touch replacement. \"\"\"",
"return",
"HoneCacheInfo",
"(",
"hits",
",",
"misses",
",",
"maxsize",
",",
"len",
"(",
"cache",
")",
",",
"maxage",
",",
"partials",
",",
"finder",
")",
"def",
"cache_clear",
"(",
")",
":",
"\"\"\" Clear cache and stats. \"\"\"",
"nonlocal",
"hits",
",",
"misses",
",",
"partials",
"hits",
"=",
"misses",
"=",
"partials",
"=",
"0",
"cache",
".",
"clear",
"(",
")",
"wrapper",
".",
"cache_info",
"=",
"cache_info",
"wrapper",
".",
"cache_clear",
"=",
"cache_clear",
"return",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"inner_func",
")"
] |
Keeps a cache of requests we've already made and use that for
generating results if possible. If the user asked for a root prior
to this call we can use it to skip a new lookup using `finder`. A
top-level lookup will effectively serves as a global cache.
|
[
"Keeps",
"a",
"cache",
"of",
"requests",
"we",
"ve",
"already",
"made",
"and",
"use",
"that",
"for",
"generating",
"results",
"if",
"possible",
".",
"If",
"the",
"user",
"asked",
"for",
"a",
"root",
"prior",
"to",
"this",
"call",
"we",
"can",
"use",
"it",
"to",
"skip",
"a",
"new",
"lookup",
"using",
"finder",
".",
"A",
"top",
"-",
"level",
"lookup",
"will",
"effectively",
"serves",
"as",
"a",
"global",
"cache",
"."
] |
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
|
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/data.py#L151-L204
|
240,008
|
mayfield/shellish
|
shellish/data.py
|
ttl_cache
|
def ttl_cache(maxage, maxsize=128):
""" A time-to-live caching decorator that follows after the style of
lru_cache. The `maxage` argument is time-to-live in seconds for each
cache result. Any cache entries over the maxage are lazily replaced. """
def decorator(inner_func):
wrapper = make_ttl_cache_wrapper(inner_func, maxage, maxsize)
return functools.update_wrapper(wrapper, inner_func)
return decorator
|
python
|
def ttl_cache(maxage, maxsize=128):
""" A time-to-live caching decorator that follows after the style of
lru_cache. The `maxage` argument is time-to-live in seconds for each
cache result. Any cache entries over the maxage are lazily replaced. """
def decorator(inner_func):
wrapper = make_ttl_cache_wrapper(inner_func, maxage, maxsize)
return functools.update_wrapper(wrapper, inner_func)
return decorator
|
[
"def",
"ttl_cache",
"(",
"maxage",
",",
"maxsize",
"=",
"128",
")",
":",
"def",
"decorator",
"(",
"inner_func",
")",
":",
"wrapper",
"=",
"make_ttl_cache_wrapper",
"(",
"inner_func",
",",
"maxage",
",",
"maxsize",
")",
"return",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"inner_func",
")",
"return",
"decorator"
] |
A time-to-live caching decorator that follows after the style of
lru_cache. The `maxage` argument is time-to-live in seconds for each
cache result. Any cache entries over the maxage are lazily replaced.
|
[
"A",
"time",
"-",
"to",
"-",
"live",
"caching",
"decorator",
"that",
"follows",
"after",
"the",
"style",
"of",
"lru_cache",
".",
"The",
"maxage",
"argument",
"is",
"time",
"-",
"to",
"-",
"live",
"in",
"seconds",
"for",
"each",
"cache",
"result",
".",
"Any",
"cache",
"entries",
"over",
"the",
"maxage",
"are",
"lazily",
"replaced",
"."
] |
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
|
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/data.py#L207-L215
|
240,009
|
mayfield/shellish
|
shellish/data.py
|
make_ttl_cache_wrapper
|
def make_ttl_cache_wrapper(inner_func, maxage, maxsize, typed=False):
""" Use the function signature as a key for a ttl mapping. Any misses
will defer to the wrapped function and its result is stored for future
calls. """
hits = misses = 0
cache = TTLMapping(maxsize, maxage)
def wrapper(*args, **kwargs):
nonlocal hits, misses
key = functools._make_key(args, kwargs, typed)
try:
result = cache[key]
except KeyError:
misses += 1
result = cache[key] = inner_func(*args, **kwargs)
else:
hits += 1
return result
def cache_info():
""" Emulate lru_cache so this is a low touch replacement. """
return TTLCacheInfo(hits, misses, maxsize, len(cache), maxage)
def cache_clear():
""" Clear cache and stats. """
nonlocal hits, misses
hits = misses = 0
cache.clear()
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return functools.update_wrapper(wrapper, inner_func)
|
python
|
def make_ttl_cache_wrapper(inner_func, maxage, maxsize, typed=False):
""" Use the function signature as a key for a ttl mapping. Any misses
will defer to the wrapped function and its result is stored for future
calls. """
hits = misses = 0
cache = TTLMapping(maxsize, maxage)
def wrapper(*args, **kwargs):
nonlocal hits, misses
key = functools._make_key(args, kwargs, typed)
try:
result = cache[key]
except KeyError:
misses += 1
result = cache[key] = inner_func(*args, **kwargs)
else:
hits += 1
return result
def cache_info():
""" Emulate lru_cache so this is a low touch replacement. """
return TTLCacheInfo(hits, misses, maxsize, len(cache), maxage)
def cache_clear():
""" Clear cache and stats. """
nonlocal hits, misses
hits = misses = 0
cache.clear()
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return functools.update_wrapper(wrapper, inner_func)
|
[
"def",
"make_ttl_cache_wrapper",
"(",
"inner_func",
",",
"maxage",
",",
"maxsize",
",",
"typed",
"=",
"False",
")",
":",
"hits",
"=",
"misses",
"=",
"0",
"cache",
"=",
"TTLMapping",
"(",
"maxsize",
",",
"maxage",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nonlocal",
"hits",
",",
"misses",
"key",
"=",
"functools",
".",
"_make_key",
"(",
"args",
",",
"kwargs",
",",
"typed",
")",
"try",
":",
"result",
"=",
"cache",
"[",
"key",
"]",
"except",
"KeyError",
":",
"misses",
"+=",
"1",
"result",
"=",
"cache",
"[",
"key",
"]",
"=",
"inner_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"hits",
"+=",
"1",
"return",
"result",
"def",
"cache_info",
"(",
")",
":",
"\"\"\" Emulate lru_cache so this is a low touch replacement. \"\"\"",
"return",
"TTLCacheInfo",
"(",
"hits",
",",
"misses",
",",
"maxsize",
",",
"len",
"(",
"cache",
")",
",",
"maxage",
")",
"def",
"cache_clear",
"(",
")",
":",
"\"\"\" Clear cache and stats. \"\"\"",
"nonlocal",
"hits",
",",
"misses",
"hits",
"=",
"misses",
"=",
"0",
"cache",
".",
"clear",
"(",
")",
"wrapper",
".",
"cache_info",
"=",
"cache_info",
"wrapper",
".",
"cache_clear",
"=",
"cache_clear",
"return",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"inner_func",
")"
] |
Use the function signature as a key for a ttl mapping. Any misses
will defer to the wrapped function and its result is stored for future
calls.
|
[
"Use",
"the",
"function",
"signature",
"as",
"a",
"key",
"for",
"a",
"ttl",
"mapping",
".",
"Any",
"misses",
"will",
"defer",
"to",
"the",
"wrapped",
"function",
"and",
"its",
"result",
"is",
"stored",
"for",
"future",
"calls",
"."
] |
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
|
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/data.py#L218-L251
|
240,010
|
vilmibm/done
|
done/Commands.py
|
run
|
def run(command, options, args):
"""Run the requested command. args is either a list of descriptions or a list of strings to filter by"""
if command == "backend":
subprocess.call(("sqlite3", db_path))
if command == "add":
dp = pdt.Calendar()
due = mktime(dp.parse(options.due)[0]) if options.due else None
print "added tasks..."
[Task(desc, due).add() for desc in args]
return
filters = args if len(args) else None
rows = Query(filters, options).find()
tasks = [Task(r["desc"], r["due"]) for r in rows]
if command == "list":
for t in tasks:
print "\t *", t
if command == "done":
print "done with..."
finished_tasks = []
for t in tasks:
finished = t.done()
if finished:
finished_tasks.append(t)
if not finished_tasks:
return
print ""
print "finished tasks:"
for t in finished_tasks:
print "\t X", t
if command == "remove":
print "remove..."
removed_tasks = []
for t in tasks:
removed = t.remove()
if removed:
removed_tasks.append(t)
if not removed_tasks:
return
print ""
print "removed tasks:"
for t in removed_tasks:
print "\t RM", t
|
python
|
def run(command, options, args):
"""Run the requested command. args is either a list of descriptions or a list of strings to filter by"""
if command == "backend":
subprocess.call(("sqlite3", db_path))
if command == "add":
dp = pdt.Calendar()
due = mktime(dp.parse(options.due)[0]) if options.due else None
print "added tasks..."
[Task(desc, due).add() for desc in args]
return
filters = args if len(args) else None
rows = Query(filters, options).find()
tasks = [Task(r["desc"], r["due"]) for r in rows]
if command == "list":
for t in tasks:
print "\t *", t
if command == "done":
print "done with..."
finished_tasks = []
for t in tasks:
finished = t.done()
if finished:
finished_tasks.append(t)
if not finished_tasks:
return
print ""
print "finished tasks:"
for t in finished_tasks:
print "\t X", t
if command == "remove":
print "remove..."
removed_tasks = []
for t in tasks:
removed = t.remove()
if removed:
removed_tasks.append(t)
if not removed_tasks:
return
print ""
print "removed tasks:"
for t in removed_tasks:
print "\t RM", t
|
[
"def",
"run",
"(",
"command",
",",
"options",
",",
"args",
")",
":",
"if",
"command",
"==",
"\"backend\"",
":",
"subprocess",
".",
"call",
"(",
"(",
"\"sqlite3\"",
",",
"db_path",
")",
")",
"if",
"command",
"==",
"\"add\"",
":",
"dp",
"=",
"pdt",
".",
"Calendar",
"(",
")",
"due",
"=",
"mktime",
"(",
"dp",
".",
"parse",
"(",
"options",
".",
"due",
")",
"[",
"0",
"]",
")",
"if",
"options",
".",
"due",
"else",
"None",
"print",
"\"added tasks...\"",
"[",
"Task",
"(",
"desc",
",",
"due",
")",
".",
"add",
"(",
")",
"for",
"desc",
"in",
"args",
"]",
"return",
"filters",
"=",
"args",
"if",
"len",
"(",
"args",
")",
"else",
"None",
"rows",
"=",
"Query",
"(",
"filters",
",",
"options",
")",
".",
"find",
"(",
")",
"tasks",
"=",
"[",
"Task",
"(",
"r",
"[",
"\"desc\"",
"]",
",",
"r",
"[",
"\"due\"",
"]",
")",
"for",
"r",
"in",
"rows",
"]",
"if",
"command",
"==",
"\"list\"",
":",
"for",
"t",
"in",
"tasks",
":",
"print",
"\"\\t *\"",
",",
"t",
"if",
"command",
"==",
"\"done\"",
":",
"print",
"\"done with...\"",
"finished_tasks",
"=",
"[",
"]",
"for",
"t",
"in",
"tasks",
":",
"finished",
"=",
"t",
".",
"done",
"(",
")",
"if",
"finished",
":",
"finished_tasks",
".",
"append",
"(",
"t",
")",
"if",
"not",
"finished_tasks",
":",
"return",
"print",
"\"\"",
"print",
"\"finished tasks:\"",
"for",
"t",
"in",
"finished_tasks",
":",
"print",
"\"\\t X\"",
",",
"t",
"if",
"command",
"==",
"\"remove\"",
":",
"print",
"\"remove...\"",
"removed_tasks",
"=",
"[",
"]",
"for",
"t",
"in",
"tasks",
":",
"removed",
"=",
"t",
".",
"remove",
"(",
")",
"if",
"removed",
":",
"removed_tasks",
".",
"append",
"(",
"t",
")",
"if",
"not",
"removed_tasks",
":",
"return",
"print",
"\"\"",
"print",
"\"removed tasks:\"",
"for",
"t",
"in",
"removed_tasks",
":",
"print",
"\"\\t RM\"",
",",
"t"
] |
Run the requested command. args is either a list of descriptions or a list of strings to filter by
|
[
"Run",
"the",
"requested",
"command",
".",
"args",
"is",
"either",
"a",
"list",
"of",
"descriptions",
"or",
"a",
"list",
"of",
"strings",
"to",
"filter",
"by"
] |
7e5b60d2900ceddefa49de352a19b794199b51a8
|
https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/done/Commands.py#L25-L76
|
240,011
|
thomasbiddle/Kippt-for-Python
|
kippt/notifications.py
|
Notifications.mark_read
|
def mark_read(self):
""" Mark notifications as read.
CURRENT UNSUPPORTED:
https://github.com/kippt/api-documentation/blob/master/endpoints/notifications/POST_notifications.md
"""
# Obviously remove the exception when Kippt says the support it.
raise NotImplementedError(
"The Kippt API does not yet support marking notifications as read."
)
data = json.dumps({"action": "mark_seen"})
r = requests.post(
"https://kippt.com/api/notifications",
headers=self.kippt.header,
data=data
)
return (r.json())
|
python
|
def mark_read(self):
""" Mark notifications as read.
CURRENT UNSUPPORTED:
https://github.com/kippt/api-documentation/blob/master/endpoints/notifications/POST_notifications.md
"""
# Obviously remove the exception when Kippt says the support it.
raise NotImplementedError(
"The Kippt API does not yet support marking notifications as read."
)
data = json.dumps({"action": "mark_seen"})
r = requests.post(
"https://kippt.com/api/notifications",
headers=self.kippt.header,
data=data
)
return (r.json())
|
[
"def",
"mark_read",
"(",
"self",
")",
":",
"# Obviously remove the exception when Kippt says the support it.",
"raise",
"NotImplementedError",
"(",
"\"The Kippt API does not yet support marking notifications as read.\"",
")",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"action\"",
":",
"\"mark_seen\"",
"}",
")",
"r",
"=",
"requests",
".",
"post",
"(",
"\"https://kippt.com/api/notifications\"",
",",
"headers",
"=",
"self",
".",
"kippt",
".",
"header",
",",
"data",
"=",
"data",
")",
"return",
"(",
"r",
".",
"json",
"(",
")",
")"
] |
Mark notifications as read.
CURRENT UNSUPPORTED:
https://github.com/kippt/api-documentation/blob/master/endpoints/notifications/POST_notifications.md
|
[
"Mark",
"notifications",
"as",
"read",
"."
] |
dddd0ff84d70ccf2d84e50e3cff7aad89f9c1267
|
https://github.com/thomasbiddle/Kippt-for-Python/blob/dddd0ff84d70ccf2d84e50e3cff7aad89f9c1267/kippt/notifications.py#L32-L50
|
240,012
|
BenDoan/perform
|
perform.py
|
get_programs
|
def get_programs():
"""Returns a generator that yields the available executable programs
:returns: a generator that yields the programs available after a refresh_listing()
:rtype: generator
"""
programs = []
os.environ['PATH'] += os.pathsep + os.getcwd()
for p in os.environ['PATH'].split(os.pathsep):
if path.isdir(p):
for f in os.listdir(p):
if _is_executable(path.join(p, f)):
yield f
|
python
|
def get_programs():
"""Returns a generator that yields the available executable programs
:returns: a generator that yields the programs available after a refresh_listing()
:rtype: generator
"""
programs = []
os.environ['PATH'] += os.pathsep + os.getcwd()
for p in os.environ['PATH'].split(os.pathsep):
if path.isdir(p):
for f in os.listdir(p):
if _is_executable(path.join(p, f)):
yield f
|
[
"def",
"get_programs",
"(",
")",
":",
"programs",
"=",
"[",
"]",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
"+=",
"os",
".",
"pathsep",
"+",
"os",
".",
"getcwd",
"(",
")",
"for",
"p",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"if",
"path",
".",
"isdir",
"(",
"p",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"p",
")",
":",
"if",
"_is_executable",
"(",
"path",
".",
"join",
"(",
"p",
",",
"f",
")",
")",
":",
"yield",
"f"
] |
Returns a generator that yields the available executable programs
:returns: a generator that yields the programs available after a refresh_listing()
:rtype: generator
|
[
"Returns",
"a",
"generator",
"that",
"yields",
"the",
"available",
"executable",
"programs"
] |
3434c5c68fb7661d74f03404c71bb5fbebe1900f
|
https://github.com/BenDoan/perform/blob/3434c5c68fb7661d74f03404c71bb5fbebe1900f/perform.py#L128-L140
|
240,013
|
BenDoan/perform
|
perform.py
|
_underscore_run_program
|
def _underscore_run_program(name, *args, **kwargs):
"""Runs the 'name' program, use this if there are illegal python method characters in the program name
>>> _underscore_run_program("echo", "Hello")
'Hello'
>>> _underscore_run_program("echo", "Hello", return_object=True).stdout
'Hello'
>>> _underscore_run_program("echo", "Hello", ro=True).stdout
'Hello'
"""
if name in get_programs() or kwargs.get("shell", False):
return _run_program(name, *args, **kwargs)
else:
raise ProgramNotFoundException()
|
python
|
def _underscore_run_program(name, *args, **kwargs):
"""Runs the 'name' program, use this if there are illegal python method characters in the program name
>>> _underscore_run_program("echo", "Hello")
'Hello'
>>> _underscore_run_program("echo", "Hello", return_object=True).stdout
'Hello'
>>> _underscore_run_program("echo", "Hello", ro=True).stdout
'Hello'
"""
if name in get_programs() or kwargs.get("shell", False):
return _run_program(name, *args, **kwargs)
else:
raise ProgramNotFoundException()
|
[
"def",
"_underscore_run_program",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"in",
"get_programs",
"(",
")",
"or",
"kwargs",
".",
"get",
"(",
"\"shell\"",
",",
"False",
")",
":",
"return",
"_run_program",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"raise",
"ProgramNotFoundException",
"(",
")"
] |
Runs the 'name' program, use this if there are illegal python method characters in the program name
>>> _underscore_run_program("echo", "Hello")
'Hello'
>>> _underscore_run_program("echo", "Hello", return_object=True).stdout
'Hello'
>>> _underscore_run_program("echo", "Hello", ro=True).stdout
'Hello'
|
[
"Runs",
"the",
"name",
"program",
"use",
"this",
"if",
"there",
"are",
"illegal",
"python",
"method",
"characters",
"in",
"the",
"program",
"name"
] |
3434c5c68fb7661d74f03404c71bb5fbebe1900f
|
https://github.com/BenDoan/perform/blob/3434c5c68fb7661d74f03404c71bb5fbebe1900f/perform.py#L142-L155
|
240,014
|
BenDoan/perform
|
perform.py
|
refresh_listing
|
def refresh_listing():
"""Refreshes the list of programs attached to the perform module from
the path"""
for program in get_programs():
if re.match(r'^[a-zA-Z_][a-zA-Z_0-9]*$', program) is not None:
globals()[program] = partial(_run_program, program)
globals()["_"] = _underscore_run_program
|
python
|
def refresh_listing():
"""Refreshes the list of programs attached to the perform module from
the path"""
for program in get_programs():
if re.match(r'^[a-zA-Z_][a-zA-Z_0-9]*$', program) is not None:
globals()[program] = partial(_run_program, program)
globals()["_"] = _underscore_run_program
|
[
"def",
"refresh_listing",
"(",
")",
":",
"for",
"program",
"in",
"get_programs",
"(",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'^[a-zA-Z_][a-zA-Z_0-9]*$'",
",",
"program",
")",
"is",
"not",
"None",
":",
"globals",
"(",
")",
"[",
"program",
"]",
"=",
"partial",
"(",
"_run_program",
",",
"program",
")",
"globals",
"(",
")",
"[",
"\"_\"",
"]",
"=",
"_underscore_run_program"
] |
Refreshes the list of programs attached to the perform module from
the path
|
[
"Refreshes",
"the",
"list",
"of",
"programs",
"attached",
"to",
"the",
"perform",
"module",
"from",
"the",
"path"
] |
3434c5c68fb7661d74f03404c71bb5fbebe1900f
|
https://github.com/BenDoan/perform/blob/3434c5c68fb7661d74f03404c71bb5fbebe1900f/perform.py#L157-L164
|
240,015
|
PonteIneptique/collatinus-python
|
pycollatinus/lemmatiseur.py
|
Lemmatiseur.load
|
def load(path=None):
""" Compile le lemmatiseur localement
"""
if path is None:
path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), "data"))
path = os.path.join(path, "compiled.pickle")
with open(path, "rb") as file:
return load(file)
|
python
|
def load(path=None):
""" Compile le lemmatiseur localement
"""
if path is None:
path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), "data"))
path = os.path.join(path, "compiled.pickle")
with open(path, "rb") as file:
return load(file)
|
[
"def",
"load",
"(",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"\"data\"",
")",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"compiled.pickle\"",
")",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"file",
":",
"return",
"load",
"(",
"file",
")"
] |
Compile le lemmatiseur localement
|
[
"Compile",
"le",
"lemmatiseur",
"localement"
] |
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
|
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemmatiseur.py#L62-L69
|
240,016
|
PonteIneptique/collatinus-python
|
pycollatinus/lemmatiseur.py
|
Lemmatiseur._lemmatise_assims
|
def _lemmatise_assims(self, f, *args, **kwargs):
""" Lemmatise un mot f avec son assimilation
:param f: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
:param results: Current results
"""
forme_assimilee = self.assims(f)
if forme_assimilee != f:
for proposal in self._lemmatise(forme_assimilee, *args, **kwargs):
yield proposal
|
python
|
def _lemmatise_assims(self, f, *args, **kwargs):
""" Lemmatise un mot f avec son assimilation
:param f: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
:param results: Current results
"""
forme_assimilee = self.assims(f)
if forme_assimilee != f:
for proposal in self._lemmatise(forme_assimilee, *args, **kwargs):
yield proposal
|
[
"def",
"_lemmatise_assims",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"forme_assimilee",
"=",
"self",
".",
"assims",
"(",
"f",
")",
"if",
"forme_assimilee",
"!=",
"f",
":",
"for",
"proposal",
"in",
"self",
".",
"_lemmatise",
"(",
"forme_assimilee",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"yield",
"proposal"
] |
Lemmatise un mot f avec son assimilation
:param f: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
:param results: Current results
|
[
"Lemmatise",
"un",
"mot",
"f",
"avec",
"son",
"assimilation"
] |
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
|
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemmatiseur.py#L176-L187
|
240,017
|
PonteIneptique/collatinus-python
|
pycollatinus/lemmatiseur.py
|
Lemmatiseur._lemmatise_roman_numerals
|
def _lemmatise_roman_numerals(self, form, pos=False, get_lemma_object=False):
""" Lemmatise un mot f si c'est un nombre romain
:param form: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
"""
if estRomain(form):
_lemma = Lemme(
cle=form, graphie_accentuee=form, graphie=form, parent=self, origin=0, pos="a",
modele=self.modele("inv")
)
yield Lemmatiseur.format_result(
form=form,
lemma=_lemma,
with_pos=pos,
raw_obj=get_lemma_object
)
if form.upper() != form:
yield from self._lemmatise_roman_numerals(form.upper(), pos=pos, get_lemma_object=get_lemma_object)
|
python
|
def _lemmatise_roman_numerals(self, form, pos=False, get_lemma_object=False):
""" Lemmatise un mot f si c'est un nombre romain
:param form: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
"""
if estRomain(form):
_lemma = Lemme(
cle=form, graphie_accentuee=form, graphie=form, parent=self, origin=0, pos="a",
modele=self.modele("inv")
)
yield Lemmatiseur.format_result(
form=form,
lemma=_lemma,
with_pos=pos,
raw_obj=get_lemma_object
)
if form.upper() != form:
yield from self._lemmatise_roman_numerals(form.upper(), pos=pos, get_lemma_object=get_lemma_object)
|
[
"def",
"_lemmatise_roman_numerals",
"(",
"self",
",",
"form",
",",
"pos",
"=",
"False",
",",
"get_lemma_object",
"=",
"False",
")",
":",
"if",
"estRomain",
"(",
"form",
")",
":",
"_lemma",
"=",
"Lemme",
"(",
"cle",
"=",
"form",
",",
"graphie_accentuee",
"=",
"form",
",",
"graphie",
"=",
"form",
",",
"parent",
"=",
"self",
",",
"origin",
"=",
"0",
",",
"pos",
"=",
"\"a\"",
",",
"modele",
"=",
"self",
".",
"modele",
"(",
"\"inv\"",
")",
")",
"yield",
"Lemmatiseur",
".",
"format_result",
"(",
"form",
"=",
"form",
",",
"lemma",
"=",
"_lemma",
",",
"with_pos",
"=",
"pos",
",",
"raw_obj",
"=",
"get_lemma_object",
")",
"if",
"form",
".",
"upper",
"(",
")",
"!=",
"form",
":",
"yield",
"from",
"self",
".",
"_lemmatise_roman_numerals",
"(",
"form",
".",
"upper",
"(",
")",
",",
"pos",
"=",
"pos",
",",
"get_lemma_object",
"=",
"get_lemma_object",
")"
] |
Lemmatise un mot f si c'est un nombre romain
:param form: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
|
[
"Lemmatise",
"un",
"mot",
"f",
"si",
"c",
"est",
"un",
"nombre",
"romain"
] |
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
|
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemmatiseur.py#L189-L209
|
240,018
|
PonteIneptique/collatinus-python
|
pycollatinus/lemmatiseur.py
|
Lemmatiseur._lemmatise_contractions
|
def _lemmatise_contractions(self, f, *args, **kwargs):
""" Lemmatise un mot f avec sa contraction
:param f: Mot à lemmatiser
:yield: Match formated like in _lemmatise()
"""
fd = f
for contraction, decontraction in self._contractions.items():
if fd.endswith(contraction):
fd = f[:-len(contraction)]
if "v" in fd or "V" in fd:
fd += decontraction
else:
fd += deramise(decontraction)
yield from self._lemmatise(fd, *args, **kwargs)
|
python
|
def _lemmatise_contractions(self, f, *args, **kwargs):
""" Lemmatise un mot f avec sa contraction
:param f: Mot à lemmatiser
:yield: Match formated like in _lemmatise()
"""
fd = f
for contraction, decontraction in self._contractions.items():
if fd.endswith(contraction):
fd = f[:-len(contraction)]
if "v" in fd or "V" in fd:
fd += decontraction
else:
fd += deramise(decontraction)
yield from self._lemmatise(fd, *args, **kwargs)
|
[
"def",
"_lemmatise_contractions",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fd",
"=",
"f",
"for",
"contraction",
",",
"decontraction",
"in",
"self",
".",
"_contractions",
".",
"items",
"(",
")",
":",
"if",
"fd",
".",
"endswith",
"(",
"contraction",
")",
":",
"fd",
"=",
"f",
"[",
":",
"-",
"len",
"(",
"contraction",
")",
"]",
"if",
"\"v\"",
"in",
"fd",
"or",
"\"V\"",
"in",
"fd",
":",
"fd",
"+=",
"decontraction",
"else",
":",
"fd",
"+=",
"deramise",
"(",
"decontraction",
")",
"yield",
"from",
"self",
".",
"_lemmatise",
"(",
"fd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Lemmatise un mot f avec sa contraction
:param f: Mot à lemmatiser
:yield: Match formated like in _lemmatise()
|
[
"Lemmatise",
"un",
"mot",
"f",
"avec",
"sa",
"contraction"
] |
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
|
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemmatiseur.py#L211-L225
|
240,019
|
PonteIneptique/collatinus-python
|
pycollatinus/lemmatiseur.py
|
Lemmatiseur._lemmatise_suffixe
|
def _lemmatise_suffixe(self, f, *args, **kwargs):
""" Lemmatise un mot f si il finit par un suffixe
:param f: Mot à lemmatiser
:yield: Match formated like in _lemmatise()
"""
for suffixe in self._suffixes:
if f.endswith(suffixe) and suffixe != f:
yield from self._lemmatise(f[:-len(suffixe)], *args, **kwargs)
|
python
|
def _lemmatise_suffixe(self, f, *args, **kwargs):
""" Lemmatise un mot f si il finit par un suffixe
:param f: Mot à lemmatiser
:yield: Match formated like in _lemmatise()
"""
for suffixe in self._suffixes:
if f.endswith(suffixe) and suffixe != f:
yield from self._lemmatise(f[:-len(suffixe)], *args, **kwargs)
|
[
"def",
"_lemmatise_suffixe",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"suffixe",
"in",
"self",
".",
"_suffixes",
":",
"if",
"f",
".",
"endswith",
"(",
"suffixe",
")",
"and",
"suffixe",
"!=",
"f",
":",
"yield",
"from",
"self",
".",
"_lemmatise",
"(",
"f",
"[",
":",
"-",
"len",
"(",
"suffixe",
")",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Lemmatise un mot f si il finit par un suffixe
:param f: Mot à lemmatiser
:yield: Match formated like in _lemmatise()
|
[
"Lemmatise",
"un",
"mot",
"f",
"si",
"il",
"finit",
"par",
"un",
"suffixe"
] |
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
|
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemmatiseur.py#L238-L246
|
240,020
|
mrstephenneal/dirutility
|
dirutility/ftp.py
|
FTP.connect
|
def connect(host, port, username, password):
"""Connect and login to an FTP server and return ftplib.FTP object."""
# Instantiate ftplib client
session = ftplib.FTP()
# Connect to host without auth
session.connect(host, port)
# Authenticate connection
session.login(username, password)
return session
|
python
|
def connect(host, port, username, password):
"""Connect and login to an FTP server and return ftplib.FTP object."""
# Instantiate ftplib client
session = ftplib.FTP()
# Connect to host without auth
session.connect(host, port)
# Authenticate connection
session.login(username, password)
return session
|
[
"def",
"connect",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
")",
":",
"# Instantiate ftplib client",
"session",
"=",
"ftplib",
".",
"FTP",
"(",
")",
"# Connect to host without auth",
"session",
".",
"connect",
"(",
"host",
",",
"port",
")",
"# Authenticate connection",
"session",
".",
"login",
"(",
"username",
",",
"password",
")",
"return",
"session"
] |
Connect and login to an FTP server and return ftplib.FTP object.
|
[
"Connect",
"and",
"login",
"to",
"an",
"FTP",
"server",
"and",
"return",
"ftplib",
".",
"FTP",
"object",
"."
] |
339378659e2d7e09c53acfc51c5df745bb0cd517
|
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/ftp.py#L22-L32
|
240,021
|
mrstephenneal/dirutility
|
dirutility/ftp.py
|
FTP.get
|
def get(self, remote, local=None, keep_dir_structure=False):
"""
Download a remote file on the fto sever to a local directory.
:param remote: File path of remote source file
:param local: Directory of local destination directory
:param keep_dir_structure: If True, replicates the remote files folder structure
"""
if local and os.path.isdir(local):
os.chdir(local)
elif keep_dir_structure:
# Replicate the remote files folder structure
for directory in remote.split(os.sep)[:-1]:
if not os.path.isdir(directory):
os.mkdir(directory)
os.chdir(directory)
# Change to the correct directory if remote is a path not just a name
if os.sep in remote:
directory, file_name = remote.rsplit(os.sep, 1)
self.chdir(directory)
else:
file_name = remote
# Download the file and get response
response = self._retrieve_binary(file_name)
# Rename downloaded files if local is a file_name string
if local and isinstance(local, str):
os.rename(file_name, local)
return response
|
python
|
def get(self, remote, local=None, keep_dir_structure=False):
"""
Download a remote file on the fto sever to a local directory.
:param remote: File path of remote source file
:param local: Directory of local destination directory
:param keep_dir_structure: If True, replicates the remote files folder structure
"""
if local and os.path.isdir(local):
os.chdir(local)
elif keep_dir_structure:
# Replicate the remote files folder structure
for directory in remote.split(os.sep)[:-1]:
if not os.path.isdir(directory):
os.mkdir(directory)
os.chdir(directory)
# Change to the correct directory if remote is a path not just a name
if os.sep in remote:
directory, file_name = remote.rsplit(os.sep, 1)
self.chdir(directory)
else:
file_name = remote
# Download the file and get response
response = self._retrieve_binary(file_name)
# Rename downloaded files if local is a file_name string
if local and isinstance(local, str):
os.rename(file_name, local)
return response
|
[
"def",
"get",
"(",
"self",
",",
"remote",
",",
"local",
"=",
"None",
",",
"keep_dir_structure",
"=",
"False",
")",
":",
"if",
"local",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"local",
")",
":",
"os",
".",
"chdir",
"(",
"local",
")",
"elif",
"keep_dir_structure",
":",
"# Replicate the remote files folder structure",
"for",
"directory",
"in",
"remote",
".",
"split",
"(",
"os",
".",
"sep",
")",
"[",
":",
"-",
"1",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"os",
".",
"mkdir",
"(",
"directory",
")",
"os",
".",
"chdir",
"(",
"directory",
")",
"# Change to the correct directory if remote is a path not just a name",
"if",
"os",
".",
"sep",
"in",
"remote",
":",
"directory",
",",
"file_name",
"=",
"remote",
".",
"rsplit",
"(",
"os",
".",
"sep",
",",
"1",
")",
"self",
".",
"chdir",
"(",
"directory",
")",
"else",
":",
"file_name",
"=",
"remote",
"# Download the file and get response",
"response",
"=",
"self",
".",
"_retrieve_binary",
"(",
"file_name",
")",
"# Rename downloaded files if local is a file_name string",
"if",
"local",
"and",
"isinstance",
"(",
"local",
",",
"str",
")",
":",
"os",
".",
"rename",
"(",
"file_name",
",",
"local",
")",
"return",
"response"
] |
Download a remote file on the fto sever to a local directory.
:param remote: File path of remote source file
:param local: Directory of local destination directory
:param keep_dir_structure: If True, replicates the remote files folder structure
|
[
"Download",
"a",
"remote",
"file",
"on",
"the",
"fto",
"sever",
"to",
"a",
"local",
"directory",
"."
] |
339378659e2d7e09c53acfc51c5df745bb0cd517
|
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/ftp.py#L48-L79
|
240,022
|
mrstephenneal/dirutility
|
dirutility/ftp.py
|
FTP.chdir
|
def chdir(self, directory_path, make=False):
"""Change directories and optionally make the directory if it doesn't exist."""
if os.sep in directory_path:
for directory in directory_path.split(os.sep):
if make and not self.directory_exists(directory):
try:
self.session.mkd(directory)
except ftplib.error_perm:
# Directory already exists
pass
self.session.cwd(directory)
else:
self.session.cwd(directory_path)
|
python
|
def chdir(self, directory_path, make=False):
"""Change directories and optionally make the directory if it doesn't exist."""
if os.sep in directory_path:
for directory in directory_path.split(os.sep):
if make and not self.directory_exists(directory):
try:
self.session.mkd(directory)
except ftplib.error_perm:
# Directory already exists
pass
self.session.cwd(directory)
else:
self.session.cwd(directory_path)
|
[
"def",
"chdir",
"(",
"self",
",",
"directory_path",
",",
"make",
"=",
"False",
")",
":",
"if",
"os",
".",
"sep",
"in",
"directory_path",
":",
"for",
"directory",
"in",
"directory_path",
".",
"split",
"(",
"os",
".",
"sep",
")",
":",
"if",
"make",
"and",
"not",
"self",
".",
"directory_exists",
"(",
"directory",
")",
":",
"try",
":",
"self",
".",
"session",
".",
"mkd",
"(",
"directory",
")",
"except",
"ftplib",
".",
"error_perm",
":",
"# Directory already exists",
"pass",
"self",
".",
"session",
".",
"cwd",
"(",
"directory",
")",
"else",
":",
"self",
".",
"session",
".",
"cwd",
"(",
"directory_path",
")"
] |
Change directories and optionally make the directory if it doesn't exist.
|
[
"Change",
"directories",
"and",
"optionally",
"make",
"the",
"directory",
"if",
"it",
"doesn",
"t",
"exist",
"."
] |
339378659e2d7e09c53acfc51c5df745bb0cd517
|
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/ftp.py#L81-L93
|
240,023
|
mrstephenneal/dirutility
|
dirutility/ftp.py
|
FTP.listdir
|
def listdir(self, directory_path=None, hidden_files=False):
"""
Return a list of files and directories in a given directory.
:param directory_path: Optional str (defaults to current directory)
:param hidden_files: Include hidden files
:return: Directory listing
"""
# Change current directory if a directory path is specified, otherwise use current
if directory_path:
self.chdir(directory_path)
# Exclude hidden files
if not hidden_files:
return [path for path in self.session.nlst() if not path.startswith('.')]
# Include hidden files
else:
return self.session.nlst()
|
python
|
def listdir(self, directory_path=None, hidden_files=False):
"""
Return a list of files and directories in a given directory.
:param directory_path: Optional str (defaults to current directory)
:param hidden_files: Include hidden files
:return: Directory listing
"""
# Change current directory if a directory path is specified, otherwise use current
if directory_path:
self.chdir(directory_path)
# Exclude hidden files
if not hidden_files:
return [path for path in self.session.nlst() if not path.startswith('.')]
# Include hidden files
else:
return self.session.nlst()
|
[
"def",
"listdir",
"(",
"self",
",",
"directory_path",
"=",
"None",
",",
"hidden_files",
"=",
"False",
")",
":",
"# Change current directory if a directory path is specified, otherwise use current",
"if",
"directory_path",
":",
"self",
".",
"chdir",
"(",
"directory_path",
")",
"# Exclude hidden files",
"if",
"not",
"hidden_files",
":",
"return",
"[",
"path",
"for",
"path",
"in",
"self",
".",
"session",
".",
"nlst",
"(",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"'.'",
")",
"]",
"# Include hidden files",
"else",
":",
"return",
"self",
".",
"session",
".",
"nlst",
"(",
")"
] |
Return a list of files and directories in a given directory.
:param directory_path: Optional str (defaults to current directory)
:param hidden_files: Include hidden files
:return: Directory listing
|
[
"Return",
"a",
"list",
"of",
"files",
"and",
"directories",
"in",
"a",
"given",
"directory",
"."
] |
339378659e2d7e09c53acfc51c5df745bb0cd517
|
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/ftp.py#L95-L113
|
240,024
|
mrstephenneal/dirutility
|
dirutility/ftp.py
|
FTP.delete
|
def delete(self, file_path):
"""Remove the file named filename from the server."""
if os.sep in file_path:
directory, file_name = file_path.rsplit(os.sep, 1)
self.chdir(directory)
return self.session.delete(file_name)
else:
return self.session.delete(file_path)
|
python
|
def delete(self, file_path):
"""Remove the file named filename from the server."""
if os.sep in file_path:
directory, file_name = file_path.rsplit(os.sep, 1)
self.chdir(directory)
return self.session.delete(file_name)
else:
return self.session.delete(file_path)
|
[
"def",
"delete",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"os",
".",
"sep",
"in",
"file_path",
":",
"directory",
",",
"file_name",
"=",
"file_path",
".",
"rsplit",
"(",
"os",
".",
"sep",
",",
"1",
")",
"self",
".",
"chdir",
"(",
"directory",
")",
"return",
"self",
".",
"session",
".",
"delete",
"(",
"file_name",
")",
"else",
":",
"return",
"self",
".",
"session",
".",
"delete",
"(",
"file_path",
")"
] |
Remove the file named filename from the server.
|
[
"Remove",
"the",
"file",
"named",
"filename",
"from",
"the",
"server",
"."
] |
339378659e2d7e09c53acfc51c5df745bb0cd517
|
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/ftp.py#L119-L127
|
240,025
|
mrstephenneal/dirutility
|
dirutility/ftp.py
|
FTP._retrieve_binary
|
def _retrieve_binary(self, file_name):
"""Retrieve a file in binary transfer mode."""
with open(file_name, 'wb') as f:
return self.session.retrbinary('RETR ' + file_name, f.write)
|
python
|
def _retrieve_binary(self, file_name):
"""Retrieve a file in binary transfer mode."""
with open(file_name, 'wb') as f:
return self.session.retrbinary('RETR ' + file_name, f.write)
|
[
"def",
"_retrieve_binary",
"(",
"self",
",",
"file_name",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"'wb'",
")",
"as",
"f",
":",
"return",
"self",
".",
"session",
".",
"retrbinary",
"(",
"'RETR '",
"+",
"file_name",
",",
"f",
".",
"write",
")"
] |
Retrieve a file in binary transfer mode.
|
[
"Retrieve",
"a",
"file",
"in",
"binary",
"transfer",
"mode",
"."
] |
339378659e2d7e09c53acfc51c5df745bb0cd517
|
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/ftp.py#L139-L142
|
240,026
|
mrstephenneal/dirutility
|
dirutility/ftp.py
|
FTP._store_binary
|
def _store_binary(self, local_path, remote):
"""Store a file in binary via ftp."""
# Destination directory
dst_dir = os.path.dirname(remote)
# Destination file name
dst_file = os.path.basename(remote)
# File upload command
dst_cmd = 'STOR {0}'.format(dst_file)
with open(local_path, 'rb') as local_file:
# Change directory if needed
if dst_dir != dst_file:
self.chdir(dst_dir, make=True)
# Upload file & return response
return self.session.storbinary(dst_cmd, local_file)
|
python
|
def _store_binary(self, local_path, remote):
"""Store a file in binary via ftp."""
# Destination directory
dst_dir = os.path.dirname(remote)
# Destination file name
dst_file = os.path.basename(remote)
# File upload command
dst_cmd = 'STOR {0}'.format(dst_file)
with open(local_path, 'rb') as local_file:
# Change directory if needed
if dst_dir != dst_file:
self.chdir(dst_dir, make=True)
# Upload file & return response
return self.session.storbinary(dst_cmd, local_file)
|
[
"def",
"_store_binary",
"(",
"self",
",",
"local_path",
",",
"remote",
")",
":",
"# Destination directory",
"dst_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"remote",
")",
"# Destination file name",
"dst_file",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"remote",
")",
"# File upload command",
"dst_cmd",
"=",
"'STOR {0}'",
".",
"format",
"(",
"dst_file",
")",
"with",
"open",
"(",
"local_path",
",",
"'rb'",
")",
"as",
"local_file",
":",
"# Change directory if needed",
"if",
"dst_dir",
"!=",
"dst_file",
":",
"self",
".",
"chdir",
"(",
"dst_dir",
",",
"make",
"=",
"True",
")",
"# Upload file & return response",
"return",
"self",
".",
"session",
".",
"storbinary",
"(",
"dst_cmd",
",",
"local_file",
")"
] |
Store a file in binary via ftp.
|
[
"Store",
"a",
"file",
"in",
"binary",
"via",
"ftp",
"."
] |
339378659e2d7e09c53acfc51c5df745bb0cd517
|
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/ftp.py#L144-L161
|
240,027
|
krukas/Trionyx
|
trionyx/trionyx/forms/accounts.py
|
UserUpdateForm.clean_new_password2
|
def clean_new_password2(self):
"""Validate password when set"""
password1 = self.cleaned_data.get('new_password1')
password2 = self.cleaned_data.get('new_password2')
if password1 or password2:
if password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
password_validation.validate_password(password2, self.instance)
return password2
|
python
|
def clean_new_password2(self):
"""Validate password when set"""
password1 = self.cleaned_data.get('new_password1')
password2 = self.cleaned_data.get('new_password2')
if password1 or password2:
if password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
password_validation.validate_password(password2, self.instance)
return password2
|
[
"def",
"clean_new_password2",
"(",
"self",
")",
":",
"password1",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'new_password1'",
")",
"password2",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'new_password2'",
")",
"if",
"password1",
"or",
"password2",
":",
"if",
"password1",
"!=",
"password2",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"self",
".",
"error_messages",
"[",
"'password_mismatch'",
"]",
",",
"code",
"=",
"'password_mismatch'",
",",
")",
"password_validation",
".",
"validate_password",
"(",
"password2",
",",
"self",
".",
"instance",
")",
"return",
"password2"
] |
Validate password when set
|
[
"Validate",
"password",
"when",
"set"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/forms/accounts.py#L69-L80
|
240,028
|
wtsi-hgi/python-baton-wrapper
|
baton/_baton/_baton_runner.py
|
BatonRunner._run_command
|
def _run_command(self, arguments: List[str], input_data: Any=None, output_encoding: str="utf-8") -> str:
"""
Run a command as a subprocess.
Ignores errors given over stderr if there is output on stdout (this is the case where baton has been run
correctly and has expressed the error in it's JSON out, which can be handled more appropriately upstream to this
method.)
:param arguments: the arguments to run
:param input_data: the input data to pass to the subprocess
:param output_encoding: optional specification of the output encoding to expect
:return: the process' standard out
"""
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
if isinstance(input_data, List):
for to_write in input_data:
to_write_as_json = json.dumps(to_write)
process.stdin.write(str.encode(to_write_as_json))
input_data = None
else:
input_data = str.encode(json.dumps(input_data))
timeout_in_seconds = self.timeout_queries_after.total_seconds() if self.timeout_queries_after is not None \
else None
out, error = process.communicate(input=input_data, timeout=timeout_in_seconds)
if len(out) == 0 and len(error) > 0:
raise RuntimeError(error)
return out.decode(output_encoding).rstrip()
|
python
|
def _run_command(self, arguments: List[str], input_data: Any=None, output_encoding: str="utf-8") -> str:
"""
Run a command as a subprocess.
Ignores errors given over stderr if there is output on stdout (this is the case where baton has been run
correctly and has expressed the error in it's JSON out, which can be handled more appropriately upstream to this
method.)
:param arguments: the arguments to run
:param input_data: the input data to pass to the subprocess
:param output_encoding: optional specification of the output encoding to expect
:return: the process' standard out
"""
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
if isinstance(input_data, List):
for to_write in input_data:
to_write_as_json = json.dumps(to_write)
process.stdin.write(str.encode(to_write_as_json))
input_data = None
else:
input_data = str.encode(json.dumps(input_data))
timeout_in_seconds = self.timeout_queries_after.total_seconds() if self.timeout_queries_after is not None \
else None
out, error = process.communicate(input=input_data, timeout=timeout_in_seconds)
if len(out) == 0 and len(error) > 0:
raise RuntimeError(error)
return out.decode(output_encoding).rstrip()
|
[
"def",
"_run_command",
"(",
"self",
",",
"arguments",
":",
"List",
"[",
"str",
"]",
",",
"input_data",
":",
"Any",
"=",
"None",
",",
"output_encoding",
":",
"str",
"=",
"\"utf-8\"",
")",
"->",
"str",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"arguments",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"if",
"isinstance",
"(",
"input_data",
",",
"List",
")",
":",
"for",
"to_write",
"in",
"input_data",
":",
"to_write_as_json",
"=",
"json",
".",
"dumps",
"(",
"to_write",
")",
"process",
".",
"stdin",
".",
"write",
"(",
"str",
".",
"encode",
"(",
"to_write_as_json",
")",
")",
"input_data",
"=",
"None",
"else",
":",
"input_data",
"=",
"str",
".",
"encode",
"(",
"json",
".",
"dumps",
"(",
"input_data",
")",
")",
"timeout_in_seconds",
"=",
"self",
".",
"timeout_queries_after",
".",
"total_seconds",
"(",
")",
"if",
"self",
".",
"timeout_queries_after",
"is",
"not",
"None",
"else",
"None",
"out",
",",
"error",
"=",
"process",
".",
"communicate",
"(",
"input",
"=",
"input_data",
",",
"timeout",
"=",
"timeout_in_seconds",
")",
"if",
"len",
"(",
"out",
")",
"==",
"0",
"and",
"len",
"(",
"error",
")",
">",
"0",
":",
"raise",
"RuntimeError",
"(",
"error",
")",
"return",
"out",
".",
"decode",
"(",
"output_encoding",
")",
".",
"rstrip",
"(",
")"
] |
Run a command as a subprocess.
Ignores errors given over stderr if there is output on stdout (this is the case where baton has been run
correctly and has expressed the error in it's JSON out, which can be handled more appropriately upstream to this
method.)
:param arguments: the arguments to run
:param input_data: the input data to pass to the subprocess
:param output_encoding: optional specification of the output encoding to expect
:return: the process' standard out
|
[
"Run",
"a",
"command",
"as",
"a",
"subprocess",
"."
] |
ae0c9e3630e2c4729a0614cc86f493688436b0b7
|
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/_baton/_baton_runner.py#L129-L157
|
240,029
|
inveniosoftware-attic/invenio-knowledge
|
invenio_knowledge/forms.py
|
collection_choices
|
def collection_choices():
"""Return collection choices."""
from invenio_collections.models import Collection
return [(0, _('-None-'))] + [
(c.id, c.name) for c in Collection.query.all()
]
|
python
|
def collection_choices():
"""Return collection choices."""
from invenio_collections.models import Collection
return [(0, _('-None-'))] + [
(c.id, c.name) for c in Collection.query.all()
]
|
[
"def",
"collection_choices",
"(",
")",
":",
"from",
"invenio_collections",
".",
"models",
"import",
"Collection",
"return",
"[",
"(",
"0",
",",
"_",
"(",
"'-None-'",
")",
")",
"]",
"+",
"[",
"(",
"c",
".",
"id",
",",
"c",
".",
"name",
")",
"for",
"c",
"in",
"Collection",
".",
"query",
".",
"all",
"(",
")",
"]"
] |
Return collection choices.
|
[
"Return",
"collection",
"choices",
"."
] |
b31722dc14243ca8f626f8b3bce9718d0119de55
|
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/forms.py#L63-L68
|
240,030
|
ministryofjustice/postcodeinfo-client-python
|
postcodeinfo.py
|
Client._query_api
|
def _query_api(self, endpoint, **kwargs):
"""
Query the API.
"""
try:
response = requests.get(
'{api}/{endpoint}?{args}'.format(
api=self.url,
endpoint=endpoint,
args=urllib.urlencode(kwargs)),
headers={
'Authorization': 'Token {token}'.format(token=self.token)},
timeout=self.timeout)
except requests.RequestException as err:
raise ServiceUnavailable(err)
if response.status_code == 404:
raise NoResults()
try:
response.raise_for_status()
except requests.HTTPError as http_err:
raise ServerException(http_err)
return response.json()
|
python
|
def _query_api(self, endpoint, **kwargs):
"""
Query the API.
"""
try:
response = requests.get(
'{api}/{endpoint}?{args}'.format(
api=self.url,
endpoint=endpoint,
args=urllib.urlencode(kwargs)),
headers={
'Authorization': 'Token {token}'.format(token=self.token)},
timeout=self.timeout)
except requests.RequestException as err:
raise ServiceUnavailable(err)
if response.status_code == 404:
raise NoResults()
try:
response.raise_for_status()
except requests.HTTPError as http_err:
raise ServerException(http_err)
return response.json()
|
[
"def",
"_query_api",
"(",
"self",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"'{api}/{endpoint}?{args}'",
".",
"format",
"(",
"api",
"=",
"self",
".",
"url",
",",
"endpoint",
"=",
"endpoint",
",",
"args",
"=",
"urllib",
".",
"urlencode",
"(",
"kwargs",
")",
")",
",",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Token {token}'",
".",
"format",
"(",
"token",
"=",
"self",
".",
"token",
")",
"}",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"except",
"requests",
".",
"RequestException",
"as",
"err",
":",
"raise",
"ServiceUnavailable",
"(",
"err",
")",
"if",
"response",
".",
"status_code",
"==",
"404",
":",
"raise",
"NoResults",
"(",
")",
"try",
":",
"response",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"http_err",
":",
"raise",
"ServerException",
"(",
"http_err",
")",
"return",
"response",
".",
"json",
"(",
")"
] |
Query the API.
|
[
"Query",
"the",
"API",
"."
] |
8644e1292cdb5d7f2b2eb3c0982b1f97202b24cf
|
https://github.com/ministryofjustice/postcodeinfo-client-python/blob/8644e1292cdb5d7f2b2eb3c0982b1f97202b24cf/postcodeinfo.py#L270-L295
|
240,031
|
okzach/bofhexcuse
|
bofhexcuse/__init__.py
|
generate_random_string
|
def generate_random_string(template_dict, key='start'):
"""Generates a random excuse from a simple template dict.
Based off of drow's generator.js (public domain).
Grok it here: http://donjon.bin.sh/code/random/generator.js
Args:
template_dict: Dict with template strings.
key: String with the starting index for the dict. (Default: 'start')
Returns:
Generated string.
"""
data = template_dict.get(key)
#if isinstance(data, list):
result = random.choice(data)
#else:
#result = random.choice(data.values())
for match in token_regex.findall(result):
word = generate_random_string(template_dict, match) or match
result = result.replace('{{{0}}}'.format(match), word)
return result
|
python
|
def generate_random_string(template_dict, key='start'):
"""Generates a random excuse from a simple template dict.
Based off of drow's generator.js (public domain).
Grok it here: http://donjon.bin.sh/code/random/generator.js
Args:
template_dict: Dict with template strings.
key: String with the starting index for the dict. (Default: 'start')
Returns:
Generated string.
"""
data = template_dict.get(key)
#if isinstance(data, list):
result = random.choice(data)
#else:
#result = random.choice(data.values())
for match in token_regex.findall(result):
word = generate_random_string(template_dict, match) or match
result = result.replace('{{{0}}}'.format(match), word)
return result
|
[
"def",
"generate_random_string",
"(",
"template_dict",
",",
"key",
"=",
"'start'",
")",
":",
"data",
"=",
"template_dict",
".",
"get",
"(",
"key",
")",
"#if isinstance(data, list):",
"result",
"=",
"random",
".",
"choice",
"(",
"data",
")",
"#else:",
"#result = random.choice(data.values())",
"for",
"match",
"in",
"token_regex",
".",
"findall",
"(",
"result",
")",
":",
"word",
"=",
"generate_random_string",
"(",
"template_dict",
",",
"match",
")",
"or",
"match",
"result",
"=",
"result",
".",
"replace",
"(",
"'{{{0}}}'",
".",
"format",
"(",
"match",
")",
",",
"word",
")",
"return",
"result"
] |
Generates a random excuse from a simple template dict.
Based off of drow's generator.js (public domain).
Grok it here: http://donjon.bin.sh/code/random/generator.js
Args:
template_dict: Dict with template strings.
key: String with the starting index for the dict. (Default: 'start')
Returns:
Generated string.
|
[
"Generates",
"a",
"random",
"excuse",
"from",
"a",
"simple",
"template",
"dict",
"."
] |
ea241b8a63c4baa44cfb17c6acd47b6e12e822af
|
https://github.com/okzach/bofhexcuse/blob/ea241b8a63c4baa44cfb17c6acd47b6e12e822af/bofhexcuse/__init__.py#L14-L39
|
240,032
|
okzach/bofhexcuse
|
bofhexcuse/__init__.py
|
bofh_excuse
|
def bofh_excuse(how_many=1):
"""Generate random BOFH themed technical excuses!
Args:
how_many: Number of excuses to generate. (Default: 1)
Returns:
A list of BOFH excuses.
"""
excuse_path = os.path.join(os.path.dirname(__file__), 'bofh_excuses.json')
with open(excuse_path, 'r') as _f:
excuse_dict = json.load(_f)
return [generate_random_string(excuse_dict) for _ in range(int(how_many))]
|
python
|
def bofh_excuse(how_many=1):
"""Generate random BOFH themed technical excuses!
Args:
how_many: Number of excuses to generate. (Default: 1)
Returns:
A list of BOFH excuses.
"""
excuse_path = os.path.join(os.path.dirname(__file__), 'bofh_excuses.json')
with open(excuse_path, 'r') as _f:
excuse_dict = json.load(_f)
return [generate_random_string(excuse_dict) for _ in range(int(how_many))]
|
[
"def",
"bofh_excuse",
"(",
"how_many",
"=",
"1",
")",
":",
"excuse_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'bofh_excuses.json'",
")",
"with",
"open",
"(",
"excuse_path",
",",
"'r'",
")",
"as",
"_f",
":",
"excuse_dict",
"=",
"json",
".",
"load",
"(",
"_f",
")",
"return",
"[",
"generate_random_string",
"(",
"excuse_dict",
")",
"for",
"_",
"in",
"range",
"(",
"int",
"(",
"how_many",
")",
")",
"]"
] |
Generate random BOFH themed technical excuses!
Args:
how_many: Number of excuses to generate. (Default: 1)
Returns:
A list of BOFH excuses.
|
[
"Generate",
"random",
"BOFH",
"themed",
"technical",
"excuses!"
] |
ea241b8a63c4baa44cfb17c6acd47b6e12e822af
|
https://github.com/okzach/bofhexcuse/blob/ea241b8a63c4baa44cfb17c6acd47b6e12e822af/bofhexcuse/__init__.py#L42-L56
|
240,033
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
get_current_waypoints
|
def get_current_waypoints(boatd=None):
'''
Get the current set of waypoints active from boatd.
:returns: The current waypoints
:rtype: List of Points
'''
if boatd is None:
boatd = Boatd()
content = boatd.get('/waypoints')
return [Point(*coords) for coords in content.get('waypoints')]
|
python
|
def get_current_waypoints(boatd=None):
'''
Get the current set of waypoints active from boatd.
:returns: The current waypoints
:rtype: List of Points
'''
if boatd is None:
boatd = Boatd()
content = boatd.get('/waypoints')
return [Point(*coords) for coords in content.get('waypoints')]
|
[
"def",
"get_current_waypoints",
"(",
"boatd",
"=",
"None",
")",
":",
"if",
"boatd",
"is",
"None",
":",
"boatd",
"=",
"Boatd",
"(",
")",
"content",
"=",
"boatd",
".",
"get",
"(",
"'/waypoints'",
")",
"return",
"[",
"Point",
"(",
"*",
"coords",
")",
"for",
"coords",
"in",
"content",
".",
"get",
"(",
"'waypoints'",
")",
"]"
] |
Get the current set of waypoints active from boatd.
:returns: The current waypoints
:rtype: List of Points
|
[
"Get",
"the",
"current",
"set",
"of",
"waypoints",
"active",
"from",
"boatd",
"."
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L211-L223
|
240,034
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
get_home_position
|
def get_home_position(boatd=None):
'''
Get the current home position from boatd.
:returns: The configured home position
:rtype: Points
'''
if boatd is None:
boatd = Boatd()
content = boatd.get('/waypoints')
home = content.get('home', None)
if home is not None:
lat, lon = home
return Point(lat, lon)
else:
return None
|
python
|
def get_home_position(boatd=None):
'''
Get the current home position from boatd.
:returns: The configured home position
:rtype: Points
'''
if boatd is None:
boatd = Boatd()
content = boatd.get('/waypoints')
home = content.get('home', None)
if home is not None:
lat, lon = home
return Point(lat, lon)
else:
return None
|
[
"def",
"get_home_position",
"(",
"boatd",
"=",
"None",
")",
":",
"if",
"boatd",
"is",
"None",
":",
"boatd",
"=",
"Boatd",
"(",
")",
"content",
"=",
"boatd",
".",
"get",
"(",
"'/waypoints'",
")",
"home",
"=",
"content",
".",
"get",
"(",
"'home'",
",",
"None",
")",
"if",
"home",
"is",
"not",
"None",
":",
"lat",
",",
"lon",
"=",
"home",
"return",
"Point",
"(",
"lat",
",",
"lon",
")",
"else",
":",
"return",
"None"
] |
Get the current home position from boatd.
:returns: The configured home position
:rtype: Points
|
[
"Get",
"the",
"current",
"home",
"position",
"from",
"boatd",
"."
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L226-L243
|
240,035
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
Boatd.get
|
def get(self, endpoint):
'''Return the result of a GET request to `endpoint` on boatd'''
json_body = urlopen(self.url(endpoint)).read().decode('utf-8')
return json.loads(json_body)
|
python
|
def get(self, endpoint):
'''Return the result of a GET request to `endpoint` on boatd'''
json_body = urlopen(self.url(endpoint)).read().decode('utf-8')
return json.loads(json_body)
|
[
"def",
"get",
"(",
"self",
",",
"endpoint",
")",
":",
"json_body",
"=",
"urlopen",
"(",
"self",
".",
"url",
"(",
"endpoint",
")",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"json",
".",
"loads",
"(",
"json_body",
")"
] |
Return the result of a GET request to `endpoint` on boatd
|
[
"Return",
"the",
"result",
"of",
"a",
"GET",
"request",
"to",
"endpoint",
"on",
"boatd"
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L31-L34
|
240,036
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
Boatd.post
|
def post(self, content, endpoint=''):
'''
Issue a POST request with `content` as the body to `endpoint` and
return the result.
'''
url = self.url(endpoint)
post_content = json.dumps(content).encode('utf-8')
headers = {'Content-Type': 'application/json'}
request = Request(url, post_content, headers)
response = urlopen(request)
return json.loads(response.read().decode('utf-8'))
|
python
|
def post(self, content, endpoint=''):
'''
Issue a POST request with `content` as the body to `endpoint` and
return the result.
'''
url = self.url(endpoint)
post_content = json.dumps(content).encode('utf-8')
headers = {'Content-Type': 'application/json'}
request = Request(url, post_content, headers)
response = urlopen(request)
return json.loads(response.read().decode('utf-8'))
|
[
"def",
"post",
"(",
"self",
",",
"content",
",",
"endpoint",
"=",
"''",
")",
":",
"url",
"=",
"self",
".",
"url",
"(",
"endpoint",
")",
"post_content",
"=",
"json",
".",
"dumps",
"(",
"content",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
"request",
"=",
"Request",
"(",
"url",
",",
"post_content",
",",
"headers",
")",
"response",
"=",
"urlopen",
"(",
"request",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] |
Issue a POST request with `content` as the body to `endpoint` and
return the result.
|
[
"Issue",
"a",
"POST",
"request",
"with",
"content",
"as",
"the",
"body",
"to",
"endpoint",
"and",
"return",
"the",
"result",
"."
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L36-L48
|
240,037
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
Boat.wind
|
def wind(self):
'''
Return the direction of the wind in degrees.
:returns: wind object containing direction bearing and speed
:rtype: Wind
'''
content = self._cached_boat.get('wind')
return Wind(
Bearing(content.get('absolute')),
content.get('speed'),
Bearing(content.get('apparent'))
)
|
python
|
def wind(self):
'''
Return the direction of the wind in degrees.
:returns: wind object containing direction bearing and speed
:rtype: Wind
'''
content = self._cached_boat.get('wind')
return Wind(
Bearing(content.get('absolute')),
content.get('speed'),
Bearing(content.get('apparent'))
)
|
[
"def",
"wind",
"(",
"self",
")",
":",
"content",
"=",
"self",
".",
"_cached_boat",
".",
"get",
"(",
"'wind'",
")",
"return",
"Wind",
"(",
"Bearing",
"(",
"content",
".",
"get",
"(",
"'absolute'",
")",
")",
",",
"content",
".",
"get",
"(",
"'speed'",
")",
",",
"Bearing",
"(",
"content",
".",
"get",
"(",
"'apparent'",
")",
")",
")"
] |
Return the direction of the wind in degrees.
:returns: wind object containing direction bearing and speed
:rtype: Wind
|
[
"Return",
"the",
"direction",
"of",
"the",
"wind",
"in",
"degrees",
"."
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L102-L114
|
240,038
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
Boat.position
|
def position(self):
'''
Return the current position of the boat.
:returns: current position
:rtype: Point
'''
content = self._cached_boat
lat, lon = content.get('position')
return Point(lat, lon)
|
python
|
def position(self):
'''
Return the current position of the boat.
:returns: current position
:rtype: Point
'''
content = self._cached_boat
lat, lon = content.get('position')
return Point(lat, lon)
|
[
"def",
"position",
"(",
"self",
")",
":",
"content",
"=",
"self",
".",
"_cached_boat",
"lat",
",",
"lon",
"=",
"content",
".",
"get",
"(",
"'position'",
")",
"return",
"Point",
"(",
"lat",
",",
"lon",
")"
] |
Return the current position of the boat.
:returns: current position
:rtype: Point
|
[
"Return",
"the",
"current",
"position",
"of",
"the",
"boat",
"."
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L118-L127
|
240,039
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
Boat.set_rudder
|
def set_rudder(self, angle):
'''
Set the angle of the rudder to be `angle` degrees.
:param angle: rudder angle
:type angle: float between -90 and 90
'''
angle = float(angle)
request = self.boatd.post({'value': float(angle)}, '/rudder')
return request.get('result')
|
python
|
def set_rudder(self, angle):
'''
Set the angle of the rudder to be `angle` degrees.
:param angle: rudder angle
:type angle: float between -90 and 90
'''
angle = float(angle)
request = self.boatd.post({'value': float(angle)}, '/rudder')
return request.get('result')
|
[
"def",
"set_rudder",
"(",
"self",
",",
"angle",
")",
":",
"angle",
"=",
"float",
"(",
"angle",
")",
"request",
"=",
"self",
".",
"boatd",
".",
"post",
"(",
"{",
"'value'",
":",
"float",
"(",
"angle",
")",
"}",
",",
"'/rudder'",
")",
"return",
"request",
".",
"get",
"(",
"'result'",
")"
] |
Set the angle of the rudder to be `angle` degrees.
:param angle: rudder angle
:type angle: float between -90 and 90
|
[
"Set",
"the",
"angle",
"of",
"the",
"rudder",
"to",
"be",
"angle",
"degrees",
"."
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L129-L138
|
240,040
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
Boat.set_sail
|
def set_sail(self, angle):
'''
Set the angle of the sail to `angle` degrees
:param angle: sail angle
:type angle: float between -90 and 90
'''
angle = float(angle)
request = self.boatd.post({'value': float(angle)}, '/sail')
return request.get('result')
|
python
|
def set_sail(self, angle):
'''
Set the angle of the sail to `angle` degrees
:param angle: sail angle
:type angle: float between -90 and 90
'''
angle = float(angle)
request = self.boatd.post({'value': float(angle)}, '/sail')
return request.get('result')
|
[
"def",
"set_sail",
"(",
"self",
",",
"angle",
")",
":",
"angle",
"=",
"float",
"(",
"angle",
")",
"request",
"=",
"self",
".",
"boatd",
".",
"post",
"(",
"{",
"'value'",
":",
"float",
"(",
"angle",
")",
"}",
",",
"'/sail'",
")",
"return",
"request",
".",
"get",
"(",
"'result'",
")"
] |
Set the angle of the sail to `angle` degrees
:param angle: sail angle
:type angle: float between -90 and 90
|
[
"Set",
"the",
"angle",
"of",
"the",
"sail",
"to",
"angle",
"degrees"
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L152-L161
|
240,041
|
boatd/python-boatd
|
boatdclient/boatd_client.py
|
Behaviour.start
|
def start(self, name):
'''
End the current behaviour and run a named behaviour.
:param name: the name of the behaviour to run
:type name: str
'''
d = self.boatd.post({'active': name}, endpoint='/behaviours')
current = d.get('active')
if current is not None:
return 'started {}'.format(current)
else:
return 'no behaviour running'
|
python
|
def start(self, name):
'''
End the current behaviour and run a named behaviour.
:param name: the name of the behaviour to run
:type name: str
'''
d = self.boatd.post({'active': name}, endpoint='/behaviours')
current = d.get('active')
if current is not None:
return 'started {}'.format(current)
else:
return 'no behaviour running'
|
[
"def",
"start",
"(",
"self",
",",
"name",
")",
":",
"d",
"=",
"self",
".",
"boatd",
".",
"post",
"(",
"{",
"'active'",
":",
"name",
"}",
",",
"endpoint",
"=",
"'/behaviours'",
")",
"current",
"=",
"d",
".",
"get",
"(",
"'active'",
")",
"if",
"current",
"is",
"not",
"None",
":",
"return",
"'started {}'",
".",
"format",
"(",
"current",
")",
"else",
":",
"return",
"'no behaviour running'"
] |
End the current behaviour and run a named behaviour.
:param name: the name of the behaviour to run
:type name: str
|
[
"End",
"the",
"current",
"behaviour",
"and",
"run",
"a",
"named",
"behaviour",
"."
] |
404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4
|
https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/boatd_client.py#L190-L202
|
240,042
|
klmitch/appathy
|
appathy/types.py
|
register_types
|
def register_types(name, *types):
"""
Register a short name for one or more content types.
"""
type_names.setdefault(name, set())
for t in types:
# Redirecting the type
if t in media_types:
type_names[media_types[t]].discard(t)
# Save the mapping
media_types[t] = name
type_names[name].add(t)
|
python
|
def register_types(name, *types):
"""
Register a short name for one or more content types.
"""
type_names.setdefault(name, set())
for t in types:
# Redirecting the type
if t in media_types:
type_names[media_types[t]].discard(t)
# Save the mapping
media_types[t] = name
type_names[name].add(t)
|
[
"def",
"register_types",
"(",
"name",
",",
"*",
"types",
")",
":",
"type_names",
".",
"setdefault",
"(",
"name",
",",
"set",
"(",
")",
")",
"for",
"t",
"in",
"types",
":",
"# Redirecting the type",
"if",
"t",
"in",
"media_types",
":",
"type_names",
"[",
"media_types",
"[",
"t",
"]",
"]",
".",
"discard",
"(",
"t",
")",
"# Save the mapping",
"media_types",
"[",
"t",
"]",
"=",
"name",
"type_names",
"[",
"name",
"]",
".",
"add",
"(",
"t",
")"
] |
Register a short name for one or more content types.
|
[
"Register",
"a",
"short",
"name",
"for",
"one",
"or",
"more",
"content",
"types",
"."
] |
a10aa7d21d38622e984a8fe106ab37114af90dc2
|
https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/types.py#L141-L154
|
240,043
|
klmitch/appathy
|
appathy/types.py
|
Translators.get_types
|
def get_types(self):
"""
Retrieve a set of all recognized content types for this
translator object.
"""
# Convert translators into a set of content types
content_types = set()
for name in self.translators:
content_types |= type_names[name]
return content_types
|
python
|
def get_types(self):
"""
Retrieve a set of all recognized content types for this
translator object.
"""
# Convert translators into a set of content types
content_types = set()
for name in self.translators:
content_types |= type_names[name]
return content_types
|
[
"def",
"get_types",
"(",
"self",
")",
":",
"# Convert translators into a set of content types",
"content_types",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"self",
".",
"translators",
":",
"content_types",
"|=",
"type_names",
"[",
"name",
"]",
"return",
"content_types"
] |
Retrieve a set of all recognized content types for this
translator object.
|
[
"Retrieve",
"a",
"set",
"of",
"all",
"recognized",
"content",
"types",
"for",
"this",
"translator",
"object",
"."
] |
a10aa7d21d38622e984a8fe106ab37114af90dc2
|
https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/types.py#L58-L69
|
240,044
|
GetRektByMe/Raitonoberu
|
Raitonoberu/raitonoberu.py
|
Raitonoberu.get_search_page
|
async def get_search_page(self, term: str):
"""Get search page.
This function will get the first link from the search term we do on term and then
it will return the link we want to parse from.
:param term: Light Novel to Search For
"""
# Uses the BASEURL and also builds link for the page we want using the term given
params = {'s': term, 'post_type': 'seriesplan'}
async with self.session.get(self.BASEURL, params=params) as response:
# If the response is 200 OK
if response.status == 200:
search = BeautifulSoup(await response.text(), 'lxml')
# Return the link that we need
return search.find('a', class_='w-blog-entry-link').get('href')
else:
# Raise an error with the response status
raise aiohttp.ClientResponseError(response.status)
|
python
|
async def get_search_page(self, term: str):
"""Get search page.
This function will get the first link from the search term we do on term and then
it will return the link we want to parse from.
:param term: Light Novel to Search For
"""
# Uses the BASEURL and also builds link for the page we want using the term given
params = {'s': term, 'post_type': 'seriesplan'}
async with self.session.get(self.BASEURL, params=params) as response:
# If the response is 200 OK
if response.status == 200:
search = BeautifulSoup(await response.text(), 'lxml')
# Return the link that we need
return search.find('a', class_='w-blog-entry-link').get('href')
else:
# Raise an error with the response status
raise aiohttp.ClientResponseError(response.status)
|
[
"async",
"def",
"get_search_page",
"(",
"self",
",",
"term",
":",
"str",
")",
":",
"# Uses the BASEURL and also builds link for the page we want using the term given",
"params",
"=",
"{",
"'s'",
":",
"term",
",",
"'post_type'",
":",
"'seriesplan'",
"}",
"async",
"with",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"BASEURL",
",",
"params",
"=",
"params",
")",
"as",
"response",
":",
"# If the response is 200 OK",
"if",
"response",
".",
"status",
"==",
"200",
":",
"search",
"=",
"BeautifulSoup",
"(",
"await",
"response",
".",
"text",
"(",
")",
",",
"'lxml'",
")",
"# Return the link that we need",
"return",
"search",
".",
"find",
"(",
"'a'",
",",
"class_",
"=",
"'w-blog-entry-link'",
")",
".",
"get",
"(",
"'href'",
")",
"else",
":",
"# Raise an error with the response status",
"raise",
"aiohttp",
".",
"ClientResponseError",
"(",
"response",
".",
"status",
")"
] |
Get search page.
This function will get the first link from the search term we do on term and then
it will return the link we want to parse from.
:param term: Light Novel to Search For
|
[
"Get",
"search",
"page",
"."
] |
c35f83cb1c5268b7e641146bc8c6139fbc10e20f
|
https://github.com/GetRektByMe/Raitonoberu/blob/c35f83cb1c5268b7e641146bc8c6139fbc10e20f/Raitonoberu/raitonoberu.py#L20-L38
|
240,045
|
GetRektByMe/Raitonoberu
|
Raitonoberu/raitonoberu.py
|
Raitonoberu._get_aliases
|
def _get_aliases(parse_info):
"""get aliases from parse info.
:param parse_info: Parsed info from html soup.
"""
return [
div.string.strip()
for div in parse_info.find('div', id='editassociated')
if div.string is not None
]
|
python
|
def _get_aliases(parse_info):
"""get aliases from parse info.
:param parse_info: Parsed info from html soup.
"""
return [
div.string.strip()
for div in parse_info.find('div', id='editassociated')
if div.string is not None
]
|
[
"def",
"_get_aliases",
"(",
"parse_info",
")",
":",
"return",
"[",
"div",
".",
"string",
".",
"strip",
"(",
")",
"for",
"div",
"in",
"parse_info",
".",
"find",
"(",
"'div'",
",",
"id",
"=",
"'editassociated'",
")",
"if",
"div",
".",
"string",
"is",
"not",
"None",
"]"
] |
get aliases from parse info.
:param parse_info: Parsed info from html soup.
|
[
"get",
"aliases",
"from",
"parse",
"info",
"."
] |
c35f83cb1c5268b7e641146bc8c6139fbc10e20f
|
https://github.com/GetRektByMe/Raitonoberu/blob/c35f83cb1c5268b7e641146bc8c6139fbc10e20f/Raitonoberu/raitonoberu.py#L57-L66
|
240,046
|
GetRektByMe/Raitonoberu
|
Raitonoberu/raitonoberu.py
|
Raitonoberu._get_related_series
|
def _get_related_series(parse_info):
"""get related_series from parse info.
:param parse_info: Parsed info from html soup.
"""
seriesother_tags = [x for x in parse_info.select('h5.seriesother')]
sibling_tag = [x for x in seriesother_tags if x.text == 'Related Series'][0]
siblings_tag = list(sibling_tag.next_siblings)
# filter valid tag
# valid tag is all tag before following tag
# <h5 class="seriesother">Recommendations</h5>
valid_tag = []
keypoint_found = False
for x in siblings_tag:
# change keypoint if condition match
if x.name == 'h5' and x.attrs['class'] == ['seriesother']:
keypoint_found = True
if not keypoint_found and x.strip is not None:
if x.strip():
valid_tag.append(x)
elif not keypoint_found:
valid_tag.append(x)
# only one item found and it is 'N/A
if len(valid_tag) == 1:
if valid_tag[0].strip() == 'N/A':
return None
# items are combination between bs4 and text
# merge and return them as list of text
if len(valid_tag) % 2 == 0:
zipped_list = zip(valid_tag[::2], valid_tag[1::2])
result = []
for x in zipped_list:
result.append('{} {}'.format(x[0].text, x[1]))
return result
raise ValueError("Valid tag isn't recognizeable.\n{}".format("\n".join(valid_tag)))
|
python
|
def _get_related_series(parse_info):
"""get related_series from parse info.
:param parse_info: Parsed info from html soup.
"""
seriesother_tags = [x for x in parse_info.select('h5.seriesother')]
sibling_tag = [x for x in seriesother_tags if x.text == 'Related Series'][0]
siblings_tag = list(sibling_tag.next_siblings)
# filter valid tag
# valid tag is all tag before following tag
# <h5 class="seriesother">Recommendations</h5>
valid_tag = []
keypoint_found = False
for x in siblings_tag:
# change keypoint if condition match
if x.name == 'h5' and x.attrs['class'] == ['seriesother']:
keypoint_found = True
if not keypoint_found and x.strip is not None:
if x.strip():
valid_tag.append(x)
elif not keypoint_found:
valid_tag.append(x)
# only one item found and it is 'N/A
if len(valid_tag) == 1:
if valid_tag[0].strip() == 'N/A':
return None
# items are combination between bs4 and text
# merge and return them as list of text
if len(valid_tag) % 2 == 0:
zipped_list = zip(valid_tag[::2], valid_tag[1::2])
result = []
for x in zipped_list:
result.append('{} {}'.format(x[0].text, x[1]))
return result
raise ValueError("Valid tag isn't recognizeable.\n{}".format("\n".join(valid_tag)))
|
[
"def",
"_get_related_series",
"(",
"parse_info",
")",
":",
"seriesother_tags",
"=",
"[",
"x",
"for",
"x",
"in",
"parse_info",
".",
"select",
"(",
"'h5.seriesother'",
")",
"]",
"sibling_tag",
"=",
"[",
"x",
"for",
"x",
"in",
"seriesother_tags",
"if",
"x",
".",
"text",
"==",
"'Related Series'",
"]",
"[",
"0",
"]",
"siblings_tag",
"=",
"list",
"(",
"sibling_tag",
".",
"next_siblings",
")",
"# filter valid tag",
"# valid tag is all tag before following tag",
"# <h5 class=\"seriesother\">Recommendations</h5>",
"valid_tag",
"=",
"[",
"]",
"keypoint_found",
"=",
"False",
"for",
"x",
"in",
"siblings_tag",
":",
"# change keypoint if condition match",
"if",
"x",
".",
"name",
"==",
"'h5'",
"and",
"x",
".",
"attrs",
"[",
"'class'",
"]",
"==",
"[",
"'seriesother'",
"]",
":",
"keypoint_found",
"=",
"True",
"if",
"not",
"keypoint_found",
"and",
"x",
".",
"strip",
"is",
"not",
"None",
":",
"if",
"x",
".",
"strip",
"(",
")",
":",
"valid_tag",
".",
"append",
"(",
"x",
")",
"elif",
"not",
"keypoint_found",
":",
"valid_tag",
".",
"append",
"(",
"x",
")",
"# only one item found and it is 'N/A",
"if",
"len",
"(",
"valid_tag",
")",
"==",
"1",
":",
"if",
"valid_tag",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"==",
"'N/A'",
":",
"return",
"None",
"# items are combination between bs4 and text",
"# merge and return them as list of text",
"if",
"len",
"(",
"valid_tag",
")",
"%",
"2",
"==",
"0",
":",
"zipped_list",
"=",
"zip",
"(",
"valid_tag",
"[",
":",
":",
"2",
"]",
",",
"valid_tag",
"[",
"1",
":",
":",
"2",
"]",
")",
"result",
"=",
"[",
"]",
"for",
"x",
"in",
"zipped_list",
":",
"result",
".",
"append",
"(",
"'{} {}'",
".",
"format",
"(",
"x",
"[",
"0",
"]",
".",
"text",
",",
"x",
"[",
"1",
"]",
")",
")",
"return",
"result",
"raise",
"ValueError",
"(",
"\"Valid tag isn't recognizeable.\\n{}\"",
".",
"format",
"(",
"\"\\n\"",
".",
"join",
"(",
"valid_tag",
")",
")",
")"
] |
get related_series from parse info.
:param parse_info: Parsed info from html soup.
|
[
"get",
"related_series",
"from",
"parse",
"info",
"."
] |
c35f83cb1c5268b7e641146bc8c6139fbc10e20f
|
https://github.com/GetRektByMe/Raitonoberu/blob/c35f83cb1c5268b7e641146bc8c6139fbc10e20f/Raitonoberu/raitonoberu.py#L69-L108
|
240,047
|
shreyaspotnis/rampage
|
rampage/daq/gpib.py
|
Aglient33250A.set_fm_ext
|
def set_fm_ext(self, freq, amplitude, peak_freq_dev=None,
output_state=True):
"""Sets the func generator to frequency modulation with external modulation.
freq is the carrier frequency in Hz."""
if peak_freq_dev is None:
peak_freq_dev = freq
commands = ['FUNC SIN', # set to output sine functions
'FM:STAT ON',
'FREQ {0}'.format(freq),
'FM:SOUR EXT',
# 'FM:FREQ {0}'.format(freq),
'FM:DEV {0}'.format(peak_freq_dev),
'VOLT {0}'.format(amplitude),
'VOLT:OFFS 0'] # set to frequency modulation
if output_state is True:
commands.append('OUTP ON')
else:
commands.append('OUTP OFF')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
python
|
def set_fm_ext(self, freq, amplitude, peak_freq_dev=None,
output_state=True):
"""Sets the func generator to frequency modulation with external modulation.
freq is the carrier frequency in Hz."""
if peak_freq_dev is None:
peak_freq_dev = freq
commands = ['FUNC SIN', # set to output sine functions
'FM:STAT ON',
'FREQ {0}'.format(freq),
'FM:SOUR EXT',
# 'FM:FREQ {0}'.format(freq),
'FM:DEV {0}'.format(peak_freq_dev),
'VOLT {0}'.format(amplitude),
'VOLT:OFFS 0'] # set to frequency modulation
if output_state is True:
commands.append('OUTP ON')
else:
commands.append('OUTP OFF')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
[
"def",
"set_fm_ext",
"(",
"self",
",",
"freq",
",",
"amplitude",
",",
"peak_freq_dev",
"=",
"None",
",",
"output_state",
"=",
"True",
")",
":",
"if",
"peak_freq_dev",
"is",
"None",
":",
"peak_freq_dev",
"=",
"freq",
"commands",
"=",
"[",
"'FUNC SIN'",
",",
"# set to output sine functions",
"'FM:STAT ON'",
",",
"'FREQ {0}'",
".",
"format",
"(",
"freq",
")",
",",
"'FM:SOUR EXT'",
",",
"# 'FM:FREQ {0}'.format(freq),",
"'FM:DEV {0}'",
".",
"format",
"(",
"peak_freq_dev",
")",
",",
"'VOLT {0}'",
".",
"format",
"(",
"amplitude",
")",
",",
"'VOLT:OFFS 0'",
"]",
"# set to frequency modulation",
"if",
"output_state",
"is",
"True",
":",
"commands",
".",
"append",
"(",
"'OUTP ON'",
")",
"else",
":",
"commands",
".",
"append",
"(",
"'OUTP OFF'",
")",
"command_string",
"=",
"'\\n'",
".",
"join",
"(",
"commands",
")",
"print_string",
"=",
"'\\n\\t'",
"+",
"command_string",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"logging",
".",
"info",
"(",
"print_string",
")",
"self",
".",
"instr",
".",
"write",
"(",
"command_string",
")"
] |
Sets the func generator to frequency modulation with external modulation.
freq is the carrier frequency in Hz.
|
[
"Sets",
"the",
"func",
"generator",
"to",
"frequency",
"modulation",
"with",
"external",
"modulation",
".",
"freq",
"is",
"the",
"carrier",
"frequency",
"in",
"Hz",
"."
] |
e2565aef7ee16ee06523de975e8aa41aca14e3b2
|
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/gpib.py#L34-L56
|
240,048
|
shreyaspotnis/rampage
|
rampage/daq/gpib.py
|
Aglient33250A.set_burst
|
def set_burst(self, freq, amplitude, period, output_state=True):
"""Sets the func generator to burst mode with external trigerring."""
ncyc = int(period*freq)
commands = ['FUNC SIN',
'BURS:STAT ON',
'BURS:MODE TRIG', # external trigger
'TRIG:SOUR EXT',
'TRIG:SLOP POS',
'FREQ {0}'.format(freq),
'VOLT {0}'.format(amplitude),
'VOLT:OFFS 0',
'BURS:NCYC {0}'.format(ncyc)]
if output_state is True:
commands.append('OUTP ON')
else:
commands.append('OUTP OFF')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
python
|
def set_burst(self, freq, amplitude, period, output_state=True):
"""Sets the func generator to burst mode with external trigerring."""
ncyc = int(period*freq)
commands = ['FUNC SIN',
'BURS:STAT ON',
'BURS:MODE TRIG', # external trigger
'TRIG:SOUR EXT',
'TRIG:SLOP POS',
'FREQ {0}'.format(freq),
'VOLT {0}'.format(amplitude),
'VOLT:OFFS 0',
'BURS:NCYC {0}'.format(ncyc)]
if output_state is True:
commands.append('OUTP ON')
else:
commands.append('OUTP OFF')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
[
"def",
"set_burst",
"(",
"self",
",",
"freq",
",",
"amplitude",
",",
"period",
",",
"output_state",
"=",
"True",
")",
":",
"ncyc",
"=",
"int",
"(",
"period",
"*",
"freq",
")",
"commands",
"=",
"[",
"'FUNC SIN'",
",",
"'BURS:STAT ON'",
",",
"'BURS:MODE TRIG'",
",",
"# external trigger",
"'TRIG:SOUR EXT'",
",",
"'TRIG:SLOP POS'",
",",
"'FREQ {0}'",
".",
"format",
"(",
"freq",
")",
",",
"'VOLT {0}'",
".",
"format",
"(",
"amplitude",
")",
",",
"'VOLT:OFFS 0'",
",",
"'BURS:NCYC {0}'",
".",
"format",
"(",
"ncyc",
")",
"]",
"if",
"output_state",
"is",
"True",
":",
"commands",
".",
"append",
"(",
"'OUTP ON'",
")",
"else",
":",
"commands",
".",
"append",
"(",
"'OUTP OFF'",
")",
"command_string",
"=",
"'\\n'",
".",
"join",
"(",
"commands",
")",
"print_string",
"=",
"'\\n\\t'",
"+",
"command_string",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"logging",
".",
"info",
"(",
"print_string",
")",
"self",
".",
"instr",
".",
"write",
"(",
"command_string",
")"
] |
Sets the func generator to burst mode with external trigerring.
|
[
"Sets",
"the",
"func",
"generator",
"to",
"burst",
"mode",
"with",
"external",
"trigerring",
"."
] |
e2565aef7ee16ee06523de975e8aa41aca14e3b2
|
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/gpib.py#L59-L80
|
240,049
|
shreyaspotnis/rampage
|
rampage/daq/gpib.py
|
Aglient33250A.set_arbitrary
|
def set_arbitrary(self, freq, low_volt, high_volt, output_state=True):
"""Programs the function generator to output the arbitrary waveform."""
commands = ['FUNC USER',
'BURS:STAT OFF',
'SWE:STAT OFF',
'FM:STAT OFF',
'FREQ {0}'.format(freq),
'VOLT:HIGH {0}'.format(high_volt),
'VOLT:LOW {0}'.format(low_volt),
]
if output_state is True:
commands.append('OUTP ON')
else:
commands.append('OUTP OFF')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
python
|
def set_arbitrary(self, freq, low_volt, high_volt, output_state=True):
"""Programs the function generator to output the arbitrary waveform."""
commands = ['FUNC USER',
'BURS:STAT OFF',
'SWE:STAT OFF',
'FM:STAT OFF',
'FREQ {0}'.format(freq),
'VOLT:HIGH {0}'.format(high_volt),
'VOLT:LOW {0}'.format(low_volt),
]
if output_state is True:
commands.append('OUTP ON')
else:
commands.append('OUTP OFF')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
[
"def",
"set_arbitrary",
"(",
"self",
",",
"freq",
",",
"low_volt",
",",
"high_volt",
",",
"output_state",
"=",
"True",
")",
":",
"commands",
"=",
"[",
"'FUNC USER'",
",",
"'BURS:STAT OFF'",
",",
"'SWE:STAT OFF'",
",",
"'FM:STAT OFF'",
",",
"'FREQ {0}'",
".",
"format",
"(",
"freq",
")",
",",
"'VOLT:HIGH {0}'",
".",
"format",
"(",
"high_volt",
")",
",",
"'VOLT:LOW {0}'",
".",
"format",
"(",
"low_volt",
")",
",",
"]",
"if",
"output_state",
"is",
"True",
":",
"commands",
".",
"append",
"(",
"'OUTP ON'",
")",
"else",
":",
"commands",
".",
"append",
"(",
"'OUTP OFF'",
")",
"command_string",
"=",
"'\\n'",
".",
"join",
"(",
"commands",
")",
"print_string",
"=",
"'\\n\\t'",
"+",
"command_string",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"logging",
".",
"info",
"(",
"print_string",
")",
"self",
".",
"instr",
".",
"write",
"(",
"command_string",
")"
] |
Programs the function generator to output the arbitrary waveform.
|
[
"Programs",
"the",
"function",
"generator",
"to",
"output",
"the",
"arbitrary",
"waveform",
"."
] |
e2565aef7ee16ee06523de975e8aa41aca14e3b2
|
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/gpib.py#L128-L146
|
240,050
|
shreyaspotnis/rampage
|
rampage/daq/gpib.py
|
SRSSG384.set_continuous
|
def set_continuous(self, freq, amplitude, offset, output_state=True):
"""Programs the Stanford MW function generator to output a continuous sine wave.
External 'triggering' is accomplished using the MW switch."""
commands = ['MODL 0', #disable any modulation
'FREQ {0}'.format(freq)
]
if freq > 4.05e9:
commands.append('AMPH {0}'.format(amplitude)) #set rear RF doubler amplitude
if offset > 0.0:
print('HIGH FREQUENCY OUTPUT IS AC ONLY')
if output_state is True:
commands.append('ENBH 1') #enable output
else:
commands.append('ENBH 0')
elif freq < 62.5e6:
commands.extend(['AMPL {0}'.format(amplitude), 'OFSL {0}'.format(offset)]) #set front BNC amplitude
if output_state is True:
commands.append('ENBL 1') #enable output
else:
commands.append('ENBL 0')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
python
|
def set_continuous(self, freq, amplitude, offset, output_state=True):
"""Programs the Stanford MW function generator to output a continuous sine wave.
External 'triggering' is accomplished using the MW switch."""
commands = ['MODL 0', #disable any modulation
'FREQ {0}'.format(freq)
]
if freq > 4.05e9:
commands.append('AMPH {0}'.format(amplitude)) #set rear RF doubler amplitude
if offset > 0.0:
print('HIGH FREQUENCY OUTPUT IS AC ONLY')
if output_state is True:
commands.append('ENBH 1') #enable output
else:
commands.append('ENBH 0')
elif freq < 62.5e6:
commands.extend(['AMPL {0}'.format(amplitude), 'OFSL {0}'.format(offset)]) #set front BNC amplitude
if output_state is True:
commands.append('ENBL 1') #enable output
else:
commands.append('ENBL 0')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
[
"def",
"set_continuous",
"(",
"self",
",",
"freq",
",",
"amplitude",
",",
"offset",
",",
"output_state",
"=",
"True",
")",
":",
"commands",
"=",
"[",
"'MODL 0'",
",",
"#disable any modulation",
"'FREQ {0}'",
".",
"format",
"(",
"freq",
")",
"]",
"if",
"freq",
">",
"4.05e9",
":",
"commands",
".",
"append",
"(",
"'AMPH {0}'",
".",
"format",
"(",
"amplitude",
")",
")",
"#set rear RF doubler amplitude",
"if",
"offset",
">",
"0.0",
":",
"print",
"(",
"'HIGH FREQUENCY OUTPUT IS AC ONLY'",
")",
"if",
"output_state",
"is",
"True",
":",
"commands",
".",
"append",
"(",
"'ENBH 1'",
")",
"#enable output",
"else",
":",
"commands",
".",
"append",
"(",
"'ENBH 0'",
")",
"elif",
"freq",
"<",
"62.5e6",
":",
"commands",
".",
"extend",
"(",
"[",
"'AMPL {0}'",
".",
"format",
"(",
"amplitude",
")",
",",
"'OFSL {0}'",
".",
"format",
"(",
"offset",
")",
"]",
")",
"#set front BNC amplitude",
"if",
"output_state",
"is",
"True",
":",
"commands",
".",
"append",
"(",
"'ENBL 1'",
")",
"#enable output",
"else",
":",
"commands",
".",
"append",
"(",
"'ENBL 0'",
")",
"command_string",
"=",
"'\\n'",
".",
"join",
"(",
"commands",
")",
"print_string",
"=",
"'\\n\\t'",
"+",
"command_string",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"logging",
".",
"info",
"(",
"print_string",
")",
"self",
".",
"instr",
".",
"write",
"(",
"command_string",
")"
] |
Programs the Stanford MW function generator to output a continuous sine wave.
External 'triggering' is accomplished using the MW switch.
|
[
"Programs",
"the",
"Stanford",
"MW",
"function",
"generator",
"to",
"output",
"a",
"continuous",
"sine",
"wave",
".",
"External",
"triggering",
"is",
"accomplished",
"using",
"the",
"MW",
"switch",
"."
] |
e2565aef7ee16ee06523de975e8aa41aca14e3b2
|
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/gpib.py#L333-L358
|
240,051
|
shreyaspotnis/rampage
|
rampage/daq/gpib.py
|
SRSSG384.set_freqsweep_ext
|
def set_freqsweep_ext(self, amplitude, sweep_low_end, sweep_high_end, offset=0.0, output_state=True):
"""Sets the Stanford MW function generator to freq modulation with external modulation.
freq is the carrier frequency in Hz."""
sweep_deviation = round(abs(sweep_low_end - sweep_high_end)/2.0,6)
freq = sweep_low_end + sweep_deviation
commands = ['TYPE 3', #set to sweep
'SFNC 5', #external modulation
'FREQ {0}'.format(freq),
'SDEV {0}'.format(sweep_deviation),
'MODL 1' #enable modulation
]
if freq > 4.05e9:
commands.append('AMPH {0}'.format(amplitude)) #set rear RF doubler amplitude
if offset > 0.0:
print('HIGH FREQUENCY OUTPUT IS AC ONLY')
if output_state is True:
commands.append('ENBH 1') #enable output
else:
commands.append('ENBH 0')
elif freq < 62.5e6:
commands.extend(['AMPL {0}'.format(amplitude), 'OFSL {0}'.format(offset)]) #set front BNC amplitude
if output_state is True:
commands.append('ENBL 1') #enable output
else:
commands.append('ENBL 0')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
python
|
def set_freqsweep_ext(self, amplitude, sweep_low_end, sweep_high_end, offset=0.0, output_state=True):
"""Sets the Stanford MW function generator to freq modulation with external modulation.
freq is the carrier frequency in Hz."""
sweep_deviation = round(abs(sweep_low_end - sweep_high_end)/2.0,6)
freq = sweep_low_end + sweep_deviation
commands = ['TYPE 3', #set to sweep
'SFNC 5', #external modulation
'FREQ {0}'.format(freq),
'SDEV {0}'.format(sweep_deviation),
'MODL 1' #enable modulation
]
if freq > 4.05e9:
commands.append('AMPH {0}'.format(amplitude)) #set rear RF doubler amplitude
if offset > 0.0:
print('HIGH FREQUENCY OUTPUT IS AC ONLY')
if output_state is True:
commands.append('ENBH 1') #enable output
else:
commands.append('ENBH 0')
elif freq < 62.5e6:
commands.extend(['AMPL {0}'.format(amplitude), 'OFSL {0}'.format(offset)]) #set front BNC amplitude
if output_state is True:
commands.append('ENBL 1') #enable output
else:
commands.append('ENBL 0')
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
self.instr.write(command_string)
|
[
"def",
"set_freqsweep_ext",
"(",
"self",
",",
"amplitude",
",",
"sweep_low_end",
",",
"sweep_high_end",
",",
"offset",
"=",
"0.0",
",",
"output_state",
"=",
"True",
")",
":",
"sweep_deviation",
"=",
"round",
"(",
"abs",
"(",
"sweep_low_end",
"-",
"sweep_high_end",
")",
"/",
"2.0",
",",
"6",
")",
"freq",
"=",
"sweep_low_end",
"+",
"sweep_deviation",
"commands",
"=",
"[",
"'TYPE 3'",
",",
"#set to sweep",
"'SFNC 5'",
",",
"#external modulation",
"'FREQ {0}'",
".",
"format",
"(",
"freq",
")",
",",
"'SDEV {0}'",
".",
"format",
"(",
"sweep_deviation",
")",
",",
"'MODL 1'",
"#enable modulation",
"]",
"if",
"freq",
">",
"4.05e9",
":",
"commands",
".",
"append",
"(",
"'AMPH {0}'",
".",
"format",
"(",
"amplitude",
")",
")",
"#set rear RF doubler amplitude",
"if",
"offset",
">",
"0.0",
":",
"print",
"(",
"'HIGH FREQUENCY OUTPUT IS AC ONLY'",
")",
"if",
"output_state",
"is",
"True",
":",
"commands",
".",
"append",
"(",
"'ENBH 1'",
")",
"#enable output",
"else",
":",
"commands",
".",
"append",
"(",
"'ENBH 0'",
")",
"elif",
"freq",
"<",
"62.5e6",
":",
"commands",
".",
"extend",
"(",
"[",
"'AMPL {0}'",
".",
"format",
"(",
"amplitude",
")",
",",
"'OFSL {0}'",
".",
"format",
"(",
"offset",
")",
"]",
")",
"#set front BNC amplitude",
"if",
"output_state",
"is",
"True",
":",
"commands",
".",
"append",
"(",
"'ENBL 1'",
")",
"#enable output",
"else",
":",
"commands",
".",
"append",
"(",
"'ENBL 0'",
")",
"command_string",
"=",
"'\\n'",
".",
"join",
"(",
"commands",
")",
"print_string",
"=",
"'\\n\\t'",
"+",
"command_string",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"logging",
".",
"info",
"(",
"print_string",
")",
"self",
".",
"instr",
".",
"write",
"(",
"command_string",
")"
] |
Sets the Stanford MW function generator to freq modulation with external modulation.
freq is the carrier frequency in Hz.
|
[
"Sets",
"the",
"Stanford",
"MW",
"function",
"generator",
"to",
"freq",
"modulation",
"with",
"external",
"modulation",
".",
"freq",
"is",
"the",
"carrier",
"frequency",
"in",
"Hz",
"."
] |
e2565aef7ee16ee06523de975e8aa41aca14e3b2
|
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/gpib.py#L424-L454
|
240,052
|
shreyaspotnis/rampage
|
rampage/daq/gpib.py
|
SRSSG384.disable_all
|
def disable_all(self, disable):
"""Disables all modulation and outputs of the Standford MW func. generator"""
commands = ['ENBH 0', #disable high freq. rear output
'ENBL 0', #disable low freq. front bnc
'MODL 0' #disable modulation
]
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
if disable:
self.instr.write(command_string)
|
python
|
def disable_all(self, disable):
"""Disables all modulation and outputs of the Standford MW func. generator"""
commands = ['ENBH 0', #disable high freq. rear output
'ENBL 0', #disable low freq. front bnc
'MODL 0' #disable modulation
]
command_string = '\n'.join(commands)
print_string = '\n\t' + command_string.replace('\n', '\n\t')
logging.info(print_string)
if disable:
self.instr.write(command_string)
|
[
"def",
"disable_all",
"(",
"self",
",",
"disable",
")",
":",
"commands",
"=",
"[",
"'ENBH 0'",
",",
"#disable high freq. rear output",
"'ENBL 0'",
",",
"#disable low freq. front bnc",
"'MODL 0'",
"#disable modulation",
"]",
"command_string",
"=",
"'\\n'",
".",
"join",
"(",
"commands",
")",
"print_string",
"=",
"'\\n\\t'",
"+",
"command_string",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"logging",
".",
"info",
"(",
"print_string",
")",
"if",
"disable",
":",
"self",
".",
"instr",
".",
"write",
"(",
"command_string",
")"
] |
Disables all modulation and outputs of the Standford MW func. generator
|
[
"Disables",
"all",
"modulation",
"and",
"outputs",
"of",
"the",
"Standford",
"MW",
"func",
".",
"generator"
] |
e2565aef7ee16ee06523de975e8aa41aca14e3b2
|
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/gpib.py#L479-L489
|
240,053
|
shreyaspotnis/rampage
|
rampage/daq/gpib.py
|
RigolDG1022Z.set_continuous
|
def set_continuous(self, freq, amplitude, offset, phase, channel=2):
"""Programs the function generator to output a continuous sine wave."""
commands = [':SOUR{0}:APPL:SIN '.format(channel),
'{0},'.format(freq),
'{0},'.format(amplitude),
'{0},'.format(offset),
'{0}'.format(phase),
]
command_string = ''.join(commands)
logging.info(command_string)
self.instr.write(command_string)
|
python
|
def set_continuous(self, freq, amplitude, offset, phase, channel=2):
"""Programs the function generator to output a continuous sine wave."""
commands = [':SOUR{0}:APPL:SIN '.format(channel),
'{0},'.format(freq),
'{0},'.format(amplitude),
'{0},'.format(offset),
'{0}'.format(phase),
]
command_string = ''.join(commands)
logging.info(command_string)
self.instr.write(command_string)
|
[
"def",
"set_continuous",
"(",
"self",
",",
"freq",
",",
"amplitude",
",",
"offset",
",",
"phase",
",",
"channel",
"=",
"2",
")",
":",
"commands",
"=",
"[",
"':SOUR{0}:APPL:SIN '",
".",
"format",
"(",
"channel",
")",
",",
"'{0},'",
".",
"format",
"(",
"freq",
")",
",",
"'{0},'",
".",
"format",
"(",
"amplitude",
")",
",",
"'{0},'",
".",
"format",
"(",
"offset",
")",
",",
"'{0}'",
".",
"format",
"(",
"phase",
")",
",",
"]",
"command_string",
"=",
"''",
".",
"join",
"(",
"commands",
")",
"logging",
".",
"info",
"(",
"command_string",
")",
"self",
".",
"instr",
".",
"write",
"(",
"command_string",
")"
] |
Programs the function generator to output a continuous sine wave.
|
[
"Programs",
"the",
"function",
"generator",
"to",
"output",
"a",
"continuous",
"sine",
"wave",
"."
] |
e2565aef7ee16ee06523de975e8aa41aca14e3b2
|
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/gpib.py#L532-L543
|
240,054
|
JNRowe/jnrbase
|
jnrbase/pip_support.py
|
parse_requires
|
def parse_requires(__fname: str) -> List[str]:
"""Parse ``pip``-style requirements files.
This is a *very* naïve parser, but very few packages make use of the more
advanced features. Support for other features will be added only when
packages in the wild depend on them.
Args:
__fname: Base file to pass
Returns:
Parsed dependencies
"""
deps = []
with open(__fname) as req_file:
entries = [s.split('#')[0].strip() for s in req_file.readlines()]
for dep in entries:
if not dep:
continue
elif dep.startswith('-r '):
include = dep.split()[1]
if '/' not in include:
include = path.join(path.dirname(__fname), include)
deps.extend(parse_requires(include))
continue
elif ';' in dep:
dep, marker = [s.strip() for s in dep.split(';')]
# Support for other markers will be added when they’re actually
# found in the wild
match = re.fullmatch(r"""
(?:python_version) # Supported markers
\s*
(?:<=?|==|>=?) # Supported comparisons
\s*
(?P<quote>(?:'|"))(?:[\d\.]+)(?P=quote) # Test
""", marker, re.VERBOSE)
if not match:
raise ValueError('Invalid marker {!r}'.format(marker))
env = {
'__builtins__': {},
'python_version': '{}.{}'.format(*version_info[:2]),
}
if not eval(marker, env): # pylint: disable=eval-used
continue
deps.append(dep)
return deps
|
python
|
def parse_requires(__fname: str) -> List[str]:
"""Parse ``pip``-style requirements files.
This is a *very* naïve parser, but very few packages make use of the more
advanced features. Support for other features will be added only when
packages in the wild depend on them.
Args:
__fname: Base file to pass
Returns:
Parsed dependencies
"""
deps = []
with open(__fname) as req_file:
entries = [s.split('#')[0].strip() for s in req_file.readlines()]
for dep in entries:
if not dep:
continue
elif dep.startswith('-r '):
include = dep.split()[1]
if '/' not in include:
include = path.join(path.dirname(__fname), include)
deps.extend(parse_requires(include))
continue
elif ';' in dep:
dep, marker = [s.strip() for s in dep.split(';')]
# Support for other markers will be added when they’re actually
# found in the wild
match = re.fullmatch(r"""
(?:python_version) # Supported markers
\s*
(?:<=?|==|>=?) # Supported comparisons
\s*
(?P<quote>(?:'|"))(?:[\d\.]+)(?P=quote) # Test
""", marker, re.VERBOSE)
if not match:
raise ValueError('Invalid marker {!r}'.format(marker))
env = {
'__builtins__': {},
'python_version': '{}.{}'.format(*version_info[:2]),
}
if not eval(marker, env): # pylint: disable=eval-used
continue
deps.append(dep)
return deps
|
[
"def",
"parse_requires",
"(",
"__fname",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"deps",
"=",
"[",
"]",
"with",
"open",
"(",
"__fname",
")",
"as",
"req_file",
":",
"entries",
"=",
"[",
"s",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"req_file",
".",
"readlines",
"(",
")",
"]",
"for",
"dep",
"in",
"entries",
":",
"if",
"not",
"dep",
":",
"continue",
"elif",
"dep",
".",
"startswith",
"(",
"'-r '",
")",
":",
"include",
"=",
"dep",
".",
"split",
"(",
")",
"[",
"1",
"]",
"if",
"'/'",
"not",
"in",
"include",
":",
"include",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"__fname",
")",
",",
"include",
")",
"deps",
".",
"extend",
"(",
"parse_requires",
"(",
"include",
")",
")",
"continue",
"elif",
"';'",
"in",
"dep",
":",
"dep",
",",
"marker",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"dep",
".",
"split",
"(",
"';'",
")",
"]",
"# Support for other markers will be added when they’re actually",
"# found in the wild",
"match",
"=",
"re",
".",
"fullmatch",
"(",
"r\"\"\"\n (?:python_version) # Supported markers\n \\s*\n (?:<=?|==|>=?) # Supported comparisons\n \\s*\n (?P<quote>(?:'|\"))(?:[\\d\\.]+)(?P=quote) # Test\n \"\"\"",
",",
"marker",
",",
"re",
".",
"VERBOSE",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"'Invalid marker {!r}'",
".",
"format",
"(",
"marker",
")",
")",
"env",
"=",
"{",
"'__builtins__'",
":",
"{",
"}",
",",
"'python_version'",
":",
"'{}.{}'",
".",
"format",
"(",
"*",
"version_info",
"[",
":",
"2",
"]",
")",
",",
"}",
"if",
"not",
"eval",
"(",
"marker",
",",
"env",
")",
":",
"# pylint: disable=eval-used",
"continue",
"deps",
".",
"append",
"(",
"dep",
")",
"return",
"deps"
] |
Parse ``pip``-style requirements files.
This is a *very* naïve parser, but very few packages make use of the more
advanced features. Support for other features will be added only when
packages in the wild depend on them.
Args:
__fname: Base file to pass
Returns:
Parsed dependencies
|
[
"Parse",
"pip",
"-",
"style",
"requirements",
"files",
"."
] |
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
|
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/pip_support.py#L32-L76
|
240,055
|
rjw57/throw
|
throw/attachment_renderer.py
|
create_email
|
def create_email(filepaths, collection_name):
"""Create an email message object which implements the
email.message.Message interface and which has the files to be shared
attached to it.
"""
outer = MIMEMultipart()
outer.preamble = 'Here are some files for you'
def add_file_to_outer(path):
if not os.path.isfile(path):
return
# Guess the content type based on the file's extension. Encoding
# will be ignored, although we should check for simple things like
# gzip'd or compressed files.
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'image':
fp = open(path, 'rb')
msg = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(path, 'rb')
msg = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'text':
# We do this to catch cases where text files have
# an encoding we can't guess correctly.
try:
fp = open(path, 'r')
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
except UnicodeDecodeError:
fp = open(path, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
encoders.encode_base64(msg)
fp.close()
else:
fp = open(path, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(path))
outer.attach(msg)
outer.attach(MIMEText("Here are some files I've thrown at you."))
for path in filepaths:
add_file_to_outer(path)
return outer
|
python
|
def create_email(filepaths, collection_name):
"""Create an email message object which implements the
email.message.Message interface and which has the files to be shared
attached to it.
"""
outer = MIMEMultipart()
outer.preamble = 'Here are some files for you'
def add_file_to_outer(path):
if not os.path.isfile(path):
return
# Guess the content type based on the file's extension. Encoding
# will be ignored, although we should check for simple things like
# gzip'd or compressed files.
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'image':
fp = open(path, 'rb')
msg = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(path, 'rb')
msg = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'text':
# We do this to catch cases where text files have
# an encoding we can't guess correctly.
try:
fp = open(path, 'r')
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
except UnicodeDecodeError:
fp = open(path, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
encoders.encode_base64(msg)
fp.close()
else:
fp = open(path, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(path))
outer.attach(msg)
outer.attach(MIMEText("Here are some files I've thrown at you."))
for path in filepaths:
add_file_to_outer(path)
return outer
|
[
"def",
"create_email",
"(",
"filepaths",
",",
"collection_name",
")",
":",
"outer",
"=",
"MIMEMultipart",
"(",
")",
"outer",
".",
"preamble",
"=",
"'Here are some files for you'",
"def",
"add_file_to_outer",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"# Guess the content type based on the file's extension. Encoding",
"# will be ignored, although we should check for simple things like",
"# gzip'd or compressed files.",
"ctype",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"path",
")",
"if",
"ctype",
"is",
"None",
"or",
"encoding",
"is",
"not",
"None",
":",
"# No guess could be made, or the file is encoded (compressed), so",
"# use a generic bag-of-bits type.",
"ctype",
"=",
"'application/octet-stream'",
"maintype",
",",
"subtype",
"=",
"ctype",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"if",
"maintype",
"==",
"'image'",
":",
"fp",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"msg",
"=",
"MIMEImage",
"(",
"fp",
".",
"read",
"(",
")",
",",
"_subtype",
"=",
"subtype",
")",
"fp",
".",
"close",
"(",
")",
"elif",
"maintype",
"==",
"'audio'",
":",
"fp",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"msg",
"=",
"MIMEAudio",
"(",
"fp",
".",
"read",
"(",
")",
",",
"_subtype",
"=",
"subtype",
")",
"fp",
".",
"close",
"(",
")",
"elif",
"maintype",
"==",
"'text'",
":",
"# We do this to catch cases where text files have",
"# an encoding we can't guess correctly.",
"try",
":",
"fp",
"=",
"open",
"(",
"path",
",",
"'r'",
")",
"msg",
"=",
"MIMEText",
"(",
"fp",
".",
"read",
"(",
")",
",",
"_subtype",
"=",
"subtype",
")",
"fp",
".",
"close",
"(",
")",
"except",
"UnicodeDecodeError",
":",
"fp",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"msg",
"=",
"MIMEBase",
"(",
"maintype",
",",
"subtype",
")",
"msg",
".",
"set_payload",
"(",
"fp",
".",
"read",
"(",
")",
")",
"encoders",
".",
"encode_base64",
"(",
"msg",
")",
"fp",
".",
"close",
"(",
")",
"else",
":",
"fp",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"msg",
"=",
"MIMEBase",
"(",
"maintype",
",",
"subtype",
")",
"msg",
".",
"set_payload",
"(",
"fp",
".",
"read",
"(",
")",
")",
"fp",
".",
"close",
"(",
")",
"# Encode the payload using Base64",
"encoders",
".",
"encode_base64",
"(",
"msg",
")",
"# Set the filename parameter",
"msg",
".",
"add_header",
"(",
"'Content-Disposition'",
",",
"'attachment'",
",",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"outer",
".",
"attach",
"(",
"msg",
")",
"outer",
".",
"attach",
"(",
"MIMEText",
"(",
"\"Here are some files I've thrown at you.\"",
")",
")",
"for",
"path",
"in",
"filepaths",
":",
"add_file_to_outer",
"(",
"path",
")",
"return",
"outer"
] |
Create an email message object which implements the
email.message.Message interface and which has the files to be shared
attached to it.
|
[
"Create",
"an",
"email",
"message",
"object",
"which",
"implements",
"the",
"email",
".",
"message",
".",
"Message",
"interface",
"and",
"which",
"has",
"the",
"files",
"to",
"be",
"shared",
"attached",
"to",
"it",
"."
] |
74a7116362ba5b45635ab247472b25cfbdece4ee
|
https://github.com/rjw57/throw/blob/74a7116362ba5b45635ab247472b25cfbdece4ee/throw/attachment_renderer.py#L12-L74
|
240,056
|
ArtoLabs/SimpleSteem
|
simplesteem/makeconfig.py
|
MakeConfig.enter_config_value
|
def enter_config_value(self, key, default=""):
''' Prompts user for a value
'''
value = input('Please enter a value for ' + key + ': ')
if value:
return value
else:
return default
|
python
|
def enter_config_value(self, key, default=""):
''' Prompts user for a value
'''
value = input('Please enter a value for ' + key + ': ')
if value:
return value
else:
return default
|
[
"def",
"enter_config_value",
"(",
"self",
",",
"key",
",",
"default",
"=",
"\"\"",
")",
":",
"value",
"=",
"input",
"(",
"'Please enter a value for '",
"+",
"key",
"+",
"': '",
")",
"if",
"value",
":",
"return",
"value",
"else",
":",
"return",
"default"
] |
Prompts user for a value
|
[
"Prompts",
"user",
"for",
"a",
"value"
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/makeconfig.py#L54-L61
|
240,057
|
shaded-enmity/docker-hica
|
injectors/introspect_runtime.py
|
IntrospectRuntimeInjector._run_introspection
|
def _run_introspection(self, runtime='', whitelist=[], verbose=False):
""" Figure out which objects are opened by a test binary and are matched by the white list.
:param runtime: The binary to run.
:type runtime: str
:param whitelist: A list of regular expressions describing acceptable library names
:type whitelist: [str]
"""
found_objects = set()
try:
# Retrieve list of successfully opened objects
strace = subprocess.Popen(['strace', runtime], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
(_, stderr) = strace.communicate()
opened_objects = set()
for line in stderr.split('\n'):
if 'open' in line and 'ENOENT' not in line:
start = line.index('"')
end = line.index('"', start + 1)
opened_objects.add(line[start + 1:end])
# filter opened objects through white list.
for obj in opened_objects:
for wl in whitelist:
m = re.match('.*' + wl + '[\..*]?', obj)
if m:
found_objects.add(obj)
if verbose:
print('Found whitelisted {} at path {}'.format(wl, obj))
continue
except Exception as e:
print e
return found_objects
|
python
|
def _run_introspection(self, runtime='', whitelist=[], verbose=False):
""" Figure out which objects are opened by a test binary and are matched by the white list.
:param runtime: The binary to run.
:type runtime: str
:param whitelist: A list of regular expressions describing acceptable library names
:type whitelist: [str]
"""
found_objects = set()
try:
# Retrieve list of successfully opened objects
strace = subprocess.Popen(['strace', runtime], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
(_, stderr) = strace.communicate()
opened_objects = set()
for line in stderr.split('\n'):
if 'open' in line and 'ENOENT' not in line:
start = line.index('"')
end = line.index('"', start + 1)
opened_objects.add(line[start + 1:end])
# filter opened objects through white list.
for obj in opened_objects:
for wl in whitelist:
m = re.match('.*' + wl + '[\..*]?', obj)
if m:
found_objects.add(obj)
if verbose:
print('Found whitelisted {} at path {}'.format(wl, obj))
continue
except Exception as e:
print e
return found_objects
|
[
"def",
"_run_introspection",
"(",
"self",
",",
"runtime",
"=",
"''",
",",
"whitelist",
"=",
"[",
"]",
",",
"verbose",
"=",
"False",
")",
":",
"found_objects",
"=",
"set",
"(",
")",
"try",
":",
"# Retrieve list of successfully opened objects",
"strace",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'strace'",
",",
"runtime",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"(",
"_",
",",
"stderr",
")",
"=",
"strace",
".",
"communicate",
"(",
")",
"opened_objects",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"stderr",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"'open'",
"in",
"line",
"and",
"'ENOENT'",
"not",
"in",
"line",
":",
"start",
"=",
"line",
".",
"index",
"(",
"'\"'",
")",
"end",
"=",
"line",
".",
"index",
"(",
"'\"'",
",",
"start",
"+",
"1",
")",
"opened_objects",
".",
"add",
"(",
"line",
"[",
"start",
"+",
"1",
":",
"end",
"]",
")",
"# filter opened objects through white list.",
"for",
"obj",
"in",
"opened_objects",
":",
"for",
"wl",
"in",
"whitelist",
":",
"m",
"=",
"re",
".",
"match",
"(",
"'.*'",
"+",
"wl",
"+",
"'[\\..*]?'",
",",
"obj",
")",
"if",
"m",
":",
"found_objects",
".",
"add",
"(",
"obj",
")",
"if",
"verbose",
":",
"print",
"(",
"'Found whitelisted {} at path {}'",
".",
"format",
"(",
"wl",
",",
"obj",
")",
")",
"continue",
"except",
"Exception",
"as",
"e",
":",
"print",
"e",
"return",
"found_objects"
] |
Figure out which objects are opened by a test binary and are matched by the white list.
:param runtime: The binary to run.
:type runtime: str
:param whitelist: A list of regular expressions describing acceptable library names
:type whitelist: [str]
|
[
"Figure",
"out",
"which",
"objects",
"are",
"opened",
"by",
"a",
"test",
"binary",
"and",
"are",
"matched",
"by",
"the",
"white",
"list",
"."
] |
bc425586297e1eb228b70ee6fca8c499849ec87d
|
https://github.com/shaded-enmity/docker-hica/blob/bc425586297e1eb228b70ee6fca8c499849ec87d/injectors/introspect_runtime.py#L31-L63
|
240,058
|
shaded-enmity/docker-hica
|
injectors/introspect_runtime.py
|
IntrospectRuntimeInjector.__get_container_path
|
def __get_container_path(self, host_path):
""" A simple helper function to determine the path of a host library
inside the container
:param host_path: The path of the library on the host
:type host_path: str
"""
libname = os.path.split(host_path)[1]
return os.path.join(_container_lib_location, libname)
|
python
|
def __get_container_path(self, host_path):
""" A simple helper function to determine the path of a host library
inside the container
:param host_path: The path of the library on the host
:type host_path: str
"""
libname = os.path.split(host_path)[1]
return os.path.join(_container_lib_location, libname)
|
[
"def",
"__get_container_path",
"(",
"self",
",",
"host_path",
")",
":",
"libname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"host_path",
")",
"[",
"1",
"]",
"return",
"os",
".",
"path",
".",
"join",
"(",
"_container_lib_location",
",",
"libname",
")"
] |
A simple helper function to determine the path of a host library
inside the container
:param host_path: The path of the library on the host
:type host_path: str
|
[
"A",
"simple",
"helper",
"function",
"to",
"determine",
"the",
"path",
"of",
"a",
"host",
"library",
"inside",
"the",
"container"
] |
bc425586297e1eb228b70ee6fca8c499849ec87d
|
https://github.com/shaded-enmity/docker-hica/blob/bc425586297e1eb228b70ee6fca8c499849ec87d/injectors/introspect_runtime.py#L65-L73
|
240,059
|
csaez/wishlib
|
wishlib/si/__init__.py
|
inside_softimage
|
def inside_softimage():
"""Returns a boolean indicating if the code is executed inside softimage."""
try:
import maya
return False
except ImportError:
pass
try:
from win32com.client import Dispatch as disp
disp('XSI.Application')
return True
except:
return False
|
python
|
def inside_softimage():
"""Returns a boolean indicating if the code is executed inside softimage."""
try:
import maya
return False
except ImportError:
pass
try:
from win32com.client import Dispatch as disp
disp('XSI.Application')
return True
except:
return False
|
[
"def",
"inside_softimage",
"(",
")",
":",
"try",
":",
"import",
"maya",
"return",
"False",
"except",
"ImportError",
":",
"pass",
"try",
":",
"from",
"win32com",
".",
"client",
"import",
"Dispatch",
"as",
"disp",
"disp",
"(",
"'XSI.Application'",
")",
"return",
"True",
"except",
":",
"return",
"False"
] |
Returns a boolean indicating if the code is executed inside softimage.
|
[
"Returns",
"a",
"boolean",
"indicating",
"if",
"the",
"code",
"is",
"executed",
"inside",
"softimage",
"."
] |
c212fa7875006a332a4cefbf69885ced9647bc2f
|
https://github.com/csaez/wishlib/blob/c212fa7875006a332a4cefbf69885ced9647bc2f/wishlib/si/__init__.py#L4-L16
|
240,060
|
krukas/Trionyx
|
trionyx/navigation.py
|
Menu.add_item
|
def add_item(self, path, name, icon=None, url=None, order=None, permission=None, active_regex=None):
"""
Add new menu item to menu
:param path: Path of menu
:param name: Display name
:param icon: CSS icon
:param url: link to page
:param order: Sort order
:param permission:
:return:
"""
if self.root_item is None:
self.root_item = MenuItem('ROOT', 'ROOT')
root_item = self.root_item
current_path = ''
for node in path.split('/')[:-1]:
if not node:
continue
current_path = '/' + '{}/{}'.format(current_path, node).strip('/')
new_root = root_item.child_by_code(node)
if not new_root: # Create menu item if not exists
new_root = MenuItem(current_path, name=str(node).capitalize())
root_item.add_child(new_root)
root_item = new_root
new_item = MenuItem(path, name, icon, url, order, permission, active_regex)
current_item = root_item.child_by_code(path.split('/')[-1])
if current_item:
current_item.merge(new_item)
else:
root_item.add_child(new_item)
|
python
|
def add_item(self, path, name, icon=None, url=None, order=None, permission=None, active_regex=None):
"""
Add new menu item to menu
:param path: Path of menu
:param name: Display name
:param icon: CSS icon
:param url: link to page
:param order: Sort order
:param permission:
:return:
"""
if self.root_item is None:
self.root_item = MenuItem('ROOT', 'ROOT')
root_item = self.root_item
current_path = ''
for node in path.split('/')[:-1]:
if not node:
continue
current_path = '/' + '{}/{}'.format(current_path, node).strip('/')
new_root = root_item.child_by_code(node)
if not new_root: # Create menu item if not exists
new_root = MenuItem(current_path, name=str(node).capitalize())
root_item.add_child(new_root)
root_item = new_root
new_item = MenuItem(path, name, icon, url, order, permission, active_regex)
current_item = root_item.child_by_code(path.split('/')[-1])
if current_item:
current_item.merge(new_item)
else:
root_item.add_child(new_item)
|
[
"def",
"add_item",
"(",
"self",
",",
"path",
",",
"name",
",",
"icon",
"=",
"None",
",",
"url",
"=",
"None",
",",
"order",
"=",
"None",
",",
"permission",
"=",
"None",
",",
"active_regex",
"=",
"None",
")",
":",
"if",
"self",
".",
"root_item",
"is",
"None",
":",
"self",
".",
"root_item",
"=",
"MenuItem",
"(",
"'ROOT'",
",",
"'ROOT'",
")",
"root_item",
"=",
"self",
".",
"root_item",
"current_path",
"=",
"''",
"for",
"node",
"in",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
":",
"-",
"1",
"]",
":",
"if",
"not",
"node",
":",
"continue",
"current_path",
"=",
"'/'",
"+",
"'{}/{}'",
".",
"format",
"(",
"current_path",
",",
"node",
")",
".",
"strip",
"(",
"'/'",
")",
"new_root",
"=",
"root_item",
".",
"child_by_code",
"(",
"node",
")",
"if",
"not",
"new_root",
":",
"# Create menu item if not exists",
"new_root",
"=",
"MenuItem",
"(",
"current_path",
",",
"name",
"=",
"str",
"(",
"node",
")",
".",
"capitalize",
"(",
")",
")",
"root_item",
".",
"add_child",
"(",
"new_root",
")",
"root_item",
"=",
"new_root",
"new_item",
"=",
"MenuItem",
"(",
"path",
",",
"name",
",",
"icon",
",",
"url",
",",
"order",
",",
"permission",
",",
"active_regex",
")",
"current_item",
"=",
"root_item",
".",
"child_by_code",
"(",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
")",
"if",
"current_item",
":",
"current_item",
".",
"merge",
"(",
"new_item",
")",
"else",
":",
"root_item",
".",
"add_child",
"(",
"new_item",
")"
] |
Add new menu item to menu
:param path: Path of menu
:param name: Display name
:param icon: CSS icon
:param url: link to page
:param order: Sort order
:param permission:
:return:
|
[
"Add",
"new",
"menu",
"item",
"to",
"menu"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L82-L116
|
240,061
|
krukas/Trionyx
|
trionyx/navigation.py
|
MenuItem.merge
|
def merge(self, item):
"""Merge Menu item data"""
self.name = item.name
if item.icon:
self.icon = item.icon
if item.url:
self.url = item.url
if item.order:
self.order = item.order
if item.permission:
self.permission = item.permission
|
python
|
def merge(self, item):
"""Merge Menu item data"""
self.name = item.name
if item.icon:
self.icon = item.icon
if item.url:
self.url = item.url
if item.order:
self.order = item.order
if item.permission:
self.permission = item.permission
|
[
"def",
"merge",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"name",
"=",
"item",
".",
"name",
"if",
"item",
".",
"icon",
":",
"self",
".",
"icon",
"=",
"item",
".",
"icon",
"if",
"item",
".",
"url",
":",
"self",
".",
"url",
"=",
"item",
".",
"url",
"if",
"item",
".",
"order",
":",
"self",
".",
"order",
"=",
"item",
".",
"order",
"if",
"item",
".",
"permission",
":",
"self",
".",
"permission",
"=",
"item",
".",
"permission"
] |
Merge Menu item data
|
[
"Merge",
"Menu",
"item",
"data"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L150-L164
|
240,062
|
krukas/Trionyx
|
trionyx/navigation.py
|
MenuItem.add_child
|
def add_child(self, item):
"""Add child to menu item"""
item.depth = self.depth + 1
self.childs.append(item)
self.childs = sorted(self.childs, key=lambda item: item.order if item.order else 999)
|
python
|
def add_child(self, item):
"""Add child to menu item"""
item.depth = self.depth + 1
self.childs.append(item)
self.childs = sorted(self.childs, key=lambda item: item.order if item.order else 999)
|
[
"def",
"add_child",
"(",
"self",
",",
"item",
")",
":",
"item",
".",
"depth",
"=",
"self",
".",
"depth",
"+",
"1",
"self",
".",
"childs",
".",
"append",
"(",
"item",
")",
"self",
".",
"childs",
"=",
"sorted",
"(",
"self",
".",
"childs",
",",
"key",
"=",
"lambda",
"item",
":",
"item",
".",
"order",
"if",
"item",
".",
"order",
"else",
"999",
")"
] |
Add child to menu item
|
[
"Add",
"child",
"to",
"menu",
"item"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L166-L170
|
240,063
|
krukas/Trionyx
|
trionyx/navigation.py
|
MenuItem.child_by_code
|
def child_by_code(self, code):
"""
Get child MenuItem by its last path code
:param code:
:return: MenuItem or None
"""
for child in self.childs:
if child.path.split('/')[-1] == code:
return child
return None
|
python
|
def child_by_code(self, code):
"""
Get child MenuItem by its last path code
:param code:
:return: MenuItem or None
"""
for child in self.childs:
if child.path.split('/')[-1] == code:
return child
return None
|
[
"def",
"child_by_code",
"(",
"self",
",",
"code",
")",
":",
"for",
"child",
"in",
"self",
".",
"childs",
":",
"if",
"child",
".",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"==",
"code",
":",
"return",
"child",
"return",
"None"
] |
Get child MenuItem by its last path code
:param code:
:return: MenuItem or None
|
[
"Get",
"child",
"MenuItem",
"by",
"its",
"last",
"path",
"code"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L172-L182
|
240,064
|
krukas/Trionyx
|
trionyx/navigation.py
|
MenuItem.is_active
|
def is_active(self, path):
"""Check if given path is active for current item"""
if self.url == '/' and self.url == path:
return True
elif self.url == '/':
return False
if self.url and path.startswith(self.url):
return True
if self.active_regex and re.compile(self.active_regex).match(path):
return True
for child in self.childs:
if child.is_active(path):
return True
return False
|
python
|
def is_active(self, path):
"""Check if given path is active for current item"""
if self.url == '/' and self.url == path:
return True
elif self.url == '/':
return False
if self.url and path.startswith(self.url):
return True
if self.active_regex and re.compile(self.active_regex).match(path):
return True
for child in self.childs:
if child.is_active(path):
return True
return False
|
[
"def",
"is_active",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"url",
"==",
"'/'",
"and",
"self",
".",
"url",
"==",
"path",
":",
"return",
"True",
"elif",
"self",
".",
"url",
"==",
"'/'",
":",
"return",
"False",
"if",
"self",
".",
"url",
"and",
"path",
".",
"startswith",
"(",
"self",
".",
"url",
")",
":",
"return",
"True",
"if",
"self",
".",
"active_regex",
"and",
"re",
".",
"compile",
"(",
"self",
".",
"active_regex",
")",
".",
"match",
"(",
"path",
")",
":",
"return",
"True",
"for",
"child",
"in",
"self",
".",
"childs",
":",
"if",
"child",
".",
"is_active",
"(",
"path",
")",
":",
"return",
"True",
"return",
"False"
] |
Check if given path is active for current item
|
[
"Check",
"if",
"given",
"path",
"is",
"active",
"for",
"current",
"item"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L184-L200
|
240,065
|
krukas/Trionyx
|
trionyx/navigation.py
|
TabRegister.get_tabs
|
def get_tabs(self, model_alias, object):
"""
Get all active tabs for given model
:param model_alias:
:param object: Object used to filter tabs
:return:
"""
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.display_filter(object):
yield item
|
python
|
def get_tabs(self, model_alias, object):
"""
Get all active tabs for given model
:param model_alias:
:param object: Object used to filter tabs
:return:
"""
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.display_filter(object):
yield item
|
[
"def",
"get_tabs",
"(",
"self",
",",
"model_alias",
",",
"object",
")",
":",
"model_alias",
"=",
"self",
".",
"get_model_alias",
"(",
"model_alias",
")",
"for",
"item",
"in",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
":",
"if",
"item",
".",
"display_filter",
"(",
"object",
")",
":",
"yield",
"item"
] |
Get all active tabs for given model
:param model_alias:
:param object: Object used to filter tabs
:return:
|
[
"Get",
"all",
"active",
"tabs",
"for",
"given",
"model"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L210-L221
|
240,066
|
krukas/Trionyx
|
trionyx/navigation.py
|
TabRegister.get_tab
|
def get_tab(self, model_alias, object, tab_code):
"""
Get tab for given object and tab code
:param model_alias:
:param object: Object used to render tab
:param tab_code: Tab code to use
:return:
"""
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.code == tab_code and item.display_filter(object):
return item
raise Exception('Given tab does not exits or is filtered')
|
python
|
def get_tab(self, model_alias, object, tab_code):
"""
Get tab for given object and tab code
:param model_alias:
:param object: Object used to render tab
:param tab_code: Tab code to use
:return:
"""
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.code == tab_code and item.display_filter(object):
return item
raise Exception('Given tab does not exits or is filtered')
|
[
"def",
"get_tab",
"(",
"self",
",",
"model_alias",
",",
"object",
",",
"tab_code",
")",
":",
"model_alias",
"=",
"self",
".",
"get_model_alias",
"(",
"model_alias",
")",
"for",
"item",
"in",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
":",
"if",
"item",
".",
"code",
"==",
"tab_code",
"and",
"item",
".",
"display_filter",
"(",
"object",
")",
":",
"return",
"item",
"raise",
"Exception",
"(",
"'Given tab does not exits or is filtered'",
")"
] |
Get tab for given object and tab code
:param model_alias:
:param object: Object used to render tab
:param tab_code: Tab code to use
:return:
|
[
"Get",
"tab",
"for",
"given",
"object",
"and",
"tab",
"code"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L223-L236
|
240,067
|
krukas/Trionyx
|
trionyx/navigation.py
|
TabRegister.register
|
def register(self, model_alias, code='general', name=None, order=None, display_filter=None):
"""
Register new tab
:param model_alias:
:param code:
:param name:
:param order:
:return:
"""
model_alias = self.get_model_alias(model_alias)
def wrapper(create_layout):
item = TabItem(
code=code,
create_layout=create_layout,
name=name,
order=order,
display_filter=display_filter
)
if item in self.tabs[model_alias]:
raise Exception("Tab {} already registered for model {}".format(code, model_alias))
self.tabs[model_alias].append(item)
self.tabs[model_alias] = sorted(self.tabs[model_alias], key=lambda item: item.order if item.order else 999)
return create_layout
return wrapper
|
python
|
def register(self, model_alias, code='general', name=None, order=None, display_filter=None):
"""
Register new tab
:param model_alias:
:param code:
:param name:
:param order:
:return:
"""
model_alias = self.get_model_alias(model_alias)
def wrapper(create_layout):
item = TabItem(
code=code,
create_layout=create_layout,
name=name,
order=order,
display_filter=display_filter
)
if item in self.tabs[model_alias]:
raise Exception("Tab {} already registered for model {}".format(code, model_alias))
self.tabs[model_alias].append(item)
self.tabs[model_alias] = sorted(self.tabs[model_alias], key=lambda item: item.order if item.order else 999)
return create_layout
return wrapper
|
[
"def",
"register",
"(",
"self",
",",
"model_alias",
",",
"code",
"=",
"'general'",
",",
"name",
"=",
"None",
",",
"order",
"=",
"None",
",",
"display_filter",
"=",
"None",
")",
":",
"model_alias",
"=",
"self",
".",
"get_model_alias",
"(",
"model_alias",
")",
"def",
"wrapper",
"(",
"create_layout",
")",
":",
"item",
"=",
"TabItem",
"(",
"code",
"=",
"code",
",",
"create_layout",
"=",
"create_layout",
",",
"name",
"=",
"name",
",",
"order",
"=",
"order",
",",
"display_filter",
"=",
"display_filter",
")",
"if",
"item",
"in",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
":",
"raise",
"Exception",
"(",
"\"Tab {} already registered for model {}\"",
".",
"format",
"(",
"code",
",",
"model_alias",
")",
")",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
".",
"append",
"(",
"item",
")",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
"=",
"sorted",
"(",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
",",
"key",
"=",
"lambda",
"item",
":",
"item",
".",
"order",
"if",
"item",
".",
"order",
"else",
"999",
")",
"return",
"create_layout",
"return",
"wrapper"
] |
Register new tab
:param model_alias:
:param code:
:param name:
:param order:
:return:
|
[
"Register",
"new",
"tab"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L238-L266
|
240,068
|
krukas/Trionyx
|
trionyx/navigation.py
|
TabRegister.update
|
def update(self, model_alias, code='general', name=None, order=None, display_filter=None):
"""
Update given tab
:param model_alias:
:param code:
:param name:
:param order:
:param display_filter:
:return:
"""
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.code != code:
continue
if name:
item.name = name
if order:
item.order = order
if display_filter:
item.display_filter = display_filter
break
self.tabs[model_alias] = sorted(self.tabs[model_alias], key=lambda item: item.code if item.code else 999)
|
python
|
def update(self, model_alias, code='general', name=None, order=None, display_filter=None):
"""
Update given tab
:param model_alias:
:param code:
:param name:
:param order:
:param display_filter:
:return:
"""
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.code != code:
continue
if name:
item.name = name
if order:
item.order = order
if display_filter:
item.display_filter = display_filter
break
self.tabs[model_alias] = sorted(self.tabs[model_alias], key=lambda item: item.code if item.code else 999)
|
[
"def",
"update",
"(",
"self",
",",
"model_alias",
",",
"code",
"=",
"'general'",
",",
"name",
"=",
"None",
",",
"order",
"=",
"None",
",",
"display_filter",
"=",
"None",
")",
":",
"model_alias",
"=",
"self",
".",
"get_model_alias",
"(",
"model_alias",
")",
"for",
"item",
"in",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
":",
"if",
"item",
".",
"code",
"!=",
"code",
":",
"continue",
"if",
"name",
":",
"item",
".",
"name",
"=",
"name",
"if",
"order",
":",
"item",
".",
"order",
"=",
"order",
"if",
"display_filter",
":",
"item",
".",
"display_filter",
"=",
"display_filter",
"break",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
"=",
"sorted",
"(",
"self",
".",
"tabs",
"[",
"model_alias",
"]",
",",
"key",
"=",
"lambda",
"item",
":",
"item",
".",
"code",
"if",
"item",
".",
"code",
"else",
"999",
")"
] |
Update given tab
:param model_alias:
:param code:
:param name:
:param order:
:param display_filter:
:return:
|
[
"Update",
"given",
"tab"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L285-L307
|
240,069
|
krukas/Trionyx
|
trionyx/navigation.py
|
TabRegister.get_model_alias
|
def get_model_alias(self, model_alias):
"""Get model alias if class then convert to alias string"""
from trionyx.models import BaseModel
if inspect.isclass(model_alias) and issubclass(model_alias, BaseModel):
config = models_config.get_config(model_alias)
return '{}.{}'.format(config.app_label, config.model_name)
return model_alias
|
python
|
def get_model_alias(self, model_alias):
"""Get model alias if class then convert to alias string"""
from trionyx.models import BaseModel
if inspect.isclass(model_alias) and issubclass(model_alias, BaseModel):
config = models_config.get_config(model_alias)
return '{}.{}'.format(config.app_label, config.model_name)
return model_alias
|
[
"def",
"get_model_alias",
"(",
"self",
",",
"model_alias",
")",
":",
"from",
"trionyx",
".",
"models",
"import",
"BaseModel",
"if",
"inspect",
".",
"isclass",
"(",
"model_alias",
")",
"and",
"issubclass",
"(",
"model_alias",
",",
"BaseModel",
")",
":",
"config",
"=",
"models_config",
".",
"get_config",
"(",
"model_alias",
")",
"return",
"'{}.{}'",
".",
"format",
"(",
"config",
".",
"app_label",
",",
"config",
".",
"model_name",
")",
"return",
"model_alias"
] |
Get model alias if class then convert to alias string
|
[
"Get",
"model",
"alias",
"if",
"class",
"then",
"convert",
"to",
"alias",
"string"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L309-L315
|
240,070
|
krukas/Trionyx
|
trionyx/navigation.py
|
TabRegister.auto_generate_missing_tabs
|
def auto_generate_missing_tabs(self):
"""Auto generate tabs for models with no tabs"""
for config in models_config.get_all_configs():
model_alias = '{}.{}'.format(config.app_label, config.model_name)
if model_alias not in self.tabs:
@self.register(model_alias)
def general_layout(obj):
return Layout(
Column12(
Panel(
'info',
DescriptionList(*[f.name for f in obj.get_fields()])
)
)
)
|
python
|
def auto_generate_missing_tabs(self):
"""Auto generate tabs for models with no tabs"""
for config in models_config.get_all_configs():
model_alias = '{}.{}'.format(config.app_label, config.model_name)
if model_alias not in self.tabs:
@self.register(model_alias)
def general_layout(obj):
return Layout(
Column12(
Panel(
'info',
DescriptionList(*[f.name for f in obj.get_fields()])
)
)
)
|
[
"def",
"auto_generate_missing_tabs",
"(",
"self",
")",
":",
"for",
"config",
"in",
"models_config",
".",
"get_all_configs",
"(",
")",
":",
"model_alias",
"=",
"'{}.{}'",
".",
"format",
"(",
"config",
".",
"app_label",
",",
"config",
".",
"model_name",
")",
"if",
"model_alias",
"not",
"in",
"self",
".",
"tabs",
":",
"@",
"self",
".",
"register",
"(",
"model_alias",
")",
"def",
"general_layout",
"(",
"obj",
")",
":",
"return",
"Layout",
"(",
"Column12",
"(",
"Panel",
"(",
"'info'",
",",
"DescriptionList",
"(",
"*",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"obj",
".",
"get_fields",
"(",
")",
"]",
")",
")",
")",
")"
] |
Auto generate tabs for models with no tabs
|
[
"Auto",
"generate",
"tabs",
"for",
"models",
"with",
"no",
"tabs"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L317-L331
|
240,071
|
krukas/Trionyx
|
trionyx/navigation.py
|
TabItem.name
|
def name(self):
"""Give back tab name if is set else generate name by code"""
if self._name:
return self._name
return self.code.replace('_', ' ').capitalize()
|
python
|
def name(self):
"""Give back tab name if is set else generate name by code"""
if self._name:
return self._name
return self.code.replace('_', ' ').capitalize()
|
[
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
":",
"return",
"self",
".",
"_name",
"return",
"self",
".",
"code",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"capitalize",
"(",
")"
] |
Give back tab name if is set else generate name by code
|
[
"Give",
"back",
"tab",
"name",
"if",
"is",
"set",
"else",
"generate",
"name",
"by",
"code"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L348-L352
|
240,072
|
krukas/Trionyx
|
trionyx/navigation.py
|
TabItem.get_layout
|
def get_layout(self, object):
"""Get complete layout for given object"""
layout = self.create_layout(object)
if isinstance(layout, Component):
layout = Layout(layout)
if isinstance(layout, list):
layout = Layout(*layout)
for update_layout in self.layout_updates:
update_layout(layout, object)
layout.set_object(object)
return layout
|
python
|
def get_layout(self, object):
"""Get complete layout for given object"""
layout = self.create_layout(object)
if isinstance(layout, Component):
layout = Layout(layout)
if isinstance(layout, list):
layout = Layout(*layout)
for update_layout in self.layout_updates:
update_layout(layout, object)
layout.set_object(object)
return layout
|
[
"def",
"get_layout",
"(",
"self",
",",
"object",
")",
":",
"layout",
"=",
"self",
".",
"create_layout",
"(",
"object",
")",
"if",
"isinstance",
"(",
"layout",
",",
"Component",
")",
":",
"layout",
"=",
"Layout",
"(",
"layout",
")",
"if",
"isinstance",
"(",
"layout",
",",
"list",
")",
":",
"layout",
"=",
"Layout",
"(",
"*",
"layout",
")",
"for",
"update_layout",
"in",
"self",
".",
"layout_updates",
":",
"update_layout",
"(",
"layout",
",",
"object",
")",
"layout",
".",
"set_object",
"(",
"object",
")",
"return",
"layout"
] |
Get complete layout for given object
|
[
"Get",
"complete",
"layout",
"for",
"given",
"object"
] |
edac132cc0797190153f2e60bc7e88cb50e80da6
|
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L359-L371
|
240,073
|
wbonnet/mnemonic-checker
|
mnemonic_checker/__main__.py
|
main
|
def main():
"""
Main entry point for the script. Create a parser, process the command line,
and run it
"""
parser = cli.Cli()
parser.parse(sys.argv[1:])
return parser.run()
|
python
|
def main():
"""
Main entry point for the script. Create a parser, process the command line,
and run it
"""
parser = cli.Cli()
parser.parse(sys.argv[1:])
return parser.run()
|
[
"def",
"main",
"(",
")",
":",
"parser",
"=",
"cli",
".",
"Cli",
"(",
")",
"parser",
".",
"parse",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"return",
"parser",
".",
"run",
"(",
")"
] |
Main entry point for the script. Create a parser, process the command line,
and run it
|
[
"Main",
"entry",
"point",
"for",
"the",
"script",
".",
"Create",
"a",
"parser",
"process",
"the",
"command",
"line",
"and",
"run",
"it"
] |
cec3f25b447c111f4d31fabcaee89af7977cafd8
|
https://github.com/wbonnet/mnemonic-checker/blob/cec3f25b447c111f4d31fabcaee89af7977cafd8/mnemonic_checker/__main__.py#L26-L33
|
240,074
|
MacHu-GWU/angora-project
|
angora/gadget/backup.py
|
run_backup
|
def run_backup(filename, root_dir, ignore=[], ignore_ext=[], ignore_pattern=[]):
"""The backup utility method.
:param root_dir: the directory you want to backup
:param ignore: file or directory defined in this list will be ignored.
:param ignore_ext: file with extensions defined in this list will be ignored.
:param ignore_pattern: any file or directory that contains this pattern
will be ignored.
"""
tab = " "
# Step 1, calculate files to backup
print("Perform backup '%s'..." % root_dir)
print(tab + "1. Calculate files...")
total_size_in_bytes = 0
init_mode = WinFile.init_mode
WinFile.use_regular_init()
fc = FileCollection.from_path_except(
root_dir, ignore, ignore_ext, ignore_pattern)
WinFile.set_initialize_mode(complexity=init_mode)
for winfile in fc.iterfiles():
total_size_in_bytes += winfile.size_on_disk
# Step 2, write files to zip archive
print(tab * 2 + "Done, got %s files, total size is %s." % (
len(fc), string_SizeInBytes(total_size_in_bytes)))
print(tab + "2. Backup files...")
filename = "%s %s.zip" % (
filename, datetime.now().strftime("%Y-%m-%d %Hh-%Mm-%Ss"))
print(tab * 2 + "Write to '%s'..." % filename)
current_dir = os.getcwd()
with ZipFile(filename, "w") as f:
os.chdir(root_dir)
for winfile in fc.iterfiles():
relpath = os.path.relpath(winfile.abspath, root_dir)
f.write(relpath)
os.chdir(current_dir)
print(tab + "Complete!")
|
python
|
def run_backup(filename, root_dir, ignore=[], ignore_ext=[], ignore_pattern=[]):
"""The backup utility method.
:param root_dir: the directory you want to backup
:param ignore: file or directory defined in this list will be ignored.
:param ignore_ext: file with extensions defined in this list will be ignored.
:param ignore_pattern: any file or directory that contains this pattern
will be ignored.
"""
tab = " "
# Step 1, calculate files to backup
print("Perform backup '%s'..." % root_dir)
print(tab + "1. Calculate files...")
total_size_in_bytes = 0
init_mode = WinFile.init_mode
WinFile.use_regular_init()
fc = FileCollection.from_path_except(
root_dir, ignore, ignore_ext, ignore_pattern)
WinFile.set_initialize_mode(complexity=init_mode)
for winfile in fc.iterfiles():
total_size_in_bytes += winfile.size_on_disk
# Step 2, write files to zip archive
print(tab * 2 + "Done, got %s files, total size is %s." % (
len(fc), string_SizeInBytes(total_size_in_bytes)))
print(tab + "2. Backup files...")
filename = "%s %s.zip" % (
filename, datetime.now().strftime("%Y-%m-%d %Hh-%Mm-%Ss"))
print(tab * 2 + "Write to '%s'..." % filename)
current_dir = os.getcwd()
with ZipFile(filename, "w") as f:
os.chdir(root_dir)
for winfile in fc.iterfiles():
relpath = os.path.relpath(winfile.abspath, root_dir)
f.write(relpath)
os.chdir(current_dir)
print(tab + "Complete!")
|
[
"def",
"run_backup",
"(",
"filename",
",",
"root_dir",
",",
"ignore",
"=",
"[",
"]",
",",
"ignore_ext",
"=",
"[",
"]",
",",
"ignore_pattern",
"=",
"[",
"]",
")",
":",
"tab",
"=",
"\" \"",
"# Step 1, calculate files to backup",
"print",
"(",
"\"Perform backup '%s'...\"",
"%",
"root_dir",
")",
"print",
"(",
"tab",
"+",
"\"1. Calculate files...\"",
")",
"total_size_in_bytes",
"=",
"0",
"init_mode",
"=",
"WinFile",
".",
"init_mode",
"WinFile",
".",
"use_regular_init",
"(",
")",
"fc",
"=",
"FileCollection",
".",
"from_path_except",
"(",
"root_dir",
",",
"ignore",
",",
"ignore_ext",
",",
"ignore_pattern",
")",
"WinFile",
".",
"set_initialize_mode",
"(",
"complexity",
"=",
"init_mode",
")",
"for",
"winfile",
"in",
"fc",
".",
"iterfiles",
"(",
")",
":",
"total_size_in_bytes",
"+=",
"winfile",
".",
"size_on_disk",
"# Step 2, write files to zip archive",
"print",
"(",
"tab",
"*",
"2",
"+",
"\"Done, got %s files, total size is %s.\"",
"%",
"(",
"len",
"(",
"fc",
")",
",",
"string_SizeInBytes",
"(",
"total_size_in_bytes",
")",
")",
")",
"print",
"(",
"tab",
"+",
"\"2. Backup files...\"",
")",
"filename",
"=",
"\"%s %s.zip\"",
"%",
"(",
"filename",
",",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y-%m-%d %Hh-%Mm-%Ss\"",
")",
")",
"print",
"(",
"tab",
"*",
"2",
"+",
"\"Write to '%s'...\"",
"%",
"filename",
")",
"current_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"with",
"ZipFile",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"f",
":",
"os",
".",
"chdir",
"(",
"root_dir",
")",
"for",
"winfile",
"in",
"fc",
".",
"iterfiles",
"(",
")",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"winfile",
".",
"abspath",
",",
"root_dir",
")",
"f",
".",
"write",
"(",
"relpath",
")",
"os",
".",
"chdir",
"(",
"current_dir",
")",
"print",
"(",
"tab",
"+",
"\"Complete!\"",
")"
] |
The backup utility method.
:param root_dir: the directory you want to backup
:param ignore: file or directory defined in this list will be ignored.
:param ignore_ext: file with extensions defined in this list will be ignored.
:param ignore_pattern: any file or directory that contains this pattern
will be ignored.
|
[
"The",
"backup",
"utility",
"method",
"."
] |
689a60da51cd88680ddbe26e28dbe81e6b01d275
|
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/backup.py#L75-L117
|
240,075
|
ddorn/pyconfiglib
|
configlib/prompting.py
|
prompt_file
|
def prompt_file(prompt, default=None):
"""Prompt a file name with autocompletion"""
def complete(text: str, state):
text = text.replace('~', HOME)
sugg = (glob.glob(text + '*') + [None])[state]
if sugg is None:
return
sugg = sugg.replace(HOME, '~')
sugg = sugg.replace('\\', '/')
if os.path.isdir(sugg) and not sugg.endswith('/'):
sugg += '/'
return sugg
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
if default is not None:
r = input('%s [%r]: ' % (prompt, default))
else:
r = input('%s: ' % prompt)
r = r or default
# remove the autocompletion before quitting for future input()
readline.parse_and_bind('tab: self-insert')
return r
|
python
|
def prompt_file(prompt, default=None):
"""Prompt a file name with autocompletion"""
def complete(text: str, state):
text = text.replace('~', HOME)
sugg = (glob.glob(text + '*') + [None])[state]
if sugg is None:
return
sugg = sugg.replace(HOME, '~')
sugg = sugg.replace('\\', '/')
if os.path.isdir(sugg) and not sugg.endswith('/'):
sugg += '/'
return sugg
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
if default is not None:
r = input('%s [%r]: ' % (prompt, default))
else:
r = input('%s: ' % prompt)
r = r or default
# remove the autocompletion before quitting for future input()
readline.parse_and_bind('tab: self-insert')
return r
|
[
"def",
"prompt_file",
"(",
"prompt",
",",
"default",
"=",
"None",
")",
":",
"def",
"complete",
"(",
"text",
":",
"str",
",",
"state",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"'~'",
",",
"HOME",
")",
"sugg",
"=",
"(",
"glob",
".",
"glob",
"(",
"text",
"+",
"'*'",
")",
"+",
"[",
"None",
"]",
")",
"[",
"state",
"]",
"if",
"sugg",
"is",
"None",
":",
"return",
"sugg",
"=",
"sugg",
".",
"replace",
"(",
"HOME",
",",
"'~'",
")",
"sugg",
"=",
"sugg",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"sugg",
")",
"and",
"not",
"sugg",
".",
"endswith",
"(",
"'/'",
")",
":",
"sugg",
"+=",
"'/'",
"return",
"sugg",
"readline",
".",
"set_completer_delims",
"(",
"' \\t\\n;'",
")",
"readline",
".",
"parse_and_bind",
"(",
"\"tab: complete\"",
")",
"readline",
".",
"set_completer",
"(",
"complete",
")",
"if",
"default",
"is",
"not",
"None",
":",
"r",
"=",
"input",
"(",
"'%s [%r]: '",
"%",
"(",
"prompt",
",",
"default",
")",
")",
"else",
":",
"r",
"=",
"input",
"(",
"'%s: '",
"%",
"prompt",
")",
"r",
"=",
"r",
"or",
"default",
"# remove the autocompletion before quitting for future input()",
"readline",
".",
"parse_and_bind",
"(",
"'tab: self-insert'",
")",
"return",
"r"
] |
Prompt a file name with autocompletion
|
[
"Prompt",
"a",
"file",
"name",
"with",
"autocompletion"
] |
3ad01d0bb9344e18719d82a5928b4d8e5fe726ac
|
https://github.com/ddorn/pyconfiglib/blob/3ad01d0bb9344e18719d82a5928b4d8e5fe726ac/configlib/prompting.py#L9-L42
|
240,076
|
Vito2015/pyextend
|
pyextend/core/math.py
|
isprime
|
def isprime(n):
"""Check the number is prime value. if prime value returns True, not False."""
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
# 在一般领域, 对正整数n, 如果用2 到 sqrt(n) 之间所有整数去除, 均无法整除, 则n为质数.
for x in range(3, int(n ** 0.5)+1, 2):
if n % x == 0:
return False
return True
|
python
|
def isprime(n):
"""Check the number is prime value. if prime value returns True, not False."""
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
# 在一般领域, 对正整数n, 如果用2 到 sqrt(n) 之间所有整数去除, 均无法整除, 则n为质数.
for x in range(3, int(n ** 0.5)+1, 2):
if n % x == 0:
return False
return True
|
[
"def",
"isprime",
"(",
"n",
")",
":",
"n",
"=",
"abs",
"(",
"int",
"(",
"n",
")",
")",
"if",
"n",
"<",
"2",
":",
"return",
"False",
"if",
"n",
"==",
"2",
":",
"return",
"True",
"if",
"not",
"n",
"&",
"1",
":",
"return",
"False",
"# 在一般领域, 对正整数n, 如果用2 到 sqrt(n) 之间所有整数去除, 均无法整除, 则n为质数.",
"for",
"x",
"in",
"range",
"(",
"3",
",",
"int",
"(",
"n",
"**",
"0.5",
")",
"+",
"1",
",",
"2",
")",
":",
"if",
"n",
"%",
"x",
"==",
"0",
":",
"return",
"False",
"return",
"True"
] |
Check the number is prime value. if prime value returns True, not False.
|
[
"Check",
"the",
"number",
"is",
"prime",
"value",
".",
"if",
"prime",
"value",
"returns",
"True",
"not",
"False",
"."
] |
36861dfe1087e437ffe9b5a1da9345c85b4fa4a1
|
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/math.py#L12-L28
|
240,077
|
mattupstate/cubric
|
cubric/contrib/servers/ubuntu/default/__init__.py
|
WsgiApplicationContext.create
|
def create(self):
"""Create an application context on the server"""
self.before_create()
puts(green('Creating app context'))
tdir = os.path.dirname(__file__)
# Ensure the app context user exists
user_ensure(self.user, home='/home/' + self.user)
dir_ensure('/home/%s/.ssh' % self.user)
t = '/home/%s/.ssh/authorized_keys'
app_authorized_keys = t % env.user
ctx_authorized_keys = t % self.user
# Ensure the app user has the same authorized_keys as the admin user
if file_exists(app_authorized_keys) and \
not file_exists(ctx_authorized_keys):
sudo('cp %s %s' % (app_authorized_keys, ctx_authorized_keys))
file_attribs(ctx_authorized_keys, mode=755,
owner=self.user, group=self.user)
# Actions to be performed with the app context user
with settings(user=self.user):
# Make sure the dot files exist
# This is mostly necessary for virtualenvwrapper to work properly
for f in ['bashrc', 'bash_profile', 'profile']:
lfn = os.path.join(tdir, 'templates', '%s.tmpl' % f)
contents = file_local_read(lfn) % self.__dict__
rfn = '/home/%s/.%s' % (self.user, f)
file_ensure(rfn, owner=self.user, group=self.user)
file_update(rfn, lambda _: contents)
# Make sure the sites folder exists
dir_ensure('/home/%s/sites' % self.user)
# Make sure the app's required folders exist
for d in [self.root_dir, self.releases_dir, self.etc_dir,
self.log_dir, self.run_dir, self.shared_dir]:
dir_ensure(d)
# Create the virtualenv
run('mkvirtualenv ' + self.name)
self.after_create()
|
python
|
def create(self):
"""Create an application context on the server"""
self.before_create()
puts(green('Creating app context'))
tdir = os.path.dirname(__file__)
# Ensure the app context user exists
user_ensure(self.user, home='/home/' + self.user)
dir_ensure('/home/%s/.ssh' % self.user)
t = '/home/%s/.ssh/authorized_keys'
app_authorized_keys = t % env.user
ctx_authorized_keys = t % self.user
# Ensure the app user has the same authorized_keys as the admin user
if file_exists(app_authorized_keys) and \
not file_exists(ctx_authorized_keys):
sudo('cp %s %s' % (app_authorized_keys, ctx_authorized_keys))
file_attribs(ctx_authorized_keys, mode=755,
owner=self.user, group=self.user)
# Actions to be performed with the app context user
with settings(user=self.user):
# Make sure the dot files exist
# This is mostly necessary for virtualenvwrapper to work properly
for f in ['bashrc', 'bash_profile', 'profile']:
lfn = os.path.join(tdir, 'templates', '%s.tmpl' % f)
contents = file_local_read(lfn) % self.__dict__
rfn = '/home/%s/.%s' % (self.user, f)
file_ensure(rfn, owner=self.user, group=self.user)
file_update(rfn, lambda _: contents)
# Make sure the sites folder exists
dir_ensure('/home/%s/sites' % self.user)
# Make sure the app's required folders exist
for d in [self.root_dir, self.releases_dir, self.etc_dir,
self.log_dir, self.run_dir, self.shared_dir]:
dir_ensure(d)
# Create the virtualenv
run('mkvirtualenv ' + self.name)
self.after_create()
|
[
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"before_create",
"(",
")",
"puts",
"(",
"green",
"(",
"'Creating app context'",
")",
")",
"tdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"# Ensure the app context user exists",
"user_ensure",
"(",
"self",
".",
"user",
",",
"home",
"=",
"'/home/'",
"+",
"self",
".",
"user",
")",
"dir_ensure",
"(",
"'/home/%s/.ssh'",
"%",
"self",
".",
"user",
")",
"t",
"=",
"'/home/%s/.ssh/authorized_keys'",
"app_authorized_keys",
"=",
"t",
"%",
"env",
".",
"user",
"ctx_authorized_keys",
"=",
"t",
"%",
"self",
".",
"user",
"# Ensure the app user has the same authorized_keys as the admin user",
"if",
"file_exists",
"(",
"app_authorized_keys",
")",
"and",
"not",
"file_exists",
"(",
"ctx_authorized_keys",
")",
":",
"sudo",
"(",
"'cp %s %s'",
"%",
"(",
"app_authorized_keys",
",",
"ctx_authorized_keys",
")",
")",
"file_attribs",
"(",
"ctx_authorized_keys",
",",
"mode",
"=",
"755",
",",
"owner",
"=",
"self",
".",
"user",
",",
"group",
"=",
"self",
".",
"user",
")",
"# Actions to be performed with the app context user",
"with",
"settings",
"(",
"user",
"=",
"self",
".",
"user",
")",
":",
"# Make sure the dot files exist",
"# This is mostly necessary for virtualenvwrapper to work properly",
"for",
"f",
"in",
"[",
"'bashrc'",
",",
"'bash_profile'",
",",
"'profile'",
"]",
":",
"lfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tdir",
",",
"'templates'",
",",
"'%s.tmpl'",
"%",
"f",
")",
"contents",
"=",
"file_local_read",
"(",
"lfn",
")",
"%",
"self",
".",
"__dict__",
"rfn",
"=",
"'/home/%s/.%s'",
"%",
"(",
"self",
".",
"user",
",",
"f",
")",
"file_ensure",
"(",
"rfn",
",",
"owner",
"=",
"self",
".",
"user",
",",
"group",
"=",
"self",
".",
"user",
")",
"file_update",
"(",
"rfn",
",",
"lambda",
"_",
":",
"contents",
")",
"# Make sure the sites folder exists",
"dir_ensure",
"(",
"'/home/%s/sites'",
"%",
"self",
".",
"user",
")",
"# Make sure the app's required folders exist",
"for",
"d",
"in",
"[",
"self",
".",
"root_dir",
",",
"self",
".",
"releases_dir",
",",
"self",
".",
"etc_dir",
",",
"self",
".",
"log_dir",
",",
"self",
".",
"run_dir",
",",
"self",
".",
"shared_dir",
"]",
":",
"dir_ensure",
"(",
"d",
")",
"# Create the virtualenv",
"run",
"(",
"'mkvirtualenv '",
"+",
"self",
".",
"name",
")",
"self",
".",
"after_create",
"(",
")"
] |
Create an application context on the server
|
[
"Create",
"an",
"application",
"context",
"on",
"the",
"server"
] |
a648ce00e4467cd14d71e754240ef6c1f87a34b5
|
https://github.com/mattupstate/cubric/blob/a648ce00e4467cd14d71e754240ef6c1f87a34b5/cubric/contrib/servers/ubuntu/default/__init__.py#L246-L291
|
240,078
|
mattupstate/cubric
|
cubric/contrib/servers/ubuntu/default/__init__.py
|
WsgiApplicationContext.upload_release
|
def upload_release(self):
"""Upload an application bundle to the server for a given context"""
self.before_upload_release()
with settings(user=self.user):
with app_bundle():
local_bundle = env.local_bundle
env.bundle = '/tmp/' + os.path.basename(local_bundle)
file_upload(env.bundle, local_bundle)
# Extract the bundle into a release folder
current_release_link = self.releases_dir + '/current'
previous_release_link = self.releases_dir + '/previous'
release_dir = self.releases_dir + '/' + env.release
dir_ensure(release_dir)
with cd(release_dir):
run('tar -xvf ' + env.bundle)
# Delete the remote bundle
run('rm ' + env.bundle)
# Remove previous release link
if file_exists(previous_release_link):
run('rm ' + previous_release_link)
# Move current to previous
if file_exists(current_release_link):
run('mv %s %s' % (current_release_link, previous_release_link))
# Link the current release
file_link(release_dir, self.releases_dir + "/current")
# Install app dependencies
with cd(current_release_link):
with prefix('workon ' + self.name):
run('pip install -r requirements.txt')
self.after_upload_release()
|
python
|
def upload_release(self):
"""Upload an application bundle to the server for a given context"""
self.before_upload_release()
with settings(user=self.user):
with app_bundle():
local_bundle = env.local_bundle
env.bundle = '/tmp/' + os.path.basename(local_bundle)
file_upload(env.bundle, local_bundle)
# Extract the bundle into a release folder
current_release_link = self.releases_dir + '/current'
previous_release_link = self.releases_dir + '/previous'
release_dir = self.releases_dir + '/' + env.release
dir_ensure(release_dir)
with cd(release_dir):
run('tar -xvf ' + env.bundle)
# Delete the remote bundle
run('rm ' + env.bundle)
# Remove previous release link
if file_exists(previous_release_link):
run('rm ' + previous_release_link)
# Move current to previous
if file_exists(current_release_link):
run('mv %s %s' % (current_release_link, previous_release_link))
# Link the current release
file_link(release_dir, self.releases_dir + "/current")
# Install app dependencies
with cd(current_release_link):
with prefix('workon ' + self.name):
run('pip install -r requirements.txt')
self.after_upload_release()
|
[
"def",
"upload_release",
"(",
"self",
")",
":",
"self",
".",
"before_upload_release",
"(",
")",
"with",
"settings",
"(",
"user",
"=",
"self",
".",
"user",
")",
":",
"with",
"app_bundle",
"(",
")",
":",
"local_bundle",
"=",
"env",
".",
"local_bundle",
"env",
".",
"bundle",
"=",
"'/tmp/'",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"local_bundle",
")",
"file_upload",
"(",
"env",
".",
"bundle",
",",
"local_bundle",
")",
"# Extract the bundle into a release folder",
"current_release_link",
"=",
"self",
".",
"releases_dir",
"+",
"'/current'",
"previous_release_link",
"=",
"self",
".",
"releases_dir",
"+",
"'/previous'",
"release_dir",
"=",
"self",
".",
"releases_dir",
"+",
"'/'",
"+",
"env",
".",
"release",
"dir_ensure",
"(",
"release_dir",
")",
"with",
"cd",
"(",
"release_dir",
")",
":",
"run",
"(",
"'tar -xvf '",
"+",
"env",
".",
"bundle",
")",
"# Delete the remote bundle",
"run",
"(",
"'rm '",
"+",
"env",
".",
"bundle",
")",
"# Remove previous release link",
"if",
"file_exists",
"(",
"previous_release_link",
")",
":",
"run",
"(",
"'rm '",
"+",
"previous_release_link",
")",
"# Move current to previous",
"if",
"file_exists",
"(",
"current_release_link",
")",
":",
"run",
"(",
"'mv %s %s'",
"%",
"(",
"current_release_link",
",",
"previous_release_link",
")",
")",
"# Link the current release",
"file_link",
"(",
"release_dir",
",",
"self",
".",
"releases_dir",
"+",
"\"/current\"",
")",
"# Install app dependencies",
"with",
"cd",
"(",
"current_release_link",
")",
":",
"with",
"prefix",
"(",
"'workon '",
"+",
"self",
".",
"name",
")",
":",
"run",
"(",
"'pip install -r requirements.txt'",
")",
"self",
".",
"after_upload_release",
"(",
")"
] |
Upload an application bundle to the server for a given context
|
[
"Upload",
"an",
"application",
"bundle",
"to",
"the",
"server",
"for",
"a",
"given",
"context"
] |
a648ce00e4467cd14d71e754240ef6c1f87a34b5
|
https://github.com/mattupstate/cubric/blob/a648ce00e4467cd14d71e754240ef6c1f87a34b5/cubric/contrib/servers/ubuntu/default/__init__.py#L299-L337
|
240,079
|
Rhathe/fixtureupper
|
fixtureupper/model.py
|
ModelFixtureUpper._print_breakdown
|
def _print_breakdown(cls, savedir, fname, data):
"""Function to print model fixtures into generated file"""
if not os.path.exists(savedir):
os.makedirs(savedir)
with open(os.path.join(savedir, fname), 'w') as fout:
fout.write(data)
|
python
|
def _print_breakdown(cls, savedir, fname, data):
"""Function to print model fixtures into generated file"""
if not os.path.exists(savedir):
os.makedirs(savedir)
with open(os.path.join(savedir, fname), 'w') as fout:
fout.write(data)
|
[
"def",
"_print_breakdown",
"(",
"cls",
",",
"savedir",
",",
"fname",
",",
"data",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"savedir",
")",
":",
"os",
".",
"makedirs",
"(",
"savedir",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"savedir",
",",
"fname",
")",
",",
"'w'",
")",
"as",
"fout",
":",
"fout",
".",
"write",
"(",
"data",
")"
] |
Function to print model fixtures into generated file
|
[
"Function",
"to",
"print",
"model",
"fixtures",
"into",
"generated",
"file"
] |
f8d6f95b5f5f38963f2389f4183d1c9884184853
|
https://github.com/Rhathe/fixtureupper/blob/f8d6f95b5f5f38963f2389f4183d1c9884184853/fixtureupper/model.py#L137-L143
|
240,080
|
Rhathe/fixtureupper
|
fixtureupper/model.py
|
ModelFixtureUpper.read_json_breakdown
|
def read_json_breakdown(cls, fname):
"""Read json file to get fixture data"""
if not os.path.exists(fname):
raise RuntimeError
with open(fname, 'r') as data_file:
return cls.fixup_from_json(data_file.read())
|
python
|
def read_json_breakdown(cls, fname):
"""Read json file to get fixture data"""
if not os.path.exists(fname):
raise RuntimeError
with open(fname, 'r') as data_file:
return cls.fixup_from_json(data_file.read())
|
[
"def",
"read_json_breakdown",
"(",
"cls",
",",
"fname",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"raise",
"RuntimeError",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"data_file",
":",
"return",
"cls",
".",
"fixup_from_json",
"(",
"data_file",
".",
"read",
"(",
")",
")"
] |
Read json file to get fixture data
|
[
"Read",
"json",
"file",
"to",
"get",
"fixture",
"data"
] |
f8d6f95b5f5f38963f2389f4183d1c9884184853
|
https://github.com/Rhathe/fixtureupper/blob/f8d6f95b5f5f38963f2389f4183d1c9884184853/fixtureupper/model.py#L226-L232
|
240,081
|
phenicle/pgdbpy
|
pgdbpy/tools.py
|
PgDbPy.execute
|
def execute(self, fetchcommand, sql, params=None):
""" where 'fetchcommand' is either 'fetchone' or 'fetchall' """
cur = self.conn.cursor()
if params:
if not type(params).__name__ == 'tuple':
raise ValueError('the params argument needs to be a tuple')
return None
cur.execute(sql, params)
else:
cur.execute(sql)
self.conn.commit()
if not fetchcommand or fetchcommand == 'none':
return
if fetchcommand == 'last' or fetchcommand == 'lastid':
lastdata = cur.fetchall()
self.conn.commit()
return lastdata
m = insertion_pattern.match(sql)
"""
TODO: This is a BUG - need to also check tail of query for RETURNING
"""
if m:
""" lastid = cursor.fetchone()['lastval'] """
lastdata = cur.fetchone()
self.conn.commit()
return lastdata
if fetchcommand == 'fetchone' or fetchcommand == 'one':
return cur.fetchone()
elif fetchcommand == 'fetchall' or fetchcommand == 'all':
return cur.fetchall()
else:
msg = "expecting <fetchcommand> argument to be either 'fetchone'|'one'|'fetchall|all'"
raise ValueError(msg)
|
python
|
def execute(self, fetchcommand, sql, params=None):
""" where 'fetchcommand' is either 'fetchone' or 'fetchall' """
cur = self.conn.cursor()
if params:
if not type(params).__name__ == 'tuple':
raise ValueError('the params argument needs to be a tuple')
return None
cur.execute(sql, params)
else:
cur.execute(sql)
self.conn.commit()
if not fetchcommand or fetchcommand == 'none':
return
if fetchcommand == 'last' or fetchcommand == 'lastid':
lastdata = cur.fetchall()
self.conn.commit()
return lastdata
m = insertion_pattern.match(sql)
"""
TODO: This is a BUG - need to also check tail of query for RETURNING
"""
if m:
""" lastid = cursor.fetchone()['lastval'] """
lastdata = cur.fetchone()
self.conn.commit()
return lastdata
if fetchcommand == 'fetchone' or fetchcommand == 'one':
return cur.fetchone()
elif fetchcommand == 'fetchall' or fetchcommand == 'all':
return cur.fetchall()
else:
msg = "expecting <fetchcommand> argument to be either 'fetchone'|'one'|'fetchall|all'"
raise ValueError(msg)
|
[
"def",
"execute",
"(",
"self",
",",
"fetchcommand",
",",
"sql",
",",
"params",
"=",
"None",
")",
":",
"cur",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"if",
"params",
":",
"if",
"not",
"type",
"(",
"params",
")",
".",
"__name__",
"==",
"'tuple'",
":",
"raise",
"ValueError",
"(",
"'the params argument needs to be a tuple'",
")",
"return",
"None",
"cur",
".",
"execute",
"(",
"sql",
",",
"params",
")",
"else",
":",
"cur",
".",
"execute",
"(",
"sql",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"if",
"not",
"fetchcommand",
"or",
"fetchcommand",
"==",
"'none'",
":",
"return",
"if",
"fetchcommand",
"==",
"'last'",
"or",
"fetchcommand",
"==",
"'lastid'",
":",
"lastdata",
"=",
"cur",
".",
"fetchall",
"(",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"return",
"lastdata",
"m",
"=",
"insertion_pattern",
".",
"match",
"(",
"sql",
")",
"\"\"\"\n\t\t TODO: This is a BUG - need to also check tail of query for RETURNING\n\t\t\"\"\"",
"if",
"m",
":",
"\"\"\" lastid = cursor.fetchone()['lastval'] \"\"\"",
"lastdata",
"=",
"cur",
".",
"fetchone",
"(",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"return",
"lastdata",
"if",
"fetchcommand",
"==",
"'fetchone'",
"or",
"fetchcommand",
"==",
"'one'",
":",
"return",
"cur",
".",
"fetchone",
"(",
")",
"elif",
"fetchcommand",
"==",
"'fetchall'",
"or",
"fetchcommand",
"==",
"'all'",
":",
"return",
"cur",
".",
"fetchall",
"(",
")",
"else",
":",
"msg",
"=",
"\"expecting <fetchcommand> argument to be either 'fetchone'|'one'|'fetchall|all'\"",
"raise",
"ValueError",
"(",
"msg",
")"
] |
where 'fetchcommand' is either 'fetchone' or 'fetchall'
|
[
"where",
"fetchcommand",
"is",
"either",
"fetchone",
"or",
"fetchall"
] |
0b4cc8825006f8ce620f693c4bd9b8b74312d9e8
|
https://github.com/phenicle/pgdbpy/blob/0b4cc8825006f8ce620f693c4bd9b8b74312d9e8/pgdbpy/tools.py#L136-L174
|
240,082
|
scivision/histutils
|
histutils/cp_parents.py
|
cp_parents
|
def cp_parents(files, target_dir: Union[str, Path]):
"""
This function requires Python >= 3.6.
This acts like bash cp --parents in Python
inspiration from
http://stackoverflow.com/questions/15329223/copy-a-file-into-a-directory-with-its-original-leading-directories-appended
example
source: /tmp/e/f
dest: /tmp/a/b/c/d/
result: /tmp/a/b/c/d/tmp/e/f
cp_parents('/tmp/a/b/c/d/boo','/tmp/e/f')
cp_parents('x/hi','/tmp/e/f/g') --> copies ./x/hi to /tmp/e/f/g/x/hi
"""
# %% make list if it's a string
if isinstance(files, (str, Path)):
files = [files]
# %% cleanup user
# relative path or absolute path is fine
files = (Path(f).expanduser() for f in files)
target_dir = Path(target_dir).expanduser()
# %% work
for f in files:
# to make it work like cp --parents, copying absolute paths if specified
newpath = target_dir / f.parent
newpath.mkdir(parents=True, exist_ok=True)
shutil.copy2(f, newpath)
|
python
|
def cp_parents(files, target_dir: Union[str, Path]):
"""
This function requires Python >= 3.6.
This acts like bash cp --parents in Python
inspiration from
http://stackoverflow.com/questions/15329223/copy-a-file-into-a-directory-with-its-original-leading-directories-appended
example
source: /tmp/e/f
dest: /tmp/a/b/c/d/
result: /tmp/a/b/c/d/tmp/e/f
cp_parents('/tmp/a/b/c/d/boo','/tmp/e/f')
cp_parents('x/hi','/tmp/e/f/g') --> copies ./x/hi to /tmp/e/f/g/x/hi
"""
# %% make list if it's a string
if isinstance(files, (str, Path)):
files = [files]
# %% cleanup user
# relative path or absolute path is fine
files = (Path(f).expanduser() for f in files)
target_dir = Path(target_dir).expanduser()
# %% work
for f in files:
# to make it work like cp --parents, copying absolute paths if specified
newpath = target_dir / f.parent
newpath.mkdir(parents=True, exist_ok=True)
shutil.copy2(f, newpath)
|
[
"def",
"cp_parents",
"(",
"files",
",",
"target_dir",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
")",
":",
"# %% make list if it's a string",
"if",
"isinstance",
"(",
"files",
",",
"(",
"str",
",",
"Path",
")",
")",
":",
"files",
"=",
"[",
"files",
"]",
"# %% cleanup user",
"# relative path or absolute path is fine",
"files",
"=",
"(",
"Path",
"(",
"f",
")",
".",
"expanduser",
"(",
")",
"for",
"f",
"in",
"files",
")",
"target_dir",
"=",
"Path",
"(",
"target_dir",
")",
".",
"expanduser",
"(",
")",
"# %% work",
"for",
"f",
"in",
"files",
":",
"# to make it work like cp --parents, copying absolute paths if specified",
"newpath",
"=",
"target_dir",
"/",
"f",
".",
"parent",
"newpath",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"shutil",
".",
"copy2",
"(",
"f",
",",
"newpath",
")"
] |
This function requires Python >= 3.6.
This acts like bash cp --parents in Python
inspiration from
http://stackoverflow.com/questions/15329223/copy-a-file-into-a-directory-with-its-original-leading-directories-appended
example
source: /tmp/e/f
dest: /tmp/a/b/c/d/
result: /tmp/a/b/c/d/tmp/e/f
cp_parents('/tmp/a/b/c/d/boo','/tmp/e/f')
cp_parents('x/hi','/tmp/e/f/g') --> copies ./x/hi to /tmp/e/f/g/x/hi
|
[
"This",
"function",
"requires",
"Python",
">",
"=",
"3",
".",
"6",
"."
] |
859a91d3894cb57faed34881c6ea16130b90571e
|
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/cp_parents.py#L7-L35
|
240,083
|
kevinsprong23/aperture
|
aperture/set_plot_params.py
|
set_plot_params
|
def set_plot_params(theme=None):
"""
set plot parameters for session, as an alternative to
manipulating RC file
"""
# set solarized color progression no matter what
mpl.rcParams['axes.color_cycle'] = ('268bd2, dc322f, 859900, ' +
'b58900, d33682, 2aa198, ' +
'cb4b16, 002b36')
# non-color options are independent as well
mpl.rcParams['figure.figsize'] = 11, 8 # figure size in inches
mpl.rcParams['lines.linewidth'] = 2.0 # line width in points
mpl.rcParams['axes.grid'] = 'True' # display grid or not
mpl.rcParams['font.size'] = 18.0
mpl.rcParams['axes.titlesize'] = 18 # fontsize of the axes title
mpl.rcParams['axes.labelsize'] = 18 # fontsize of the x any y labels
mpl.rcParams['legend.fontsize'] = 18
mpl.rcParams['figure.edgecolor'] = 'None' # figure edgecolor
mpl.rcParams['savefig.edgecolor'] = 'None' # figure edgecolor saving
# color by theme
if theme == 'dark':
mpl.rcParams['text.color'] = "bbbbbb"
mpl.rcParams['axes.facecolor'] = '333333'
mpl.rcParams['axes.edgecolor'] = '999999' # axes edge color
mpl.rcParams['axes.labelcolor'] = 'bbbbbb'
mpl.rcParams['xtick.color'] = 'bbbbbb' # color of the tick labels
mpl.rcParams['ytick.color'] = 'bbbbbb' # color of the tick labels
mpl.rcParams['grid.color'] = 'bbbbbb' # grid color
mpl.rcParams['figure.facecolor'] = '333333' # figure facecolor
mpl.rcParams['savefig.facecolor'] = '333333' # figure facecolor saving
elif theme == 'white':
mpl.rcParams['text.color'] = "111111"
mpl.rcParams['axes.facecolor'] = 'ffffff'
mpl.rcParams['axes.edgecolor'] = '111111' # axes edge color
mpl.rcParams['axes.labelcolor'] = '111111'
mpl.rcParams['xtick.color'] = '111111' # color of the tick labels
mpl.rcParams['ytick.color'] = '111111' # color of the tick labels
mpl.rcParams['grid.color'] = '111111' # grid color
mpl.rcParams['figure.facecolor'] = 'ffffff' # figure facecolor
mpl.rcParams['savefig.facecolor'] = 'ffffff' # figure facecolor saving
else:
mpl.rcParams['text.color'] = "777777"
mpl.rcParams['axes.facecolor'] = 'f7f7f5'
mpl.rcParams['axes.edgecolor'] = '111111' # axes edge color
mpl.rcParams['axes.labelcolor'] = '777777'
mpl.rcParams['xtick.color'] = '777777' # color of the tick labels
mpl.rcParams['ytick.color'] = '777777' # color of the tick labels
mpl.rcParams['grid.color'] = '777777' # grid color
mpl.rcParams['figure.facecolor'] = 'f7f7f5' # figure facecolor
mpl.rcParams['savefig.facecolor'] = 'f7f7f5'
|
python
|
def set_plot_params(theme=None):
"""
set plot parameters for session, as an alternative to
manipulating RC file
"""
# set solarized color progression no matter what
mpl.rcParams['axes.color_cycle'] = ('268bd2, dc322f, 859900, ' +
'b58900, d33682, 2aa198, ' +
'cb4b16, 002b36')
# non-color options are independent as well
mpl.rcParams['figure.figsize'] = 11, 8 # figure size in inches
mpl.rcParams['lines.linewidth'] = 2.0 # line width in points
mpl.rcParams['axes.grid'] = 'True' # display grid or not
mpl.rcParams['font.size'] = 18.0
mpl.rcParams['axes.titlesize'] = 18 # fontsize of the axes title
mpl.rcParams['axes.labelsize'] = 18 # fontsize of the x any y labels
mpl.rcParams['legend.fontsize'] = 18
mpl.rcParams['figure.edgecolor'] = 'None' # figure edgecolor
mpl.rcParams['savefig.edgecolor'] = 'None' # figure edgecolor saving
# color by theme
if theme == 'dark':
mpl.rcParams['text.color'] = "bbbbbb"
mpl.rcParams['axes.facecolor'] = '333333'
mpl.rcParams['axes.edgecolor'] = '999999' # axes edge color
mpl.rcParams['axes.labelcolor'] = 'bbbbbb'
mpl.rcParams['xtick.color'] = 'bbbbbb' # color of the tick labels
mpl.rcParams['ytick.color'] = 'bbbbbb' # color of the tick labels
mpl.rcParams['grid.color'] = 'bbbbbb' # grid color
mpl.rcParams['figure.facecolor'] = '333333' # figure facecolor
mpl.rcParams['savefig.facecolor'] = '333333' # figure facecolor saving
elif theme == 'white':
mpl.rcParams['text.color'] = "111111"
mpl.rcParams['axes.facecolor'] = 'ffffff'
mpl.rcParams['axes.edgecolor'] = '111111' # axes edge color
mpl.rcParams['axes.labelcolor'] = '111111'
mpl.rcParams['xtick.color'] = '111111' # color of the tick labels
mpl.rcParams['ytick.color'] = '111111' # color of the tick labels
mpl.rcParams['grid.color'] = '111111' # grid color
mpl.rcParams['figure.facecolor'] = 'ffffff' # figure facecolor
mpl.rcParams['savefig.facecolor'] = 'ffffff' # figure facecolor saving
else:
mpl.rcParams['text.color'] = "777777"
mpl.rcParams['axes.facecolor'] = 'f7f7f5'
mpl.rcParams['axes.edgecolor'] = '111111' # axes edge color
mpl.rcParams['axes.labelcolor'] = '777777'
mpl.rcParams['xtick.color'] = '777777' # color of the tick labels
mpl.rcParams['ytick.color'] = '777777' # color of the tick labels
mpl.rcParams['grid.color'] = '777777' # grid color
mpl.rcParams['figure.facecolor'] = 'f7f7f5' # figure facecolor
mpl.rcParams['savefig.facecolor'] = 'f7f7f5'
|
[
"def",
"set_plot_params",
"(",
"theme",
"=",
"None",
")",
":",
"# set solarized color progression no matter what",
"mpl",
".",
"rcParams",
"[",
"'axes.color_cycle'",
"]",
"=",
"(",
"'268bd2, dc322f, 859900, '",
"+",
"'b58900, d33682, 2aa198, '",
"+",
"'cb4b16, 002b36'",
")",
"# non-color options are independent as well",
"mpl",
".",
"rcParams",
"[",
"'figure.figsize'",
"]",
"=",
"11",
",",
"8",
"# figure size in inches",
"mpl",
".",
"rcParams",
"[",
"'lines.linewidth'",
"]",
"=",
"2.0",
"# line width in points",
"mpl",
".",
"rcParams",
"[",
"'axes.grid'",
"]",
"=",
"'True'",
"# display grid or not",
"mpl",
".",
"rcParams",
"[",
"'font.size'",
"]",
"=",
"18.0",
"mpl",
".",
"rcParams",
"[",
"'axes.titlesize'",
"]",
"=",
"18",
"# fontsize of the axes title",
"mpl",
".",
"rcParams",
"[",
"'axes.labelsize'",
"]",
"=",
"18",
"# fontsize of the x any y labels",
"mpl",
".",
"rcParams",
"[",
"'legend.fontsize'",
"]",
"=",
"18",
"mpl",
".",
"rcParams",
"[",
"'figure.edgecolor'",
"]",
"=",
"'None'",
"# figure edgecolor",
"mpl",
".",
"rcParams",
"[",
"'savefig.edgecolor'",
"]",
"=",
"'None'",
"# figure edgecolor saving",
"# color by theme",
"if",
"theme",
"==",
"'dark'",
":",
"mpl",
".",
"rcParams",
"[",
"'text.color'",
"]",
"=",
"\"bbbbbb\"",
"mpl",
".",
"rcParams",
"[",
"'axes.facecolor'",
"]",
"=",
"'333333'",
"mpl",
".",
"rcParams",
"[",
"'axes.edgecolor'",
"]",
"=",
"'999999'",
"# axes edge color",
"mpl",
".",
"rcParams",
"[",
"'axes.labelcolor'",
"]",
"=",
"'bbbbbb'",
"mpl",
".",
"rcParams",
"[",
"'xtick.color'",
"]",
"=",
"'bbbbbb'",
"# color of the tick labels",
"mpl",
".",
"rcParams",
"[",
"'ytick.color'",
"]",
"=",
"'bbbbbb'",
"# color of the tick labels",
"mpl",
".",
"rcParams",
"[",
"'grid.color'",
"]",
"=",
"'bbbbbb'",
"# grid color",
"mpl",
".",
"rcParams",
"[",
"'figure.facecolor'",
"]",
"=",
"'333333'",
"# figure facecolor",
"mpl",
".",
"rcParams",
"[",
"'savefig.facecolor'",
"]",
"=",
"'333333'",
"# figure facecolor saving",
"elif",
"theme",
"==",
"'white'",
":",
"mpl",
".",
"rcParams",
"[",
"'text.color'",
"]",
"=",
"\"111111\"",
"mpl",
".",
"rcParams",
"[",
"'axes.facecolor'",
"]",
"=",
"'ffffff'",
"mpl",
".",
"rcParams",
"[",
"'axes.edgecolor'",
"]",
"=",
"'111111'",
"# axes edge color",
"mpl",
".",
"rcParams",
"[",
"'axes.labelcolor'",
"]",
"=",
"'111111'",
"mpl",
".",
"rcParams",
"[",
"'xtick.color'",
"]",
"=",
"'111111'",
"# color of the tick labels",
"mpl",
".",
"rcParams",
"[",
"'ytick.color'",
"]",
"=",
"'111111'",
"# color of the tick labels",
"mpl",
".",
"rcParams",
"[",
"'grid.color'",
"]",
"=",
"'111111'",
"# grid color",
"mpl",
".",
"rcParams",
"[",
"'figure.facecolor'",
"]",
"=",
"'ffffff'",
"# figure facecolor",
"mpl",
".",
"rcParams",
"[",
"'savefig.facecolor'",
"]",
"=",
"'ffffff'",
"# figure facecolor saving ",
"else",
":",
"mpl",
".",
"rcParams",
"[",
"'text.color'",
"]",
"=",
"\"777777\"",
"mpl",
".",
"rcParams",
"[",
"'axes.facecolor'",
"]",
"=",
"'f7f7f5'",
"mpl",
".",
"rcParams",
"[",
"'axes.edgecolor'",
"]",
"=",
"'111111'",
"# axes edge color",
"mpl",
".",
"rcParams",
"[",
"'axes.labelcolor'",
"]",
"=",
"'777777'",
"mpl",
".",
"rcParams",
"[",
"'xtick.color'",
"]",
"=",
"'777777'",
"# color of the tick labels",
"mpl",
".",
"rcParams",
"[",
"'ytick.color'",
"]",
"=",
"'777777'",
"# color of the tick labels",
"mpl",
".",
"rcParams",
"[",
"'grid.color'",
"]",
"=",
"'777777'",
"# grid color",
"mpl",
".",
"rcParams",
"[",
"'figure.facecolor'",
"]",
"=",
"'f7f7f5'",
"# figure facecolor",
"mpl",
".",
"rcParams",
"[",
"'savefig.facecolor'",
"]",
"=",
"'f7f7f5'"
] |
set plot parameters for session, as an alternative to
manipulating RC file
|
[
"set",
"plot",
"parameters",
"for",
"session",
"as",
"an",
"alternative",
"to",
"manipulating",
"RC",
"file"
] |
d0420fef3b25d8afc0e5ddcfb6fe5f0ff42b9799
|
https://github.com/kevinsprong23/aperture/blob/d0420fef3b25d8afc0e5ddcfb6fe5f0ff42b9799/aperture/set_plot_params.py#L7-L64
|
240,084
|
rsalmaso/django-fluo
|
fluo/management/commands/load_admin_data.py
|
Command.handle
|
def handle(self, *args, **options):
"""Load a default admin user"""
try:
admin = User.objects.get(username='admin')
except User.DoesNotExist:
admin = User(
username='admin',
first_name='admin',
last_name='admin',
email='admin@localhost.localdomain',
is_staff=True,
is_active=True,
is_superuser=True,
)
admin.set_password('admin')
admin.save()
|
python
|
def handle(self, *args, **options):
"""Load a default admin user"""
try:
admin = User.objects.get(username='admin')
except User.DoesNotExist:
admin = User(
username='admin',
first_name='admin',
last_name='admin',
email='admin@localhost.localdomain',
is_staff=True,
is_active=True,
is_superuser=True,
)
admin.set_password('admin')
admin.save()
|
[
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"try",
":",
"admin",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"'admin'",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"admin",
"=",
"User",
"(",
"username",
"=",
"'admin'",
",",
"first_name",
"=",
"'admin'",
",",
"last_name",
"=",
"'admin'",
",",
"email",
"=",
"'admin@localhost.localdomain'",
",",
"is_staff",
"=",
"True",
",",
"is_active",
"=",
"True",
",",
"is_superuser",
"=",
"True",
",",
")",
"admin",
".",
"set_password",
"(",
"'admin'",
")",
"admin",
".",
"save",
"(",
")"
] |
Load a default admin user
|
[
"Load",
"a",
"default",
"admin",
"user"
] |
1321c1e7d6a912108f79be02a9e7f2108c57f89f
|
https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/management/commands/load_admin_data.py#L30-L45
|
240,085
|
EnigmaBridge/client.py
|
ebclient/crypto_util.py
|
left_zero_pad
|
def left_zero_pad(s, blocksize):
"""
Left padding with zero bytes to a given block size
:param s:
:param blocksize:
:return:
"""
if blocksize > 0 and len(s) % blocksize:
s = (blocksize - len(s) % blocksize) * b('\000') + s
return s
|
python
|
def left_zero_pad(s, blocksize):
"""
Left padding with zero bytes to a given block size
:param s:
:param blocksize:
:return:
"""
if blocksize > 0 and len(s) % blocksize:
s = (blocksize - len(s) % blocksize) * b('\000') + s
return s
|
[
"def",
"left_zero_pad",
"(",
"s",
",",
"blocksize",
")",
":",
"if",
"blocksize",
">",
"0",
"and",
"len",
"(",
"s",
")",
"%",
"blocksize",
":",
"s",
"=",
"(",
"blocksize",
"-",
"len",
"(",
"s",
")",
"%",
"blocksize",
")",
"*",
"b",
"(",
"'\\000'",
")",
"+",
"s",
"return",
"s"
] |
Left padding with zero bytes to a given block size
:param s:
:param blocksize:
:return:
|
[
"Left",
"padding",
"with",
"zero",
"bytes",
"to",
"a",
"given",
"block",
"size"
] |
0fafe3902da394da88e9f960751d695ca65bbabd
|
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L129-L139
|
240,086
|
inveniosoftware-contrib/record-recommender
|
record_recommender/fetcher.py
|
_is_bot
|
def _is_bot(user_agent):
"""Check if user_agent is a known bot."""
bot_list = [
'http://www.baidu.com/search/spider.html',
'python-requests',
'http://ltx71.com/',
'http://drupal.org/',
'www.sogou.com',
'http://search.msn.com/msnbot.htm',
'semantic-visions.com crawler',
]
for bot in bot_list:
if re.search(re.escape(bot), user_agent):
return True
return False
|
python
|
def _is_bot(user_agent):
"""Check if user_agent is a known bot."""
bot_list = [
'http://www.baidu.com/search/spider.html',
'python-requests',
'http://ltx71.com/',
'http://drupal.org/',
'www.sogou.com',
'http://search.msn.com/msnbot.htm',
'semantic-visions.com crawler',
]
for bot in bot_list:
if re.search(re.escape(bot), user_agent):
return True
return False
|
[
"def",
"_is_bot",
"(",
"user_agent",
")",
":",
"bot_list",
"=",
"[",
"'http://www.baidu.com/search/spider.html'",
",",
"'python-requests'",
",",
"'http://ltx71.com/'",
",",
"'http://drupal.org/'",
",",
"'www.sogou.com'",
",",
"'http://search.msn.com/msnbot.htm'",
",",
"'semantic-visions.com crawler'",
",",
"]",
"for",
"bot",
"in",
"bot_list",
":",
"if",
"re",
".",
"search",
"(",
"re",
".",
"escape",
"(",
"bot",
")",
",",
"user_agent",
")",
":",
"return",
"True",
"return",
"False"
] |
Check if user_agent is a known bot.
|
[
"Check",
"if",
"user_agent",
"is",
"a",
"known",
"bot",
"."
] |
07f71e783369e6373218b5e6ba0bf15901e9251a
|
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L316-L330
|
240,087
|
inveniosoftware-contrib/record-recommender
|
record_recommender/fetcher.py
|
_is_download
|
def _is_download(ending):
"""Check if file ending is considered as download."""
list = [
'PDF',
'DOC',
'TXT',
'PPT',
'XLSX',
'MP3',
'SVG',
'7Z',
'HTML',
'TEX',
'MPP',
'ODT',
'RAR',
'ZIP',
'TAR',
'EPUB',
]
list_regex = [
'PDF'
]
if ending in list:
return True
for file_type in list_regex:
if re.search(re.escape(file_type), ending):
return True
return False
|
python
|
def _is_download(ending):
"""Check if file ending is considered as download."""
list = [
'PDF',
'DOC',
'TXT',
'PPT',
'XLSX',
'MP3',
'SVG',
'7Z',
'HTML',
'TEX',
'MPP',
'ODT',
'RAR',
'ZIP',
'TAR',
'EPUB',
]
list_regex = [
'PDF'
]
if ending in list:
return True
for file_type in list_regex:
if re.search(re.escape(file_type), ending):
return True
return False
|
[
"def",
"_is_download",
"(",
"ending",
")",
":",
"list",
"=",
"[",
"'PDF'",
",",
"'DOC'",
",",
"'TXT'",
",",
"'PPT'",
",",
"'XLSX'",
",",
"'MP3'",
",",
"'SVG'",
",",
"'7Z'",
",",
"'HTML'",
",",
"'TEX'",
",",
"'MPP'",
",",
"'ODT'",
",",
"'RAR'",
",",
"'ZIP'",
",",
"'TAR'",
",",
"'EPUB'",
",",
"]",
"list_regex",
"=",
"[",
"'PDF'",
"]",
"if",
"ending",
"in",
"list",
":",
"return",
"True",
"for",
"file_type",
"in",
"list_regex",
":",
"if",
"re",
".",
"search",
"(",
"re",
".",
"escape",
"(",
"file_type",
")",
",",
"ending",
")",
":",
"return",
"True",
"return",
"False"
] |
Check if file ending is considered as download.
|
[
"Check",
"if",
"file",
"ending",
"is",
"considered",
"as",
"download",
"."
] |
07f71e783369e6373218b5e6ba0bf15901e9251a
|
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L333-L361
|
240,088
|
inveniosoftware-contrib/record-recommender
|
record_recommender/fetcher.py
|
ElasticsearchFetcher.fetch
|
def fetch(self, year, week, overwrite=False):
"""Fetch PageViews and Downloads from Elasticsearch."""
self.config['overwrite_files'] = overwrite
time_start = time.time()
self._fetch_pageviews(self.storage, year, week, ip_users=False)
self._fetch_downloads(self.storage, year, week, ip_users=False)
# CDS has no user_agent before this date 1433400000:
self._fetch_pageviews(self.storage, year, week, ip_users=True)
self._fetch_downloads(self.storage, year, week, ip_users=True)
logger.info('Fetch %s-%s in %s seconds.', year, week,
time.time() - time_start)
|
python
|
def fetch(self, year, week, overwrite=False):
"""Fetch PageViews and Downloads from Elasticsearch."""
self.config['overwrite_files'] = overwrite
time_start = time.time()
self._fetch_pageviews(self.storage, year, week, ip_users=False)
self._fetch_downloads(self.storage, year, week, ip_users=False)
# CDS has no user_agent before this date 1433400000:
self._fetch_pageviews(self.storage, year, week, ip_users=True)
self._fetch_downloads(self.storage, year, week, ip_users=True)
logger.info('Fetch %s-%s in %s seconds.', year, week,
time.time() - time_start)
|
[
"def",
"fetch",
"(",
"self",
",",
"year",
",",
"week",
",",
"overwrite",
"=",
"False",
")",
":",
"self",
".",
"config",
"[",
"'overwrite_files'",
"]",
"=",
"overwrite",
"time_start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_fetch_pageviews",
"(",
"self",
".",
"storage",
",",
"year",
",",
"week",
",",
"ip_users",
"=",
"False",
")",
"self",
".",
"_fetch_downloads",
"(",
"self",
".",
"storage",
",",
"year",
",",
"week",
",",
"ip_users",
"=",
"False",
")",
"# CDS has no user_agent before this date 1433400000:",
"self",
".",
"_fetch_pageviews",
"(",
"self",
".",
"storage",
",",
"year",
",",
"week",
",",
"ip_users",
"=",
"True",
")",
"self",
".",
"_fetch_downloads",
"(",
"self",
".",
"storage",
",",
"year",
",",
"week",
",",
"ip_users",
"=",
"True",
")",
"logger",
".",
"info",
"(",
"'Fetch %s-%s in %s seconds.'",
",",
"year",
",",
"week",
",",
"time",
".",
"time",
"(",
")",
"-",
"time_start",
")"
] |
Fetch PageViews and Downloads from Elasticsearch.
|
[
"Fetch",
"PageViews",
"and",
"Downloads",
"from",
"Elasticsearch",
"."
] |
07f71e783369e6373218b5e6ba0bf15901e9251a
|
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L93-L103
|
240,089
|
inveniosoftware-contrib/record-recommender
|
record_recommender/fetcher.py
|
ElasticsearchFetcher._fetch_pageviews
|
def _fetch_pageviews(self, storage, year, week, ip_users=False):
"""
Fetch PageViews from Elasticsearch.
:param time_from: Staring at timestamp.
:param time_to: To timestamp
"""
prefix = 'Pageviews'
if ip_users:
query_add = "AND !(bot:True) AND (id_user:0)"
prefix += '_IP'
else:
query_add = "AND !(bot:True) AND !(id_user:0)"
store = self.storage.get(prefix, year, week)
if not self.config['overwrite_files'] and store.does_file_exist():
logger.debug("File already exist, skip: {}-{}".format(year, week))
return
store.open('overwrite')
time_from, time_to = get_week_dates(year, week, as_timestamp=True)
es_type = "events.pageviews"
es_query = self.ES_QUERY % {'timestamp_start': time_from * 1000,
'timestamp_end': time_to * 1000,
'event_name': es_type,
'query_add': query_add}
logger.info("{}: {} - {}".format(es_type, time_from, time_to))
for hit in self._fetch_elasticsearch(es_query):
item = {}
try:
item['user'] = hit['_source'].get('id_user')
if ip_users:
assert 0 == item['user']
else:
assert 0 != item['user']
assert es_type == hit['_type']
item['timestamp'] = float(hit['_source']['@timestamp']) / 1000
if ip_users:
item['ip'] = str(hit['_source'].get('client_host'))
user_agent = str(hit['_source'].get('user_agent'))
if user_agent is None or user_agent == 'None':
continue
elif _is_bot(user_agent):
continue
item['user_agent'] = user_agent
item['recid'] = int(hit['_source'].get('id_bibrec'))
except UnicodeEncodeError as e:
# TODO: Error logging.
# print(e)
continue
# Save entry
store.add_hit(item)
store.close()
# Delete File if no hits were added.
if store.number_of_hits == 0:
store.delete()
|
python
|
def _fetch_pageviews(self, storage, year, week, ip_users=False):
"""
Fetch PageViews from Elasticsearch.
:param time_from: Staring at timestamp.
:param time_to: To timestamp
"""
prefix = 'Pageviews'
if ip_users:
query_add = "AND !(bot:True) AND (id_user:0)"
prefix += '_IP'
else:
query_add = "AND !(bot:True) AND !(id_user:0)"
store = self.storage.get(prefix, year, week)
if not self.config['overwrite_files'] and store.does_file_exist():
logger.debug("File already exist, skip: {}-{}".format(year, week))
return
store.open('overwrite')
time_from, time_to = get_week_dates(year, week, as_timestamp=True)
es_type = "events.pageviews"
es_query = self.ES_QUERY % {'timestamp_start': time_from * 1000,
'timestamp_end': time_to * 1000,
'event_name': es_type,
'query_add': query_add}
logger.info("{}: {} - {}".format(es_type, time_from, time_to))
for hit in self._fetch_elasticsearch(es_query):
item = {}
try:
item['user'] = hit['_source'].get('id_user')
if ip_users:
assert 0 == item['user']
else:
assert 0 != item['user']
assert es_type == hit['_type']
item['timestamp'] = float(hit['_source']['@timestamp']) / 1000
if ip_users:
item['ip'] = str(hit['_source'].get('client_host'))
user_agent = str(hit['_source'].get('user_agent'))
if user_agent is None or user_agent == 'None':
continue
elif _is_bot(user_agent):
continue
item['user_agent'] = user_agent
item['recid'] = int(hit['_source'].get('id_bibrec'))
except UnicodeEncodeError as e:
# TODO: Error logging.
# print(e)
continue
# Save entry
store.add_hit(item)
store.close()
# Delete File if no hits were added.
if store.number_of_hits == 0:
store.delete()
|
[
"def",
"_fetch_pageviews",
"(",
"self",
",",
"storage",
",",
"year",
",",
"week",
",",
"ip_users",
"=",
"False",
")",
":",
"prefix",
"=",
"'Pageviews'",
"if",
"ip_users",
":",
"query_add",
"=",
"\"AND !(bot:True) AND (id_user:0)\"",
"prefix",
"+=",
"'_IP'",
"else",
":",
"query_add",
"=",
"\"AND !(bot:True) AND !(id_user:0)\"",
"store",
"=",
"self",
".",
"storage",
".",
"get",
"(",
"prefix",
",",
"year",
",",
"week",
")",
"if",
"not",
"self",
".",
"config",
"[",
"'overwrite_files'",
"]",
"and",
"store",
".",
"does_file_exist",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"File already exist, skip: {}-{}\"",
".",
"format",
"(",
"year",
",",
"week",
")",
")",
"return",
"store",
".",
"open",
"(",
"'overwrite'",
")",
"time_from",
",",
"time_to",
"=",
"get_week_dates",
"(",
"year",
",",
"week",
",",
"as_timestamp",
"=",
"True",
")",
"es_type",
"=",
"\"events.pageviews\"",
"es_query",
"=",
"self",
".",
"ES_QUERY",
"%",
"{",
"'timestamp_start'",
":",
"time_from",
"*",
"1000",
",",
"'timestamp_end'",
":",
"time_to",
"*",
"1000",
",",
"'event_name'",
":",
"es_type",
",",
"'query_add'",
":",
"query_add",
"}",
"logger",
".",
"info",
"(",
"\"{}: {} - {}\"",
".",
"format",
"(",
"es_type",
",",
"time_from",
",",
"time_to",
")",
")",
"for",
"hit",
"in",
"self",
".",
"_fetch_elasticsearch",
"(",
"es_query",
")",
":",
"item",
"=",
"{",
"}",
"try",
":",
"item",
"[",
"'user'",
"]",
"=",
"hit",
"[",
"'_source'",
"]",
".",
"get",
"(",
"'id_user'",
")",
"if",
"ip_users",
":",
"assert",
"0",
"==",
"item",
"[",
"'user'",
"]",
"else",
":",
"assert",
"0",
"!=",
"item",
"[",
"'user'",
"]",
"assert",
"es_type",
"==",
"hit",
"[",
"'_type'",
"]",
"item",
"[",
"'timestamp'",
"]",
"=",
"float",
"(",
"hit",
"[",
"'_source'",
"]",
"[",
"'@timestamp'",
"]",
")",
"/",
"1000",
"if",
"ip_users",
":",
"item",
"[",
"'ip'",
"]",
"=",
"str",
"(",
"hit",
"[",
"'_source'",
"]",
".",
"get",
"(",
"'client_host'",
")",
")",
"user_agent",
"=",
"str",
"(",
"hit",
"[",
"'_source'",
"]",
".",
"get",
"(",
"'user_agent'",
")",
")",
"if",
"user_agent",
"is",
"None",
"or",
"user_agent",
"==",
"'None'",
":",
"continue",
"elif",
"_is_bot",
"(",
"user_agent",
")",
":",
"continue",
"item",
"[",
"'user_agent'",
"]",
"=",
"user_agent",
"item",
"[",
"'recid'",
"]",
"=",
"int",
"(",
"hit",
"[",
"'_source'",
"]",
".",
"get",
"(",
"'id_bibrec'",
")",
")",
"except",
"UnicodeEncodeError",
"as",
"e",
":",
"# TODO: Error logging.",
"# print(e)",
"continue",
"# Save entry",
"store",
".",
"add_hit",
"(",
"item",
")",
"store",
".",
"close",
"(",
")",
"# Delete File if no hits were added.",
"if",
"store",
".",
"number_of_hits",
"==",
"0",
":",
"store",
".",
"delete",
"(",
")"
] |
Fetch PageViews from Elasticsearch.
:param time_from: Staring at timestamp.
:param time_to: To timestamp
|
[
"Fetch",
"PageViews",
"from",
"Elasticsearch",
"."
] |
07f71e783369e6373218b5e6ba0bf15901e9251a
|
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L105-L165
|
240,090
|
inveniosoftware-contrib/record-recommender
|
record_recommender/fetcher.py
|
ElasticsearchFetcher._fetch_elasticsearch
|
def _fetch_elasticsearch(self, es_query):
"""
Load data from Elasticsearch.
:param query: TODO
:param time_from: TODO
:param time_to: TODO
:returns: TODO
"""
# TODO: Show error if index is not found.
scanResp = self._esd.search(index=self.config['es_index'],
body=es_query, size=2000,
search_type="scan", scroll="10000",
timeout=900, request_timeout=900)
resp = dict(scanResp)
resp.pop('_scroll_id')
logger.debug(resp)
scroll_hits = scanResp['hits']['total']
scrollTime = scanResp['took']
scrollId = scanResp['_scroll_id']
# Check for shard errors
if scanResp['_shards']['failed'] > 0:
logger.warn("Failing shards, check ES")
retry_count = 0
number_of_retrys = 5
hit_count = 0
while True:
try:
response = self._esd.scroll(scroll_id=scrollId, scroll="10000",
request_timeout=900)
if response['_scroll_id'] != scrollId:
scrollId = response['_scroll_id']
if scanResp['_shards']['failed'] > 0:
print("Failing shards, check ES")
# No more hits
if len(response["hits"]["hits"]) == 0:
break
except esd_exceptions.ConnectionTimeout:
logger.warning("ES exceptions: Connection Timeout")
if retry_count >= number_of_retrys:
raise esd_exceptions.ConnectionTimeout()
retry_count += 1
continue
except StopIteration:
break
except Exception as e:
# TODO: Logging
logging.exception("ES exception", exc_info=True)
print("EXCEPTION")
print(e)
break
for hit in response["hits"]["hits"]:
yield hit
hit_count += 1
if hit_count > scroll_hits:
# More hits as expected, happens sometimes.
logger.info('More hits as expected %s/%s', hit_count, scroll_hits)
elif hit_count < scroll_hits:
# Less hits as expected, something went wrong.
logger.warn('Less hits as expected %s/%s', hit_count, scroll_hits)
logger.info('%s Hits', hit_count)
|
python
|
def _fetch_elasticsearch(self, es_query):
"""
Load data from Elasticsearch.
:param query: TODO
:param time_from: TODO
:param time_to: TODO
:returns: TODO
"""
# TODO: Show error if index is not found.
scanResp = self._esd.search(index=self.config['es_index'],
body=es_query, size=2000,
search_type="scan", scroll="10000",
timeout=900, request_timeout=900)
resp = dict(scanResp)
resp.pop('_scroll_id')
logger.debug(resp)
scroll_hits = scanResp['hits']['total']
scrollTime = scanResp['took']
scrollId = scanResp['_scroll_id']
# Check for shard errors
if scanResp['_shards']['failed'] > 0:
logger.warn("Failing shards, check ES")
retry_count = 0
number_of_retrys = 5
hit_count = 0
while True:
try:
response = self._esd.scroll(scroll_id=scrollId, scroll="10000",
request_timeout=900)
if response['_scroll_id'] != scrollId:
scrollId = response['_scroll_id']
if scanResp['_shards']['failed'] > 0:
print("Failing shards, check ES")
# No more hits
if len(response["hits"]["hits"]) == 0:
break
except esd_exceptions.ConnectionTimeout:
logger.warning("ES exceptions: Connection Timeout")
if retry_count >= number_of_retrys:
raise esd_exceptions.ConnectionTimeout()
retry_count += 1
continue
except StopIteration:
break
except Exception as e:
# TODO: Logging
logging.exception("ES exception", exc_info=True)
print("EXCEPTION")
print(e)
break
for hit in response["hits"]["hits"]:
yield hit
hit_count += 1
if hit_count > scroll_hits:
# More hits as expected, happens sometimes.
logger.info('More hits as expected %s/%s', hit_count, scroll_hits)
elif hit_count < scroll_hits:
# Less hits as expected, something went wrong.
logger.warn('Less hits as expected %s/%s', hit_count, scroll_hits)
logger.info('%s Hits', hit_count)
|
[
"def",
"_fetch_elasticsearch",
"(",
"self",
",",
"es_query",
")",
":",
"# TODO: Show error if index is not found.",
"scanResp",
"=",
"self",
".",
"_esd",
".",
"search",
"(",
"index",
"=",
"self",
".",
"config",
"[",
"'es_index'",
"]",
",",
"body",
"=",
"es_query",
",",
"size",
"=",
"2000",
",",
"search_type",
"=",
"\"scan\"",
",",
"scroll",
"=",
"\"10000\"",
",",
"timeout",
"=",
"900",
",",
"request_timeout",
"=",
"900",
")",
"resp",
"=",
"dict",
"(",
"scanResp",
")",
"resp",
".",
"pop",
"(",
"'_scroll_id'",
")",
"logger",
".",
"debug",
"(",
"resp",
")",
"scroll_hits",
"=",
"scanResp",
"[",
"'hits'",
"]",
"[",
"'total'",
"]",
"scrollTime",
"=",
"scanResp",
"[",
"'took'",
"]",
"scrollId",
"=",
"scanResp",
"[",
"'_scroll_id'",
"]",
"# Check for shard errors",
"if",
"scanResp",
"[",
"'_shards'",
"]",
"[",
"'failed'",
"]",
">",
"0",
":",
"logger",
".",
"warn",
"(",
"\"Failing shards, check ES\"",
")",
"retry_count",
"=",
"0",
"number_of_retrys",
"=",
"5",
"hit_count",
"=",
"0",
"while",
"True",
":",
"try",
":",
"response",
"=",
"self",
".",
"_esd",
".",
"scroll",
"(",
"scroll_id",
"=",
"scrollId",
",",
"scroll",
"=",
"\"10000\"",
",",
"request_timeout",
"=",
"900",
")",
"if",
"response",
"[",
"'_scroll_id'",
"]",
"!=",
"scrollId",
":",
"scrollId",
"=",
"response",
"[",
"'_scroll_id'",
"]",
"if",
"scanResp",
"[",
"'_shards'",
"]",
"[",
"'failed'",
"]",
">",
"0",
":",
"print",
"(",
"\"Failing shards, check ES\"",
")",
"# No more hits",
"if",
"len",
"(",
"response",
"[",
"\"hits\"",
"]",
"[",
"\"hits\"",
"]",
")",
"==",
"0",
":",
"break",
"except",
"esd_exceptions",
".",
"ConnectionTimeout",
":",
"logger",
".",
"warning",
"(",
"\"ES exceptions: Connection Timeout\"",
")",
"if",
"retry_count",
">=",
"number_of_retrys",
":",
"raise",
"esd_exceptions",
".",
"ConnectionTimeout",
"(",
")",
"retry_count",
"+=",
"1",
"continue",
"except",
"StopIteration",
":",
"break",
"except",
"Exception",
"as",
"e",
":",
"# TODO: Logging",
"logging",
".",
"exception",
"(",
"\"ES exception\"",
",",
"exc_info",
"=",
"True",
")",
"print",
"(",
"\"EXCEPTION\"",
")",
"print",
"(",
"e",
")",
"break",
"for",
"hit",
"in",
"response",
"[",
"\"hits\"",
"]",
"[",
"\"hits\"",
"]",
":",
"yield",
"hit",
"hit_count",
"+=",
"1",
"if",
"hit_count",
">",
"scroll_hits",
":",
"# More hits as expected, happens sometimes.",
"logger",
".",
"info",
"(",
"'More hits as expected %s/%s'",
",",
"hit_count",
",",
"scroll_hits",
")",
"elif",
"hit_count",
"<",
"scroll_hits",
":",
"# Less hits as expected, something went wrong.",
"logger",
".",
"warn",
"(",
"'Less hits as expected %s/%s'",
",",
"hit_count",
",",
"scroll_hits",
")",
"logger",
".",
"info",
"(",
"'%s Hits'",
",",
"hit_count",
")"
] |
Load data from Elasticsearch.
:param query: TODO
:param time_from: TODO
:param time_to: TODO
:returns: TODO
|
[
"Load",
"data",
"from",
"Elasticsearch",
"."
] |
07f71e783369e6373218b5e6ba0bf15901e9251a
|
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L247-L313
|
240,091
|
diffeo/rejester
|
rejester/_queue.py
|
RejesterQueue.dump_queue
|
def dump_queue(self, *names):
"""Debug-log some of the queues.
``names`` may include any of "worker", "available", "priorities",
"expiration", "workers", or "reservations_ITEM" filling in some
specific item.
"""
conn = redis.StrictRedis(connection_pool=self.pool)
for name in names:
if name == 'worker':
logger.debug('last worker: ' + conn.get(self._key_worker()))
elif name == 'available':
logger.debug('available: ' +
str(conn.zrevrange(self._key_available(), 0, -1,
withscores=True)))
elif name == 'priorities':
logger.debug('priorities: ' +
str(conn.hgetall(self._key_priorities())))
elif name == 'expiration':
logger.debug('expiration: ' +
str(conn.zrevrange(self._key_expiration(), 0, -1,
withscores=True)))
elif name == 'workers':
logger.debug('workers: ' +
str(conn.hgetall(self._key_workers())))
elif name.startswith('reservations_'):
item = name[len('reservations_'):]
logger.debug('reservations for ' + item + ': ' +
str(conn.smembers(self._key_reservations(item))))
|
python
|
def dump_queue(self, *names):
"""Debug-log some of the queues.
``names`` may include any of "worker", "available", "priorities",
"expiration", "workers", or "reservations_ITEM" filling in some
specific item.
"""
conn = redis.StrictRedis(connection_pool=self.pool)
for name in names:
if name == 'worker':
logger.debug('last worker: ' + conn.get(self._key_worker()))
elif name == 'available':
logger.debug('available: ' +
str(conn.zrevrange(self._key_available(), 0, -1,
withscores=True)))
elif name == 'priorities':
logger.debug('priorities: ' +
str(conn.hgetall(self._key_priorities())))
elif name == 'expiration':
logger.debug('expiration: ' +
str(conn.zrevrange(self._key_expiration(), 0, -1,
withscores=True)))
elif name == 'workers':
logger.debug('workers: ' +
str(conn.hgetall(self._key_workers())))
elif name.startswith('reservations_'):
item = name[len('reservations_'):]
logger.debug('reservations for ' + item + ': ' +
str(conn.smembers(self._key_reservations(item))))
|
[
"def",
"dump_queue",
"(",
"self",
",",
"*",
"names",
")",
":",
"conn",
"=",
"redis",
".",
"StrictRedis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"==",
"'worker'",
":",
"logger",
".",
"debug",
"(",
"'last worker: '",
"+",
"conn",
".",
"get",
"(",
"self",
".",
"_key_worker",
"(",
")",
")",
")",
"elif",
"name",
"==",
"'available'",
":",
"logger",
".",
"debug",
"(",
"'available: '",
"+",
"str",
"(",
"conn",
".",
"zrevrange",
"(",
"self",
".",
"_key_available",
"(",
")",
",",
"0",
",",
"-",
"1",
",",
"withscores",
"=",
"True",
")",
")",
")",
"elif",
"name",
"==",
"'priorities'",
":",
"logger",
".",
"debug",
"(",
"'priorities: '",
"+",
"str",
"(",
"conn",
".",
"hgetall",
"(",
"self",
".",
"_key_priorities",
"(",
")",
")",
")",
")",
"elif",
"name",
"==",
"'expiration'",
":",
"logger",
".",
"debug",
"(",
"'expiration: '",
"+",
"str",
"(",
"conn",
".",
"zrevrange",
"(",
"self",
".",
"_key_expiration",
"(",
")",
",",
"0",
",",
"-",
"1",
",",
"withscores",
"=",
"True",
")",
")",
")",
"elif",
"name",
"==",
"'workers'",
":",
"logger",
".",
"debug",
"(",
"'workers: '",
"+",
"str",
"(",
"conn",
".",
"hgetall",
"(",
"self",
".",
"_key_workers",
"(",
")",
")",
")",
")",
"elif",
"name",
".",
"startswith",
"(",
"'reservations_'",
")",
":",
"item",
"=",
"name",
"[",
"len",
"(",
"'reservations_'",
")",
":",
"]",
"logger",
".",
"debug",
"(",
"'reservations for '",
"+",
"item",
"+",
"': '",
"+",
"str",
"(",
"conn",
".",
"smembers",
"(",
"self",
".",
"_key_reservations",
"(",
"item",
")",
")",
")",
")"
] |
Debug-log some of the queues.
``names`` may include any of "worker", "available", "priorities",
"expiration", "workers", or "reservations_ITEM" filling in some
specific item.
|
[
"Debug",
"-",
"log",
"some",
"of",
"the",
"queues",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L91-L120
|
240,092
|
diffeo/rejester
|
rejester/_queue.py
|
RejesterQueue.worker_id
|
def worker_id(self):
"""A unique identifier for this queue instance and the items it owns."""
if self._worker_id is not None: return self._worker_id
return self._get_worker_id(self._conn())
|
python
|
def worker_id(self):
"""A unique identifier for this queue instance and the items it owns."""
if self._worker_id is not None: return self._worker_id
return self._get_worker_id(self._conn())
|
[
"def",
"worker_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"_worker_id",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_worker_id",
"return",
"self",
".",
"_get_worker_id",
"(",
"self",
".",
"_conn",
"(",
")",
")"
] |
A unique identifier for this queue instance and the items it owns.
|
[
"A",
"unique",
"identifier",
"for",
"this",
"queue",
"instance",
"and",
"the",
"items",
"it",
"owns",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L123-L126
|
240,093
|
diffeo/rejester
|
rejester/_queue.py
|
RejesterQueue._get_worker_id
|
def _get_worker_id(self, conn):
"""Get the worker ID, using a preestablished connection."""
if self._worker_id is None:
self._worker_id = conn.incr(self._key_worker())
return self._worker_id
|
python
|
def _get_worker_id(self, conn):
"""Get the worker ID, using a preestablished connection."""
if self._worker_id is None:
self._worker_id = conn.incr(self._key_worker())
return self._worker_id
|
[
"def",
"_get_worker_id",
"(",
"self",
",",
"conn",
")",
":",
"if",
"self",
".",
"_worker_id",
"is",
"None",
":",
"self",
".",
"_worker_id",
"=",
"conn",
".",
"incr",
"(",
"self",
".",
"_key_worker",
"(",
")",
")",
"return",
"self",
".",
"_worker_id"
] |
Get the worker ID, using a preestablished connection.
|
[
"Get",
"the",
"worker",
"ID",
"using",
"a",
"preestablished",
"connection",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L137-L141
|
240,094
|
diffeo/rejester
|
rejester/_queue.py
|
RejesterQueue.add_item
|
def add_item(self, item, priority):
"""Add ``item`` to this queue.
It will have the specified ``priority`` (highest priority runs
first). If it is already in the queue, fail if it is checked
out or reserved, or change its priority to ``priority``
otherwise.
"""
conn = self._conn()
self._run_expiration(conn)
script = conn.register_script("""
if (redis.call("hexists", KEYS[2], ARGV[1]) ~= 0) and
not(redis.call("zscore", KEYS[1], ARGV[1]))
then
return -1
end
redis.call("zadd", KEYS[1], ARGV[2], ARGV[1])
redis.call("hset", KEYS[2], ARGV[1], ARGV[2])
return 0
""")
result = script(keys=[self._key_available(), self._key_priorities()],
args=[item, priority])
if result == -1:
raise ItemInUseError(item)
return
|
python
|
def add_item(self, item, priority):
"""Add ``item`` to this queue.
It will have the specified ``priority`` (highest priority runs
first). If it is already in the queue, fail if it is checked
out or reserved, or change its priority to ``priority``
otherwise.
"""
conn = self._conn()
self._run_expiration(conn)
script = conn.register_script("""
if (redis.call("hexists", KEYS[2], ARGV[1]) ~= 0) and
not(redis.call("zscore", KEYS[1], ARGV[1]))
then
return -1
end
redis.call("zadd", KEYS[1], ARGV[2], ARGV[1])
redis.call("hset", KEYS[2], ARGV[1], ARGV[2])
return 0
""")
result = script(keys=[self._key_available(), self._key_priorities()],
args=[item, priority])
if result == -1:
raise ItemInUseError(item)
return
|
[
"def",
"add_item",
"(",
"self",
",",
"item",
",",
"priority",
")",
":",
"conn",
"=",
"self",
".",
"_conn",
"(",
")",
"self",
".",
"_run_expiration",
"(",
"conn",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"\"\"\"\n if (redis.call(\"hexists\", KEYS[2], ARGV[1]) ~= 0) and\n not(redis.call(\"zscore\", KEYS[1], ARGV[1]))\n then\n return -1\n end\n redis.call(\"zadd\", KEYS[1], ARGV[2], ARGV[1])\n redis.call(\"hset\", KEYS[2], ARGV[1], ARGV[2])\n return 0\n \"\"\"",
")",
"result",
"=",
"script",
"(",
"keys",
"=",
"[",
"self",
".",
"_key_available",
"(",
")",
",",
"self",
".",
"_key_priorities",
"(",
")",
"]",
",",
"args",
"=",
"[",
"item",
",",
"priority",
"]",
")",
"if",
"result",
"==",
"-",
"1",
":",
"raise",
"ItemInUseError",
"(",
"item",
")",
"return"
] |
Add ``item`` to this queue.
It will have the specified ``priority`` (highest priority runs
first). If it is already in the queue, fail if it is checked
out or reserved, or change its priority to ``priority``
otherwise.
|
[
"Add",
"item",
"to",
"this",
"queue",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L143-L168
|
240,095
|
diffeo/rejester
|
rejester/_queue.py
|
RejesterQueue.check_out_item
|
def check_out_item(self, expiration):
"""Get the highest-priority item out of this queue.
Returns the item, or None if no items are available. The item
must be either ``return_item()`` or ``renew_item()`` before
``expiration`` seconds pass, or it will become available to
future callers. The item will be marked as being owned by
``worker_id``.
"""
conn = redis.StrictRedis(connection_pool=self.pool)
self._run_expiration(conn)
expiration += time.time()
script = conn.register_script("""
local item = redis.call("zrevrange", KEYS[1], 0, 0)
if #item == 0 then return nil end
item = item[1]
redis.call("zrem", KEYS[1], item)
redis.call("zadd", KEYS[2], ARGV[1], item)
redis.call("hset", KEYS[3], "i" .. item, "w" .. ARGV[2])
redis.call("hset", KEYS[3], "w" .. ARGV[2], "i" .. item)
return item
""")
result = script(keys=[self._key_available(), self._key_expiration(),
self._key_workers()],
args=[expiration, self._get_worker_id(conn)])
return result
|
python
|
def check_out_item(self, expiration):
"""Get the highest-priority item out of this queue.
Returns the item, or None if no items are available. The item
must be either ``return_item()`` or ``renew_item()`` before
``expiration`` seconds pass, or it will become available to
future callers. The item will be marked as being owned by
``worker_id``.
"""
conn = redis.StrictRedis(connection_pool=self.pool)
self._run_expiration(conn)
expiration += time.time()
script = conn.register_script("""
local item = redis.call("zrevrange", KEYS[1], 0, 0)
if #item == 0 then return nil end
item = item[1]
redis.call("zrem", KEYS[1], item)
redis.call("zadd", KEYS[2], ARGV[1], item)
redis.call("hset", KEYS[3], "i" .. item, "w" .. ARGV[2])
redis.call("hset", KEYS[3], "w" .. ARGV[2], "i" .. item)
return item
""")
result = script(keys=[self._key_available(), self._key_expiration(),
self._key_workers()],
args=[expiration, self._get_worker_id(conn)])
return result
|
[
"def",
"check_out_item",
"(",
"self",
",",
"expiration",
")",
":",
"conn",
"=",
"redis",
".",
"StrictRedis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"self",
".",
"_run_expiration",
"(",
"conn",
")",
"expiration",
"+=",
"time",
".",
"time",
"(",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"\"\"\"\n local item = redis.call(\"zrevrange\", KEYS[1], 0, 0)\n if #item == 0 then return nil end\n item = item[1]\n redis.call(\"zrem\", KEYS[1], item)\n redis.call(\"zadd\", KEYS[2], ARGV[1], item)\n redis.call(\"hset\", KEYS[3], \"i\" .. item, \"w\" .. ARGV[2])\n redis.call(\"hset\", KEYS[3], \"w\" .. ARGV[2], \"i\" .. item)\n return item\n \"\"\"",
")",
"result",
"=",
"script",
"(",
"keys",
"=",
"[",
"self",
".",
"_key_available",
"(",
")",
",",
"self",
".",
"_key_expiration",
"(",
")",
",",
"self",
".",
"_key_workers",
"(",
")",
"]",
",",
"args",
"=",
"[",
"expiration",
",",
"self",
".",
"_get_worker_id",
"(",
"conn",
")",
"]",
")",
"return",
"result"
] |
Get the highest-priority item out of this queue.
Returns the item, or None if no items are available. The item
must be either ``return_item()`` or ``renew_item()`` before
``expiration`` seconds pass, or it will become available to
future callers. The item will be marked as being owned by
``worker_id``.
|
[
"Get",
"the",
"highest",
"-",
"priority",
"item",
"out",
"of",
"this",
"queue",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L170-L196
|
240,096
|
diffeo/rejester
|
rejester/_queue.py
|
RejesterQueue.renew_item
|
def renew_item(self, item, expiration):
"""Update the expiration time for ``item``.
The item will remain checked out for ``expiration`` seconds
beyond the current time. This queue instance must have
already checked out ``item``, and this method can fail if
``item`` is already overdue.
"""
conn = self._conn()
self._run_expiration(conn)
expiration += time.time()
script = conn.register_script("""
-- already expired?
if redis.call("hget", KEYS[2], "i" .. ARGV[1]) ~= "w" .. ARGV[3]
then return -1 end
-- otherwise just update the expiration
redis.call("zadd", KEYS[1], ARGV[2], ARGV[1])
return 0
""")
result = script(keys=[self._key_expiration(), self._key_workers()],
args=[item, expiration, self._get_worker_id(conn)])
if result == -1:
raise LostLease(item)
return
|
python
|
def renew_item(self, item, expiration):
"""Update the expiration time for ``item``.
The item will remain checked out for ``expiration`` seconds
beyond the current time. This queue instance must have
already checked out ``item``, and this method can fail if
``item`` is already overdue.
"""
conn = self._conn()
self._run_expiration(conn)
expiration += time.time()
script = conn.register_script("""
-- already expired?
if redis.call("hget", KEYS[2], "i" .. ARGV[1]) ~= "w" .. ARGV[3]
then return -1 end
-- otherwise just update the expiration
redis.call("zadd", KEYS[1], ARGV[2], ARGV[1])
return 0
""")
result = script(keys=[self._key_expiration(), self._key_workers()],
args=[item, expiration, self._get_worker_id(conn)])
if result == -1:
raise LostLease(item)
return
|
[
"def",
"renew_item",
"(",
"self",
",",
"item",
",",
"expiration",
")",
":",
"conn",
"=",
"self",
".",
"_conn",
"(",
")",
"self",
".",
"_run_expiration",
"(",
"conn",
")",
"expiration",
"+=",
"time",
".",
"time",
"(",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"\"\"\"\n -- already expired?\n if redis.call(\"hget\", KEYS[2], \"i\" .. ARGV[1]) ~= \"w\" .. ARGV[3]\n then return -1 end\n\n -- otherwise just update the expiration\n redis.call(\"zadd\", KEYS[1], ARGV[2], ARGV[1])\n return 0\n \"\"\"",
")",
"result",
"=",
"script",
"(",
"keys",
"=",
"[",
"self",
".",
"_key_expiration",
"(",
")",
",",
"self",
".",
"_key_workers",
"(",
")",
"]",
",",
"args",
"=",
"[",
"item",
",",
"expiration",
",",
"self",
".",
"_get_worker_id",
"(",
"conn",
")",
"]",
")",
"if",
"result",
"==",
"-",
"1",
":",
"raise",
"LostLease",
"(",
"item",
")",
"return"
] |
Update the expiration time for ``item``.
The item will remain checked out for ``expiration`` seconds
beyond the current time. This queue instance must have
already checked out ``item``, and this method can fail if
``item`` is already overdue.
|
[
"Update",
"the",
"expiration",
"time",
"for",
"item",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L198-L223
|
240,097
|
diffeo/rejester
|
rejester/_queue.py
|
RejesterQueue.reserve_items
|
def reserve_items(self, parent_item, *items):
"""Reserve a set of items until a parent item is returned.
Prevent ``check_out_item()`` from returning any of ``items``
until ``parent_item`` is completed or times out. For each
item, if it is not already checked out or reserved by some
other parent item, it is associated with ``parent_item``, and
the reservation will be released when ``parent_item``
completes or times out. Returns a list that is a subset of
``items`` for which we could get the reservation.
Raises ``LostLease`` if this queue instance no longer owns
``parent_item``. If any of the items do not exist, they are
silently ignored.
"""
conn = redis.StrictRedis(connection_pool=self.pool)
self._run_expiration(conn)
script = conn.register_script("""
-- expired?
if redis.call("hget", KEYS[2], "i" .. ARGV[1]) ~= "w" .. ARGV[2]
then return -1 end
-- loop through each item
local result = {}
for i = 3, #ARGV do
local item = ARGV[i]
-- item must be available to reserve
if redis.call("zscore", KEYS[1], item) then
redis.call("zrem", KEYS[1], item)
redis.call("sadd", KEYS[3], item)
result[#result + 1] = item
end
end
return result
""")
result = script(keys=[self._key_available(), self._key_workers(),
self._key_reservations(parent_item)],
args=([parent_item, self._get_worker_id(conn)] +
list(items)))
if result == -1:
raise LostLease(parent_item)
return result
|
python
|
def reserve_items(self, parent_item, *items):
"""Reserve a set of items until a parent item is returned.
Prevent ``check_out_item()`` from returning any of ``items``
until ``parent_item`` is completed or times out. For each
item, if it is not already checked out or reserved by some
other parent item, it is associated with ``parent_item``, and
the reservation will be released when ``parent_item``
completes or times out. Returns a list that is a subset of
``items`` for which we could get the reservation.
Raises ``LostLease`` if this queue instance no longer owns
``parent_item``. If any of the items do not exist, they are
silently ignored.
"""
conn = redis.StrictRedis(connection_pool=self.pool)
self._run_expiration(conn)
script = conn.register_script("""
-- expired?
if redis.call("hget", KEYS[2], "i" .. ARGV[1]) ~= "w" .. ARGV[2]
then return -1 end
-- loop through each item
local result = {}
for i = 3, #ARGV do
local item = ARGV[i]
-- item must be available to reserve
if redis.call("zscore", KEYS[1], item) then
redis.call("zrem", KEYS[1], item)
redis.call("sadd", KEYS[3], item)
result[#result + 1] = item
end
end
return result
""")
result = script(keys=[self._key_available(), self._key_workers(),
self._key_reservations(parent_item)],
args=([parent_item, self._get_worker_id(conn)] +
list(items)))
if result == -1:
raise LostLease(parent_item)
return result
|
[
"def",
"reserve_items",
"(",
"self",
",",
"parent_item",
",",
"*",
"items",
")",
":",
"conn",
"=",
"redis",
".",
"StrictRedis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"self",
".",
"_run_expiration",
"(",
"conn",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"\"\"\"\n -- expired?\n if redis.call(\"hget\", KEYS[2], \"i\" .. ARGV[1]) ~= \"w\" .. ARGV[2]\n then return -1 end\n\n -- loop through each item\n local result = {}\n for i = 3, #ARGV do\n local item = ARGV[i]\n -- item must be available to reserve\n if redis.call(\"zscore\", KEYS[1], item) then\n redis.call(\"zrem\", KEYS[1], item)\n redis.call(\"sadd\", KEYS[3], item)\n result[#result + 1] = item\n end\n end\n return result\n \"\"\"",
")",
"result",
"=",
"script",
"(",
"keys",
"=",
"[",
"self",
".",
"_key_available",
"(",
")",
",",
"self",
".",
"_key_workers",
"(",
")",
",",
"self",
".",
"_key_reservations",
"(",
"parent_item",
")",
"]",
",",
"args",
"=",
"(",
"[",
"parent_item",
",",
"self",
".",
"_get_worker_id",
"(",
"conn",
")",
"]",
"+",
"list",
"(",
"items",
")",
")",
")",
"if",
"result",
"==",
"-",
"1",
":",
"raise",
"LostLease",
"(",
"parent_item",
")",
"return",
"result"
] |
Reserve a set of items until a parent item is returned.
Prevent ``check_out_item()`` from returning any of ``items``
until ``parent_item`` is completed or times out. For each
item, if it is not already checked out or reserved by some
other parent item, it is associated with ``parent_item``, and
the reservation will be released when ``parent_item``
completes or times out. Returns a list that is a subset of
``items`` for which we could get the reservation.
Raises ``LostLease`` if this queue instance no longer owns
``parent_item``. If any of the items do not exist, they are
silently ignored.
|
[
"Reserve",
"a",
"set",
"of",
"items",
"until",
"a",
"parent",
"item",
"is",
"returned",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L273-L315
|
240,098
|
diffeo/rejester
|
rejester/_queue.py
|
RejesterQueue._run_expiration
|
def _run_expiration(self, conn):
"""Return any items that have expired."""
# The logic here is sufficiently complicated, and we need
# enough random keys (Redis documentation strongly encourages
# not constructing key names in scripts) that we'll need to
# do this in multiple steps. This means that, when we do
# go in and actually expire things, we need to first check
# that they're still running.
# Get, and clear out, the list of expiring items
now = time.time()
script = conn.register_script("""
local result = redis.call("zrangebyscore", KEYS[1], 0, ARGV[1])
redis.call("zremrangebyscore", KEYS[1], 0, ARGV[1])
return result
""")
expiring = script(keys=[self._key_expiration()], args=[time.time()])
# Manually expire each item one by one
script = conn.register_script("""
-- item may have fallen out of the worker list, if someone finished
-- at just the very last possible moment (phew!)
local wworker = redis.call("hget", KEYS[3], "i" .. ARGV[1])
if not wworker then return end
-- we want to return item, plus everything it's reserved
local to_return = redis.call("smembers", KEYS[4])
to_return[#to_return + 1] = ARGV[1]
for i = 1, #to_return do
local pri = redis.call("hget", KEYS[2], to_return[i])
redis.call("zadd", KEYS[1], pri, to_return[i])
end
-- already removed from expiration list
-- remove from worker list too
redis.call("hdel", KEYS[3], "i" .. ARGV[1])
redis.call("hdel", KEYS[3], wworker)
""")
for item in expiring:
script(keys=[self._key_available(), self._key_priorities(),
self._key_workers(), self._key_reservations(item)],
args=[item])
|
python
|
def _run_expiration(self, conn):
"""Return any items that have expired."""
# The logic here is sufficiently complicated, and we need
# enough random keys (Redis documentation strongly encourages
# not constructing key names in scripts) that we'll need to
# do this in multiple steps. This means that, when we do
# go in and actually expire things, we need to first check
# that they're still running.
# Get, and clear out, the list of expiring items
now = time.time()
script = conn.register_script("""
local result = redis.call("zrangebyscore", KEYS[1], 0, ARGV[1])
redis.call("zremrangebyscore", KEYS[1], 0, ARGV[1])
return result
""")
expiring = script(keys=[self._key_expiration()], args=[time.time()])
# Manually expire each item one by one
script = conn.register_script("""
-- item may have fallen out of the worker list, if someone finished
-- at just the very last possible moment (phew!)
local wworker = redis.call("hget", KEYS[3], "i" .. ARGV[1])
if not wworker then return end
-- we want to return item, plus everything it's reserved
local to_return = redis.call("smembers", KEYS[4])
to_return[#to_return + 1] = ARGV[1]
for i = 1, #to_return do
local pri = redis.call("hget", KEYS[2], to_return[i])
redis.call("zadd", KEYS[1], pri, to_return[i])
end
-- already removed from expiration list
-- remove from worker list too
redis.call("hdel", KEYS[3], "i" .. ARGV[1])
redis.call("hdel", KEYS[3], wworker)
""")
for item in expiring:
script(keys=[self._key_available(), self._key_priorities(),
self._key_workers(), self._key_reservations(item)],
args=[item])
|
[
"def",
"_run_expiration",
"(",
"self",
",",
"conn",
")",
":",
"# The logic here is sufficiently complicated, and we need",
"# enough random keys (Redis documentation strongly encourages",
"# not constructing key names in scripts) that we'll need to",
"# do this in multiple steps. This means that, when we do",
"# go in and actually expire things, we need to first check",
"# that they're still running.",
"# Get, and clear out, the list of expiring items",
"now",
"=",
"time",
".",
"time",
"(",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"\"\"\"\n local result = redis.call(\"zrangebyscore\", KEYS[1], 0, ARGV[1])\n redis.call(\"zremrangebyscore\", KEYS[1], 0, ARGV[1])\n return result\n \"\"\"",
")",
"expiring",
"=",
"script",
"(",
"keys",
"=",
"[",
"self",
".",
"_key_expiration",
"(",
")",
"]",
",",
"args",
"=",
"[",
"time",
".",
"time",
"(",
")",
"]",
")",
"# Manually expire each item one by one",
"script",
"=",
"conn",
".",
"register_script",
"(",
"\"\"\"\n -- item may have fallen out of the worker list, if someone finished\n -- at just the very last possible moment (phew!)\n local wworker = redis.call(\"hget\", KEYS[3], \"i\" .. ARGV[1])\n if not wworker then return end\n\n -- we want to return item, plus everything it's reserved\n local to_return = redis.call(\"smembers\", KEYS[4])\n to_return[#to_return + 1] = ARGV[1]\n for i = 1, #to_return do\n local pri = redis.call(\"hget\", KEYS[2], to_return[i])\n redis.call(\"zadd\", KEYS[1], pri, to_return[i])\n end\n -- already removed from expiration list\n -- remove from worker list too\n redis.call(\"hdel\", KEYS[3], \"i\" .. ARGV[1])\n redis.call(\"hdel\", KEYS[3], wworker)\n \"\"\"",
")",
"for",
"item",
"in",
"expiring",
":",
"script",
"(",
"keys",
"=",
"[",
"self",
".",
"_key_available",
"(",
")",
",",
"self",
".",
"_key_priorities",
"(",
")",
",",
"self",
".",
"_key_workers",
"(",
")",
",",
"self",
".",
"_key_reservations",
"(",
"item",
")",
"]",
",",
"args",
"=",
"[",
"item",
"]",
")"
] |
Return any items that have expired.
|
[
"Return",
"any",
"items",
"that",
"have",
"expired",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_queue.py#L317-L357
|
240,099
|
zacernst/timed_dict
|
timed_dict/timed_dict.py
|
cleanup_sweep_threads
|
def cleanup_sweep_threads():
'''
Not used. Keeping this function in case we decide not to use
daemonized threads and it becomes necessary to clean up the
running threads upon exit.
'''
for dict_name, obj in globals().items():
if isinstance(obj, (TimedDict,)):
logging.info(
'Stopping thread for TimedDict {dict_name}'.format(
dict_name=dict_name))
obj.stop_sweep()
|
python
|
def cleanup_sweep_threads():
'''
Not used. Keeping this function in case we decide not to use
daemonized threads and it becomes necessary to clean up the
running threads upon exit.
'''
for dict_name, obj in globals().items():
if isinstance(obj, (TimedDict,)):
logging.info(
'Stopping thread for TimedDict {dict_name}'.format(
dict_name=dict_name))
obj.stop_sweep()
|
[
"def",
"cleanup_sweep_threads",
"(",
")",
":",
"for",
"dict_name",
",",
"obj",
"in",
"globals",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"TimedDict",
",",
")",
")",
":",
"logging",
".",
"info",
"(",
"'Stopping thread for TimedDict {dict_name}'",
".",
"format",
"(",
"dict_name",
"=",
"dict_name",
")",
")",
"obj",
".",
"stop_sweep",
"(",
")"
] |
Not used. Keeping this function in case we decide not to use
daemonized threads and it becomes necessary to clean up the
running threads upon exit.
|
[
"Not",
"used",
".",
"Keeping",
"this",
"function",
"in",
"case",
"we",
"decide",
"not",
"to",
"use",
"daemonized",
"threads",
"and",
"it",
"becomes",
"necessary",
"to",
"clean",
"up",
"the",
"running",
"threads",
"upon",
"exit",
"."
] |
01a1d145d246832e63c2e92e11d91cac5c3f2d1e
|
https://github.com/zacernst/timed_dict/blob/01a1d145d246832e63c2e92e11d91cac5c3f2d1e/timed_dict/timed_dict.py#L343-L355
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.