code
stringlengths
1
18.2k
def save_image(filename,view='axial',type='png',hostname=None): '''Save currently open AFNI view ``view`` to ``filename`` using ``type`` (``png`` or ``jpeg``)''' driver_send("SAVE_%s %simage %s" % (type.upper(),view.lower(),filename),hostname=hostname)
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)
def search(self, _): """ Implements the `search <http://docs.annotatorjs.org/en/v1.2.x/storage.html#search>`_ endpoint. We rely on the behaviour of the ``filter_backends`` to manage the actual filtering of search results. :param _: :class:`rest_framework.request.Request` object—ignored here as we rely on the ``filter_b...
def get_success_headers(self, data): """ As per the *Annotator* documentation regarding the `create <http://docs.annotatorjs.org/en/v1.2.x/storage.html#create>`_ and `update <http://docs.annotatorjs.org/en/v1.2.x/storage.html#update>`_ endpoints, we must return an absolute URL in the ``Location`` header. :param data: s...
def create(self, request, *args, **kwargs): """ See the *Annotator* documentation regarding the `create <http://docs.annotatorjs.org/en/v1.2.x/storage.html#create>`_ endpoint. :param request: incoming :class:`rest_framework.request.Request`. :return: 303 :class:`rest_framework.response.Response`. """ response = super(A...
def update(self, request, *args, **kwargs): """ See the *Annotator* documentation regarding the `update <http://docs.annotatorjs.org/en/v1.2.x/storage.html#update>`_ endpoint. :param request: incoming :class:`rest_framework.request.Request`. :return: 303 :class:`rest_framework.response.Response`. """ response = super(A...
def get_diskinfo(opts, show_all=False, local_only=False): ''' Returns a list holding the current disk info, stats divided by the ouptut unit. ''' disks = [] outunit = opts.outunit for drive in get_drives(): drive += ':\\' disk = DiskInfo(dev=drive) try: usage = get_fs_usage(drive) except WindowsError: # disk not ready,...
# this not giving correct result on Win7 RTM either disk.rw = stat.S_IMODE(os.stat(drive).st_mode) & stat.S_IWRITE else: disk.rw = False disks.append(disk) if opts.debug: for disk in disks: print(disk.dev, disk, '\n') return disks
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)\% Usage', 'double')[0] / 100 except WindowsError: p...
= 0 meminfo.cached = cache / float(outunit) # SWAP these numbers are actually commit charge, not swap; fix # should not contain RAM :/ swpt = abs(mstat.TotalPageFile - totl) # these nums aren't quite right either, use perfmon instead :/ swpu = swpt * pgpcnt swpf = swpt - swpu meminfo.swaptotal = swpt / float(outunit) m...
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(): if value.startswith(api + " "): return cl...
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:] return cls(api, properties) except IndexError: raise MalformedDocumentErr...
def inline(self) -> str: """ Return endpoint string :return: """ doc = self.api for p in self.properties: doc += " {0}".format(p) return doc
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 MalformedDocumentError(BMAEndpoint.API) server = m.group(1) ipv4 = m.group(2) ipv6 = m...
def inline(self) -> str: """ Return endpoint string :return: """ return BMAEndpoint.API + "{DNS}{IPv4}{IPv6}{PORT}" \ .format(DNS=(" {0}".format(self.server) if self.server else ""), IPv4=(" {0}".format(self.ipv4) if self.ipv4 else ""), IPv6=(" {0}".format(self.ipv6) if self.ipv6 else ""), PORT=(" {0}".format(self.port...
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: raise MalformedDocumentError(SecuredBMAEndpoint.API) server = m....
def inline(self) -> str: """ Return endpoint string :return: """ inlined = [str(info) for info in (self.server, self.ipv4, self.ipv6, self.port, self.path) if info] return SecuredBMAEndpoint.API + " " + " ".join(inlined)
def conn_handler(self, session: ClientSession, proxy: str = None) -> ConnectionHandler: """ Return connection handler instance for the endpoint :param session: AIOHTTP client session instance :param proxy: Proxy url :return: """ if self.server: return ConnectionHandler("https", "wss", self.server, self.port, self.path,...
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 MalformedDocumentError(WS2PEndpoint.API) ws2pid = m.group(1) server = m.group(2) p...
def inline(self) -> str: """ Return endpoint string :return: """ inlined = [str(info) for info in (self.ws2pid, self.server, self.port, self.path) if info] return WS2PEndpoint.API + " " + " ".join(inlined)
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 MalformedDocumentError(ESCoreEndpoint.API) server = m.group(1) port = int(...
def conn_handler(self, session: ClientSession, proxy: str = None) -> ConnectionHandler: """ Return connection handler instance for the endpoint :param session: AIOHTTP client session instance :param proxy: Proxy url :return: """ return ConnectionHandler("https", "wss", self.server, self.port, "", session, proxy)
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 MalformedDocumentError(ESUserEndpoint.API) server = m.group(1) port = int(...
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 is None: raise MalformedDocumentError(ESSubscribtionEndpo...
def inline(self) -> str: """ Return endpoint string :return: """ inlined = [str(info) for info in (self.server, self.port) if info] return ESSubscribtionEndpoint.API + " " + " ".join(inlined)
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) raise self.Continue() return wrapped
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_prefix + nodekey else: yield self._method_prefix + nodekey
def get_method(self, node): '''Given a particular node, check the visitor instance for methods mathing the computed methodnames (the function is a generator). Note that methods are cached at the class level. ''' methods = self._methods for methodname in self.get_methodnames(node): if methodname in methods: return metho...
def visit(self, node): '''The main visit function. Visits the passed-in node and calls finalize. ''' for token in self.itervisit(node): pass result = self.finalize() if result is not self: return result
def itervisit_node(self, node): '''Given a node, find the matching visitor function (if any) and run it. If the result is a context manager, yield from all the nodes children before allowing it to exit. Otherwise, return the result. ''' # Get the corresponding method and run it. func = self.get_method(node) if func is ...
continue # Otherwise just yield the result. else: yield result
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] data_friends={cn:[] for cn i...
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, content_type='application/json; charset=UTF-8')
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) ret = "{callback}('{val}');".fo...
def get_collection_instance(klass, api_client = None, request_api=True, **kwargs): """ instatiates the collection lookup of json type klass :param klass: json file name :param api_client: transportation api :param request_api: if True uses the default APIClient """ _type = klass if api_client is None and request_api: a...
if($e->getCode() == "FILTER_NOTEXISTING") # { # throw new BadMethodCallException('Call to undefined method :'.$method); # } # # throw $e; # } # } def sort(self, direction = "ASC"): """ set the sort to the query ['ASC','DESC'] """ direction = directtion.upper() if direction in ['ASC','DESC']: self.sort = direction else:...
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 the per-page limit");
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)
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,value)
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 else: msg = u'Invalid filter value: filter:%s value:%s' % (key, filter_val...
def _is_type(self, instance, type): """ Check if an ``instance`` is of the provided (JSON Schema) ``type``. """ if type not in self._types: raise UnknownType(type) type = self._types[type] # bool inherits from int, so ensure bools aren't reported as integers if isinstance(instance, bool): type = _flatten(type) if int i...
def validate_filter(self, key, filter_value): """ validate the filter key and value against the collection schema :param key: property name :param filter_value: value of the filter :returns True if all is ok otherwise False """ ok = False seek = u"filter[%s]" % key value = None for link in self.schema['links']: if link...
def _validate_json_format(self, filter_value, schema_validation_type): """ adds the type:string format:schema_validation_type :param filter_value: value of the filter :param schema_validation_type: format description of the json schema entry """ ok = False try: validators.json_schema_validation_format(filter_value, sch...
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) # value = urlencode(value) # query_str = u"%s=%s" % (afilter, value) if len(self.f...
def get_list_endpoint(self, rel=u"instances"): """ get the configured list entpoint for the schema.type :param rel: lookup rel: value inside the links section :returns the value :raises APIException """ schema_loaded = not self.schema is None links_present = "links" in self.schema.keys() if (schema_loaded and links_pre...
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 if response is not None and response.status_code == 200: types = helpers.pluralize(self.resource_type) #print "types %s"...
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) # raises exception if something goes wrong obj = i...
def load(self, page = None, verbose=False): """ call to execute the collection loading :param page: integer of the page to load :param verbose: boolean to print to console :returns response :raises the SalesKingException """ url = self._build_query_url(page, verbose) response = self._load(url, verbose) response = self....
def _load(self, url, verbose): """ Execute a request against the Salesking API to fetch the items :param url: url to fetch :return response :raises SaleskingException with the corresponding http errors """ msg = u"_load url: %s" % url self._last_query_str = url log.debug(msg) if verbose: print msg response = self.__api...
def addAdminResource(self, pluginSubPath: bytes, resource: BasicResource) -> None: """ Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. :return: None """ pluginSubPath = plugin...
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")
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")
def cmd_echo(self, connection, sender, target, payload): """ Echoes the given payload """ connection.privmsg(target, payload or "Hello, {0}".format(sender))
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.")
def do_refresh(self,args): """Refresh the view of the log group""" # prints all the groups: pprint(AwsConnectionFactory.getLogClient().describe_log_groups()) response = AwsConnectionFactory.getLogClient().describe_log_groups(logGroupNamePrefix=self.stackResource.physical_resource_id) if not 'logGroups' in response: rai...
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(args['logStream']) index = int(args['logS...
def from_path(path): """ Selects and returns a build class based on project structure/config from a given path. :param path(str): required path argument to be used """ for item in ref: build = ref[item] valid_ = build['is_valid'] if valid_(path) is True: return build['builder'](path) raise errors.InvalidProjectStructur...
def get_nodekey(self, token, types=types, coll_abc=collections.abc): '''Given a particular token, check the visitor instance for methods mathing the computed methodnames (the function is a generator). ''' # Check the mro. for mro_type in type(token).__mro__: yield mro_type.__name__ # Check for callability. if callable(...
is None: continue if isinstance(token, type_): yield type_name
def itervisit( self, iterable, gentype=types.GeneratorType, exhaust_generators=True): '''The main visit function. Visits the passed-in node and calls finalize. ''' self.iterable = iter(iterable) for token in self.iterable: result = self.itervisit_node(token) if exhaust_generators and isinstance(result, gentype): for ou...
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)
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)
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).encode('utf8') return base64url_encode(datajson)
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 parameters are passed as is to...
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)
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 named pubkey. The parameter expire_after...
= _jws_header(addy, algo).decode('utf8') payload = _build_payload(expire_after, requrl, **kwargs) signdata = "{}.{}".format(header, payload) signature = _jws_signature(signdata, privkey, algo).decode('utf8') return "{}.{}".format(signdata, signature)
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 performed using the same algorithm. The par...
= {"payload": payload, "signatures": []} algo = ALGORITHM_AVAILABLE[algorithm_name] for pk in privkeys: addy = algo.pubkey_serialize(pk.pubkey) header = _jws_header(addy, algo).decode('utf8') signdata = "{}.{}".format(header, payload) signature = _jws_signature(signdata, pk, algo).decode('utf8') result["signatures"].ap...
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. If check_expiration is False, the payload will be accepted even if expired. If dec...
**entry) all_valid = all_valid and valid except Exception as err: raise InvalidMessage('failed to verify signature: {}'.format(err)) if not all_valid: return None, None if decode_payload: _verify_payload(payload, check_expiration, requrl) return [entry['header'] for entry in sigs], payload
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 accepted even if expired. If decode_payload is Tr...
signature, algo) except Exception as err: raise InvalidMessage('failed to verify signature: {}'.format(err)) if not valid: return None, None if decode_payload: _verify_payload(payload, check_expiration, requrl) return header, payload
def raise_(type_, value=None, traceback=None): # pylint: disable=W0613 """ Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is: please be pretty car...
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, data=data, headers=headers, **kwargs) response = self._request(url, method=method, data=data, headers=headers, **kwa...
def _pre_request(self, url, method = u"get", data = None, headers=None, **kwargs): """ hook for manipulating the _pre request data """ return (url, method, data, headers, kwargs)
def _pre_request(self, url, method = u"get", data = None, headers=None, **kwargs): """ hook for manipulating the _pre request data """ header = { u"Content-Type": u"application/json", u"User-Agent": u"salesking_api_py_v1", } if headers: headers.update(header) else: headers = header if url.find(self.base_url) !=0: url =...
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"Authorization": "Bearer %s" % (self.access_token) # } # headers.update(auth_header) #basic auth msg = "me...
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: msg = u"authorization failed user:%s" % (self.sk_user) raise exceptions.U...
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
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('class '): return True return False
def get(self, name=None): """Get initial yield value, or result of send(name) if name given.""" if name is None: return self.init_value elif not self.support_name: msg = "generator does not support get-by-name: function {!r}" raise TypeError(msg.format(self.function)) try: value = self.generator.send(name) except StopI...
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.format(self.function))
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))
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(__fn)) __fn.__notes__ = (notes, keyword_notes)
def wraps(__fn, **kw): """Like ``functools.wraps``, with support for annotations.""" kw['assigned'] = kw.get('assigned', WRAPPER_ASSIGNMENTS) return functools.wraps(__fn, **kw)
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): return @annotate('foo', annotate.partial(foobar)) def bazquux(f...
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())))
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())))
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, tuple(kw.items())))
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 @Injector.provider('hello') class HelloProvider(Provider): def get(self, name=None):...
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') def echo(name=None): return name Registration can be a decorator or a direct metho...
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)
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 provided by injector 2. positional arguments p...
= getattr(lazy_injection_fn, 'arg_pack', None) if arg_pack is not None: pack_args, pack_kwargs = arg_pack else: jeni_args, jeni_kwargs = self.prepare_callable(fn, partial=True) pack_args = jeni_args + user_args pack_kwargs = {} pack_kwargs.update(jeni_kwargs) pack_kwargs.update(user_kwargs) lazy_injection_fn.arg_pack =...
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 the partially applied function is c...
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)
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)
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)
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 functions. if isinstance(note, tuple) and len(note) == 2:...