_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q43500 | Butcher.missing_nodes | train | def missing_nodes(self):
"""The set of targets known as dependencies but not yet defined."""
missing = set()
for target_addr, target_attrs in self.graph.node.items():
if 'target_obj' not in target_attrs:
missing.add(target_addr)
return missing | python | {
"resource": ""
} |
q43501 | Butcher.load_buildfile | train | def load_buildfile(self, target):
"""Pull a build file from git."""
log.info('Loading: %s', target)
filepath = os.path.join(target.path, app.get_options().buildfile_name)
try:
repo = self.repo_state.GetRepo(target.repo)
return repo.get_file(filepath)
excep... | python | {
"resource": ""
} |
q43502 | constructSpec | train | def constructSpec(indentation, begin_block, end_block, begin_line, end_line,
begin_action, end_action,
begin_condition, end_condition,
logical_and, logical_or):
"""Return a language specification based on parameters."""
return {
INDENTATION : in... | python | {
"resource": ""
} |
q43503 | translated | train | def translated(structure, values, lang_spec):
"""Return code associated to given structure and values,
translate with given language specification."""
# LANGUAGE SPECS
indentation = '\t'
endline = '\n'
object_code = ""
stack = []
# define shortcuts to behavior
push = lambda x: sta... | python | {
"resource": ""
} |
q43504 | cpp_spec | train | def cpp_spec():
"""C++ specification, provided for example, and java compatible."""
return {
INDENTATION : '\t',
BEG_BLOCK : '{',
END_BLOCK : '}',
BEG_LINE : '',
END_LINE : '\n',
BEG_ACTION : '',
END_ACTION : ';',
B... | python | {
"resource": ""
} |
q43505 | set_thresh | train | def set_thresh(thresh,p=False,hostname=None):
'''Sets the level of the threshold slider.
If ``p==True`` will be interpreted as a _p_-value'''
driver_send("SET_THRESHNEW %s *%s" % (str(thresh),"p" if p else ""),hostname=hostname) | python | {
"resource": ""
} |
q43506 | get_meminfo | train | def get_meminfo(opts):
''' Returns a dictionary holding the current memory info,
divided by the ouptut unit.
'''
meminfo = MemInfo()
outunit = opts.outunit
mstat = get_mem_info() # from winstats
pinf = get_perf_info()
try:
pgpcnt = get_perf_data(r'\Paging File(_Total)\% Usag... | python | {
"resource": ""
} |
q43507 | endpoint | train | def endpoint(value: Any) -> Any:
"""
Convert a endpoint string to the corresponding Endpoint instance type
:param value: Endpoint string or subclass
:return:
"""
if issubclass(type(value), Endpoint):
return value
elif isinstance(value, str):
for api, cls in MANAGED_API.items... | python | {
"resource": ""
} |
q43508 | UnknownEndpoint.from_inline | train | def from_inline(cls: Type[UnknownEndpointType], inline: str) -> UnknownEndpointType:
"""
Return UnknownEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
try:
api = inline.split()[0]
properties = inline.split()[1:]
... | python | {
"resource": ""
} |
q43509 | BMAEndpoint.from_inline | train | def from_inline(cls: Type[BMAEndpointType], inline: str) -> BMAEndpointType:
"""
Return BMAEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = BMAEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocument... | python | {
"resource": ""
} |
q43510 | SecuredBMAEndpoint.from_inline | train | def from_inline(cls: Type[SecuredBMAEndpointType], inline: str) -> SecuredBMAEndpointType:
"""
Return SecuredBMAEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = SecuredBMAEndpoint.re_inline.match(inline)
if m is None:
... | python | {
"resource": ""
} |
q43511 | WS2PEndpoint.from_inline | train | def from_inline(cls: Type[WS2PEndpointType], inline: str) -> WS2PEndpointType:
"""
Return WS2PEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = WS2PEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocu... | python | {
"resource": ""
} |
q43512 | ESCoreEndpoint.from_inline | train | def from_inline(cls: Type[ESCoreEndpointType], inline: str) -> ESCoreEndpointType:
"""
Return ESCoreEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = ESCoreEndpoint.re_inline.match(inline)
if m is None:
raise Malfo... | python | {
"resource": ""
} |
q43513 | ESUserEndpoint.from_inline | train | def from_inline(cls: Type[ESUserEndpointType], inline: str) -> ESUserEndpointType:
"""
Return ESUserEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = ESUserEndpoint.re_inline.match(inline)
if m is None:
raise Malfo... | python | {
"resource": ""
} |
q43514 | ESSubscribtionEndpoint.from_inline | train | def from_inline(cls: Type[ESSubscribtionEndpointType], inline: str) -> ESSubscribtionEndpointType:
"""
Return ESSubscribtionEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = ESSubscribtionEndpoint.re_inline.match(inline)
if m ... | python | {
"resource": ""
} |
q43515 | Visitor.continues | train | def continues(method):
'''Method decorator signifying that the visitor should not visit the
current node's children once this method has been invoked.
'''
@functools.wraps(method)
def wrapped(self, *args, **kwargs):
yield method(self, *args, **kwargs)
rais... | python | {
"resource": ""
} |
q43516 | Visitor.get_methodnames | train | def get_methodnames(self, node):
'''Given a node, generate all names for matching visitor methods.
'''
nodekey = self.get_nodekey(node)
prefix = self._method_prefix
if isinstance(nodekey, self.GeneratorType):
for nodekey in nodekey:
yield self._method_... | python | {
"resource": ""
} |
q43517 | readGDF | train | def readGDF(filename="../data/RenatoFabbri06022014.gdf"):
"""Made to work with gdf files from my own network and friends and groups"""
with open(filename,"r") as f:
data=f.read()
lines=data.split("\n")
columns=lines[0].split(">")[1].split(",")
column_names=[i.split(" ")[0] for i in columns]
... | python | {
"resource": ""
} |
q43518 | json_response | train | def json_response(data, status=200, serializer=None):
"""
Returns an HttpResponse object containing JSON serialized data.
The mime-type is set to application/json, and the charset to UTF-8.
"""
return HttpResponse(json.dumps(data, default=serializer),
status=status,
... | python | {
"resource": ""
} |
q43519 | jsonp_response | train | def jsonp_response(data, callback="f", status=200, serializer=None):
"""
Returns an HttpResponse object containing JSON serialized data,
wrapped in a JSONP callback.
The mime-type is set to application/x-javascript, and the charset to UTF-8.
"""
val = json.dumps(data, default=serializer)
re... | python | {
"resource": ""
} |
q43520 | CollectionAttributesMixin.set_per_page | train | def set_per_page(self, entries=100):
"""
set entries per page max 200
"""
if isinstance(entries, int) and entries <= 200:
self.per_page = int(entries)
return self
else:
raise SalesKingException("PERPAGE_ONLYINT", "Please set an integer <200 for... | python | {
"resource": ""
} |
q43521 | CollectionAttributesMixin.set_resource_type | train | def set_resource_type(self, klass):
"""
set type to load and load schema
"""
self.resource_type = klass
self.schema = loaders.load_schema_raw(self.resource_type) | python | {
"resource": ""
} |
q43522 | CollectionAttributesMixin.set_filters | train | def set_filters(self, filters):
"""
set and validate filters dict
"""
if not isinstance(filters, dict):
raise Exception("filters must be a dict")
self.filters = {}
for key in filters.keys():
value = filters[key]
self.add_filter(key,valu... | python | {
"resource": ""
} |
q43523 | CollectionAttributesMixin.add_filter | train | def add_filter(self, key, filter_value):
"""
add and validate a filter with value
returns True on success otherwise exception
"""
seek = u"filter[%s]" % key
if self.validate_filter(key, filter_value):
self.filters[key] = filter_value
return True
... | python | {
"resource": ""
} |
q43524 | CollectionAttributesMixin._build_query_url | train | def _build_query_url(self, page = None, verbose = False):
"""
builds the url to call
"""
query = []
# # build the filters
# for afilter in self.filters.keys():
# value = self.filters[afilter]
# print"filter:%s value:%s" % (afilter,value)
# v... | python | {
"resource": ""
} |
q43525 | CollectionAttributesMixin._post_load | train | def _post_load(self, response, verbose):
"""
post load processing
fills the self._items collection
"""
try:
if verbose:
print response.content
log.debug(response.content)
except Exception, e:
raise e
... | python | {
"resource": ""
} |
q43526 | CollectionAttributesMixin._response_item_to_object | train | def _response_item_to_object(self, resp_item):
"""
take json and make a resource out of it
"""
item_cls = resources.get_model_class(self.resource_type)
properties_dict = resp_item[self.resource_type]
new_dict = helpers.remove_properties_containing_None(properties_dict)
... | python | {
"resource": ""
} |
q43527 | BasicCommandsBot.cmd_part | train | def cmd_part(self, connection, sender, target, payload):
"""
Asks the bot to leave a channel
"""
if payload:
connection.part(payload)
else:
raise ValueError("No channel given") | python | {
"resource": ""
} |
q43528 | BasicCommandsBot.cmd_join | train | def cmd_join(self, connection, sender, target, payload):
"""
Asks the bot to join a channel
"""
if payload:
connection.join(payload)
else:
raise ValueError("No channel given") | python | {
"resource": ""
} |
q43529 | BasicCommandsBot.cmd_echo | train | def cmd_echo(self, connection, sender, target, payload):
"""
Echoes the given payload
"""
connection.privmsg(target, payload or "Hello, {0}".format(sender)) | python | {
"resource": ""
} |
q43530 | BasicCommandsBot.cmd_work | train | def cmd_work(self, connection, sender, target, payload):
"""
Does some job
"""
connection.action(target, "is doing something...")
time.sleep(int(payload or "5"))
connection.action(target, "has finished !")
connection.privmsg(target, "My answer is: 42.") | python | {
"resource": ""
} |
q43531 | AwsLogGroup.do_logStream | train | def do_logStream(self,args):
"""Go to the specified log stream. logStream -h for detailed help"""
parser = CommandArgumentParser("logStream")
parser.add_argument(dest='logStream',help='logStream index.');
args = vars(parser.parse_args(args))
print "loading log stream {}".format(... | python | {
"resource": ""
} |
q43532 | print_version | train | def print_version(ctx: click.Context, _, value):
"""
Prints current version then exits
"""
if not value or ctx.resilient_parsing:
return
print(__version__)
sys.exit(0) | python | {
"resource": ""
} |
q43533 | base64url_decode | train | def base64url_decode(msg):
"""
Decode a base64 message based on JWT spec, Appendix B.
"Notes on implementing base64url encoding without padding"
"""
rem = len(msg) % 4
if rem:
msg += b'=' * (4 - rem)
return base64.urlsafe_b64decode(msg) | python | {
"resource": ""
} |
q43534 | _jws_header | train | def _jws_header(keyid, algorithm):
"""Produce a base64-encoded JWS header."""
data = {
'typ': 'JWT',
'alg': algorithm.name,
# 'kid' is used to indicate the public part of the key
# used during signing.
'kid': keyid
}
datajson = json.dumps(data, sort_keys=True).en... | python | {
"resource": ""
} |
q43535 | _jws_payload | train | def _jws_payload(expire_at, requrl=None, **kwargs):
"""
Produce a base64-encoded JWS payload.
expire_at, if specified, must be a number that indicates
a timestamp after which the message must be rejected.
requrl, if specified, is used as the "audience" according
to the JWT spec.
Any other... | python | {
"resource": ""
} |
q43536 | _jws_signature | train | def _jws_signature(signdata, privkey, algorithm):
"""
Produce a base64-encoded JWS signature based on the signdata
specified, the privkey instance, and the algorithm passed.
"""
signature = algorithm.sign(privkey, signdata)
return base64url_encode(signature) | python | {
"resource": ""
} |
q43537 | sign_serialize | train | def sign_serialize(privkey, expire_after=3600, requrl=None,
algorithm_name=DEFAULT_ALGO, **kwargs):
"""
Produce a JWT compact serialization by generating a header, payload,
and signature using the privkey and algorithm specified.
The privkey object must contain at least a member name... | python | {
"resource": ""
} |
q43538 | multisig_sign_serialize | train | def multisig_sign_serialize(privkeys, expire_after=3600, requrl=None,
algorithm_name=DEFAULT_ALGO, **kwargs):
"""
Produce a general JSON serialization by generating a header, payload,
and multiple signatures using the list of private keys specified.
All the signatures will be... | python | {
"resource": ""
} |
q43539 | multisig_validate_deserialize | train | def multisig_validate_deserialize(rawmsg, requrl=None, check_expiration=True,
decode_payload=True,
algorithm_name=DEFAULT_ALGO):
"""
Validate a general JSON serialization and return the headers and
payload if all the signatures are good.
... | python | {
"resource": ""
} |
q43540 | validate_deserialize | train | def validate_deserialize(rawmsg, requrl=None, check_expiration=True,
decode_payload=True, algorithm_name=DEFAULT_ALGO):
"""
Validate a JWT compact serialization and return the header and
payload if the signature is good.
If check_expiration is False, the payload will be accepte... | python | {
"resource": ""
} |
q43541 | SalesKingApiBase.request | train | def request(self, url, method = u"get", data = None, headers = None, **kwargs):
"""
public method for doing the live request
"""
url, method, data, headers, kwargs = self._pre_request(url,
method=method,
... | python | {
"resource": ""
} |
q43542 | APIClient._request | train | def _request(self, url, method = u"get", data = None, headers=None, **kwargs):
"""
does the request via requests
- oauth not implemented yet
- use basic auth please
"""
# if self.access_token:
# auth_header = {
# u"Authoriz... | python | {
"resource": ""
} |
q43543 | APIClient._handle_response | train | def _handle_response(self, response):
"""
internal method to throw the correct exception if something went wrong
"""
status = response.status_code
if status == 400:
msg = u"bad request"
raise exceptions.BadRequest(status, msg)
elif status == 401:
... | python | {
"resource": ""
} |
q43544 | see_doc | train | def see_doc(obj_with_doc):
"""Copy docstring from existing object to the decorated callable."""
def decorator(fn):
fn.__doc__ = obj_with_doc.__doc__
return fn
return decorator | python | {
"resource": ""
} |
q43545 | class_in_progress | train | def class_in_progress(stack=None):
"""True if currently inside a class definition, else False."""
if stack is None:
stack = inspect.stack()
for frame in stack:
statement_list = frame[4]
if statement_list is None:
continue
if statement_list[0].strip().startswith('c... | python | {
"resource": ""
} |
q43546 | GeneratorProvider.close | train | def close(self):
"""Close the generator."""
if self.support_name:
self.generator.close()
try:
next(self.generator)
except StopIteration:
return
else:
msg = "generator didn't stop: function {!r}"
raise RuntimeError(msg.fo... | python | {
"resource": ""
} |
q43547 | Annotator.get_annotations | train | def get_annotations(cls, __fn):
"""Get the annotations of a given callable."""
if hasattr(__fn, '__func__'):
__fn = __fn.__func__
if hasattr(__fn, '__notes__'):
return __fn.__notes__
raise AttributeError('{!r} does not have annotations'.format(__fn)) | python | {
"resource": ""
} |
q43548 | Annotator.set_annotations | train | def set_annotations(cls, __fn, *notes, **keyword_notes):
"""Set the annotations on the given callable."""
if hasattr(__fn, '__func__'):
__fn = __fn.__func__
if hasattr(__fn, '__notes__'):
msg = 'callable already has notes: {!r}'
raise AttributeError(msg.format... | python | {
"resource": ""
} |
q43549 | Annotator.wraps | train | def wraps(__fn, **kw):
"""Like ``functools.wraps``, with support for annotations."""
kw['assigned'] = kw.get('assigned', WRAPPER_ASSIGNMENTS)
return functools.wraps(__fn, **kw) | python | {
"resource": ""
} |
q43550 | Annotator.partial | train | def partial(__fn, *a, **kw):
"""Wrap a note for injection of a partially applied function.
This allows for annotated functions to be injected for composition::
from jeni import annotate
@annotate('foo', bar=annotate.maybe('bar'))
def foobar(foo, bar=None):
... | python | {
"resource": ""
} |
q43551 | Annotator.partial_regardless | train | def partial_regardless(__fn, *a, **kw):
"""Wrap a note for injection of a partially applied function, or don't.
Use this instead of `partial` when binding a callable that may or may
not have annotations.
"""
return (PARTIAL_REGARDLESS, (__fn, a, tuple(kw.items()))) | python | {
"resource": ""
} |
q43552 | Annotator.eager_partial | train | def eager_partial(__fn, *a, **kw):
"""Wrap a note for injection of an eagerly partially applied function.
Use this instead of `partial` when eager injection is needed in place
of lazy injection.
"""
return (EAGER_PARTIAL, (__fn, a, tuple(kw.items()))) | python | {
"resource": ""
} |
q43553 | Annotator.eager_partial_regardless | train | def eager_partial_regardless(__fn, *a, **kw):
"""Wrap a note for injection of an eagerly partially applied function, or don't.
Use this instead of `eager_partial partial` when binding a callable
that may or may not have annotations.
"""
return (EAGER_PARTIAL_REGARDLESS, (__fn, a... | python | {
"resource": ""
} |
q43554 | Injector.provider | train | def provider(cls, note, provider=None, name=False):
"""Register a provider, either a Provider class or a generator.
Provider class::
from jeni import Injector as BaseInjector
from jeni import Provider
class Injector(BaseInjector):
pass
... | python | {
"resource": ""
} |
q43555 | Injector.factory | train | def factory(cls, note, fn=None):
"""Register a function as a provider.
Function (name support is optional)::
from jeni import Injector as BaseInjector
from jeni import Provider
class Injector(BaseInjector):
pass
@Injector.factory('echo'... | python | {
"resource": ""
} |
q43556 | Injector.apply | train | def apply(self, fn, *a, **kw):
"""Fully apply annotated callable, returning callable's result."""
args, kwargs = self.prepare_callable(fn)
args += a; kwargs.update(kw)
return fn(*args, **kwargs) | python | {
"resource": ""
} |
q43557 | Injector.partial | train | def partial(self, fn, *user_args, **user_kwargs):
"""Return function with closure to lazily inject annotated callable.
Repeat calls to the resulting function will reuse injections from the
first call.
Positional arguments are provided in this order:
1. positional arguments pro... | python | {
"resource": ""
} |
q43558 | Injector.eager_partial | train | def eager_partial(self, fn, *a, **kw):
"""Partially apply annotated callable, returning a partial function.
By default, `partial` is lazy so that injections only happen when they
are needed. Use `eager_partial` in place of `partial` when a guarantee
of injection is needed at the time th... | python | {
"resource": ""
} |
q43559 | Injector.apply_regardless | train | def apply_regardless(self, fn, *a, **kw):
"""Like `apply`, but applies if callable is not annotated."""
if self.has_annotations(fn):
return self.apply(fn, *a, **kw)
return fn(*a, **kw) | python | {
"resource": ""
} |
q43560 | Injector.partial_regardless | train | def partial_regardless(self, fn, *a, **kw):
"""Like `partial`, but applies if callable is not annotated."""
if self.has_annotations(fn):
return self.partial(fn, *a, **kw)
else:
return functools.partial(fn, *a, **kw) | python | {
"resource": ""
} |
q43561 | Injector.eager_partial_regardless | train | def eager_partial_regardless(self, fn, *a, **kw):
"""Like `eager_partial`, but applies if callable is not annotated."""
if self.has_annotations(fn):
return self.eager_partial(fn, *a, **kw)
return functools.partial(fn, *a, **kw) | python | {
"resource": ""
} |
q43562 | Injector.get | train | def get(self, note):
"""Resolve a single note into an object."""
if self.closed:
raise RuntimeError('{!r} already closed'.format(self))
# Record request for note even if it fails to resolve.
self.stats[note] += 1
# Handle injection of partially applied annotated fun... | python | {
"resource": ""
} |
q43563 | Injector.close | train | def close(self):
"""Close injector & injected Provider instances, including generators.
Providers are closed in the reverse order in which they were opened,
and each provider is only closed once. Providers are closed if accessed
by the injector, even if a dependency is not successfully ... | python | {
"resource": ""
} |
q43564 | Injector.prepare_callable | train | def prepare_callable(self, fn, partial=False):
"""Prepare arguments required to apply function."""
notes, keyword_notes = self.get_annotations(fn)
return self.prepare_notes(*notes, __partial=partial, **keyword_notes) | python | {
"resource": ""
} |
q43565 | Injector.prepare_notes | train | def prepare_notes(self, *notes, **keyword_notes):
"""Get injection values for all given notes."""
__partial = keyword_notes.pop('__partial', False)
args = tuple(self.get(note) for note in notes)
kwargs = {}
for arg in keyword_notes:
note = keyword_notes[arg]
... | python | {
"resource": ""
} |
q43566 | Injector.parse_note | train | def parse_note(cls, note):
"""Parse string annotation into object reference with optional name."""
if isinstance(note, tuple):
if len(note) != 2:
raise ValueError('tuple annotations must be length 2')
return note
try:
match = cls.re_note.match(... | python | {
"resource": ""
} |
q43567 | Injector.handle_provider | train | def handle_provider(self, provider_factory, note):
"""Get value from provider as requested by note."""
# Implementation in separate method to support accurate book-keeping.
basenote, name = self.parse_note(note)
# _handle_provider could be even shorter if
# Injector.apply() work... | python | {
"resource": ""
} |
q43568 | Injector.register | train | def register(cls, note, provider):
"""Implementation to register provider via `provider` & `factory`."""
basenote, name = cls.parse_note(note)
if 'provider_registry' not in vars(cls):
cls.provider_registry = {}
cls.provider_registry[basenote] = provider | python | {
"resource": ""
} |
q43569 | Injector.lookup | train | def lookup(cls, basenote):
"""Look up note in registered annotations, walking class tree."""
# Walk method resolution order, which includes current class.
for c in cls.mro():
if 'provider_registry' not in vars(c):
# class is a mixin, super to base class, or never regi... | python | {
"resource": ""
} |
q43570 | Injector.sub | train | def sub(cls, *mixins_and_dicts, **values):
"""Create and instantiate a sub-injector.
Mixins and local value dicts can be passed in as arguments. Local
values can also be passed in as keyword arguments.
"""
class SubInjector(cls):
pass
mixins = [ x for x in... | python | {
"resource": ""
} |
q43571 | _getFuncArgs | train | def _getFuncArgs(func):
r"""Gives the details on the args of the given func.
Args:
func (function): The function to get details on.
"""
code = func.func_code
Defaults = func.func_defaults
nargs = code.co_argcount
ArgNames = code.co_varnames[:nargs]
Args = OrderedDict()
argCount = len(ArgNames)
... | python | {
"resource": ""
} |
q43572 | FormLabel.get_form_label | train | def get_form_label(self, request=None, obj=None, model=None, form=None):
"""Returns a customized form label, if condition is met,
otherwise returns the default form label.
* condition is an instance of CustomLabelCondition.
"""
label = form.base_fields[self.field].label
... | python | {
"resource": ""
} |
q43573 | AwsRoot.do_stack | train | def do_stack(self,args):
"""Go to the specified stack. stack -h for detailed help"""
parser = CommandArgumentParser("stack")
parser.add_argument(dest='stack',help='stack index or name');
parser.add_argument('-a','--asg',dest='asg',help='descend into specified asg');
args = vars(p... | python | {
"resource": ""
} |
q43574 | AwsRoot.do_delete_stack | train | def do_delete_stack(self,args):
"""Delete specified stack. delete_stack -h for detailed help."""
parser = CommandArgumentParser("delete_stack")
parser.add_argument(dest='stack',help='stack index or name');
args = vars(parser.parse_args(args))
try:
index = int(args['s... | python | {
"resource": ""
} |
q43575 | AwsRoot.do_stacks | train | def do_stacks(self,args):
"""List available stacks. stacks -h for detailed help."""
parser = CommandArgumentParser()
parser.add_argument('-s','--silent',dest='silent',action='store_true',help='Run silently')
parser.add_argument('-i','--include',nargs='*',dest='includes',default=[],help='... | python | {
"resource": ""
} |
q43576 | AwsRoot.do_stack_resource | train | def do_stack_resource(self, args):
"""Use specified stack resource. stack_resource -h for detailed help."""
parser = CommandArgumentParser()
parser.add_argument('-s','--stack-name',dest='stack-name',help='name of the stack resource');
parser.add_argument('-i','--logical-id',dest='logical... | python | {
"resource": ""
} |
q43577 | Monitor.configure | train | def configure(self, config):
"""
Configure Monitor, pull list of what to monitor, initialize threads
"""
self.config = config
self.update_monitors()
# initialize thread pools
for profile in ('worker', 'result'):
for _ in range(config['threads'][profil... | python | {
"resource": ""
} |
q43578 | Monitor.start | train | def start(self):
"""
The main loop, run forever.
"""
while True:
self.thread_debug("Interval starting")
for thr in threading.enumerate():
self.thread_debug(" " + str(thr))
self.feed_monitors()
start = time.time()
... | python | {
"resource": ""
} |
q43579 | Monitor.update_monitors | train | def update_monitors(self):
"""
Periodically check in with Reflex Engine and refresh the list of what to monitor
"""
self.thread_debug("Starting monitor refresh", module="update_monitors")
# need to make a more efficient way of doing this via Reflex Engine
monitors = []
... | python | {
"resource": ""
} |
q43580 | Monitor.thread_debug | train | def thread_debug(self, *args, **kwargs):
"""
Wrap debug to include thread information
"""
if 'module' not in kwargs:
kwargs['module'] = "Monitor"
if kwargs['module'] != 'Monitor' and self.do_DEBUG(module='Monitor'):
self.debug[kwargs['module']] = True
... | python | {
"resource": ""
} |
q43581 | Monitor._worker_http | train | def _worker_http(self, monitor):
"""
Process an http monitor.
"""
self.thread_debug("process_http", data=monitor, module='handler')
query = monitor['query']
method = query['method'].lower()
self.stats.http_run += 1
try:
target = monitor['target... | python | {
"resource": ""
} |
q43582 | Monitor._handler_http | train | def _handler_http(self, result):
"""
Handle the result of an http monitor
"""
monitor = result['monitor']
self.thread_debug("process_http", data=monitor, module='handler')
self.stats.http_handled += 1
# splunk will pick this up
logargs = {
'ty... | python | {
"resource": ""
} |
q43583 | Monitor.reporting | train | def reporting(self):
"""
report on consumption info
"""
self.thread_debug("reporting")
res = resource.getrusage(resource.RUSAGE_SELF)
self.NOTIFY("",
type='internal-usage',
maxrss=round(res.ru_maxrss/1024, 2),
ix... | python | {
"resource": ""
} |
q43584 | Monitor.start_agent | train | def start_agent(self, cfgin=True):
"""
CLI interface to start 12-factor service
"""
default_conf = {
"threads": {
"result": {
"number": 0,
"function": None
},
"worker": {
... | python | {
"resource": ""
} |
q43585 | start | train | def start():
r"""Starts ec.
"""
processPendingModules()
if not state.main_module_name in ModuleMembers: # don't start the core when main is not Ec-ed
return
MainModule = sys.modules[state.main_module_name]
if not MainModule.__ec_member__.Members: # there was some error while loading script(... | python | {
"resource": ""
} |
q43586 | execCommand | train | def execCommand(Argv, collect_missing):
r"""Executes the given task with parameters.
"""
try:
return _execCommand(Argv, collect_missing)
except Exception as e:
if Settings['errorHandler']:
Settings['errorHandler'](e)
if Settings['debug']:
# #ToDo: Have an option to debug throug... | python | {
"resource": ""
} |
q43587 | getDescendant | train | def getDescendant(Ancestor, RouteParts):
r"""Resolves a descendant, of the given Ancestor, as pointed by the RouteParts.
"""
if not RouteParts:
return Ancestor
Resolved = Ancestor.Members.get(RouteParts.pop(0))
if isinstance(Resolved, Group):
return getDescendant(Resolved, RouteParts)
... | python | {
"resource": ""
} |
q43588 | setActiveModule | train | def setActiveModule(Module):
r"""Helps with collecting the members of the imported modules.
"""
module_name = Module.__name__
if module_name not in ModuleMembers:
ModuleMembers[module_name] = []
ModulesQ.append(module_name)
Group(Module, {}) # brand the module with __ec_member__
state.... | python | {
"resource": ""
} |
q43589 | processModule | train | def processModule(module_name):
r"""Builds a command tree out of the configured members of a module.
"""
Module = sys.modules[module_name]
MembersTarget = []
ClassQ = []
Cls = None
ClsGroup = None
ClsGrpMembers = []
for Member in ModuleMembers[module_name]:
Underlying = Member.Underlyi... | python | {
"resource": ""
} |
q43590 | _execCommand | train | def _execCommand(Argv, collect_missing):
r"""Worker of execCommand.
"""
if not Argv:
raise HandledException('Please specify a command!')
RouteParts = Argv[0].split('/')
Args, KwArgs = getDigestableArgs(Argv[1:])
ResolvedMember = getDescendant(BaseGroup, RouteParts[:])
if isinstance(Resol... | python | {
"resource": ""
} |
q43591 | memoize | train | def memoize(fn):
'''Cache the results of a function that only takes positional arguments.'''
cache = {}
@wraps(fn)
def wrapped_function(*args):
if args in cache:
return cache[args]
else:
result = fn(*args)
cache[args] = result
return res... | python | {
"resource": ""
} |
q43592 | setup_config | train | def setup_config(epab_version: str):
"""
Set up elib_config package
:param epab_version: installed version of EPAB as as string
"""
logger = logging.getLogger('EPAB')
logger.debug('setting up config')
elib_config.ELIBConfig.setup(
app_name='EPAB',
app_version=epab_version,
... | python | {
"resource": ""
} |
q43593 | get_month_list | train | def get_month_list(to_date, from_date):
"""
Generate a list containing year+month between two dates.
Returns:
[(2013, 11), (2013, 12), (2014, 1)]
"""
num_months = get_months_apart(to_date, from_date)
month_offset = from_date.month
month_list = []
for month in range(month_offset... | python | {
"resource": ""
} |
q43594 | find_amplitude | train | def find_amplitude(chunk):
"""
Calculate the 0-1 amplitude of an ndarray chunk of audio samples.
Samples in the ndarray chunk are signed int16 values oscillating
anywhere between -32768 and 32767. Find the amplitude between 0 and 1
by summing the absolute values of the minimum and maximum, and divi... | python | {
"resource": ""
} |
q43595 | AmplitudeHandler.step_amp | train | def step_amp(self):
"""
Change the amplitude according to the change rate and drift target.
Returns: None
"""
difference = self.drift_target - self._raw_value
if abs(difference) < self.change_rate:
self.value = self.drift_target
else:
delt... | python | {
"resource": ""
} |
q43596 | _LoaderBasics.create_module | train | def create_module(self, spec):
"""Creates the module, and also insert it into sys.modules, adding this onto py2 import logic."""
mod = sys.modules.setdefault(spec.name, types.ModuleType(spec.name))
# we are using setdefault to satisfy https://docs.python.org/3/reference/import.html#loaders
... | python | {
"resource": ""
} |
q43597 | _LoaderBasics.exec_module | train | def exec_module(self, module):
"""Execute the module."""
code = self.get_code(module.__name__)
if code is None:
raise ImportError('cannot load module {!r} when get_code() '
'returns None'.format(module.__name__))
exec(code, module.__dict__) | python | {
"resource": ""
} |
q43598 | _LoaderBasics.load_module | train | def load_module(self, fullname):
"""Load the specified module into sys.modules and return it.
This method is for python2 only, but implemented with backported py3 methods.
"""
if fullname in sys.modules:
mod = sys.modules[fullname]
self.exec_module(mod)
... | python | {
"resource": ""
} |
q43599 | NamespaceLoader2.create_module | train | def create_module(self, spec):
"""Improve python2 semantics for module creation."""
mod = super(NamespaceLoader2, self).create_module(spec)
# Set a few properties required by PEP 302
# mod.__file__ = [p for p in self.path]
# this will set mod.__repr__ to not builtin... shouldnt b... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.