code
stringlengths
1
18.2k
new method new_content = MethodType(*args) # update ctx with intercepted setattr(ctx, intercepted_name, new_content) joinpoint_function = _get_function(target) del_joinpoint_function = True if del_joinpoint_function: # delete _INTERCEPTED and _INTERCEPTED_CTX from joinpoint_function if hasattr(joinpoint_function, _INTE...
def is_intercepted(target): """True iif input target is intercepted. :param target: target to check such as an intercepted target. :return: True iif input target is intercepted. :rtype: bool """ result = False # get interception function from input target function = _get_function(target) result = hasattr(function, _INT...
def get_intercepted(target): """Get intercepted function and ctx from input target. :param target: target from where getting the intercepted function and ctx. :return: target intercepted function and ctx. (None, None) if no intercepted function exist. (fn, None) if not ctx exists. :rtype: tuple """ function = _get_func...
def _get_function(target): """Get target function. :param callable target: target from where get function. :return: depending on target type:: - class: constructor. - method: method function. - function: function. - else: __call__ method. :raises: TypeError if target is not callable or is a class without a constructor....
target.__init__ # if constructor is a method, return function method if ismethod(constructor): result = constructor.__func__ # else return constructor else: result = constructor elif ismethod(target): # if target is a method, return function method result = target.__func__ # return target if target is function or built...
def set_target(self, target, ctx=None): """Set target. :param target: new target to use. :param target ctx: target ctx if target is an class/instance attribute. """ if target is not None: # check if target is already intercepted if is_intercepted(target): # set self interception last target reference self._interception...
def start( self, target=None, args=None, kwargs=None, advices=None, exec_ctx=None, ctx=None ): """ Start to proceed this Joinpoint in initializing target, its arguments and advices. Call self.proceed at the end. :param callable target: new target to use in proceeding. self.target by default. :param tuple args: new targ...
init kwargs if not None if kwargs is not None: self.kwargs = kwargs # get advices to process if advices is None: if self._advices is not None: advices = self._advices else: advices = self.get_advices(self._interception) # initialize self._advices_iterator self._advices_iterator = iter(advices) # initialize execution co...
def proceed(self): """Proceed this Joinpoint in calling all advices with this joinpoint as the only one parameter, and call at the end the target. """ try: # get next advice advice = next(self._advices_iterator) except StopIteration: # if no advice can be applied # call target result = self.target(*self.args, **self.kw...
def apply_pointcut(self, target, function=None, ctx=None): """Apply pointcut on input target and returns final interception. The poincut respects all meta properties such as: - function signature, - module path, - file path, - __dict__ reference. """ try: __file__ = getfile(target) except TypeError: __file__ = '<string...
and updates updated = [] for wrapper_update in WRAPPER_UPDATES: if hasattr(function, wrapper_update): updated.append(wrapper_update) @wraps(function, assigned=assigned, updated=updated) def wrapper(*args, **kwargs): """Default wrapper.""" function = wrapper # get params from target wrapper args, varargs, kwargs, _ = ge...
", ")) newcodestr = join((newcodestr, "**{0}".format(kwargs))) newcodestr = join((newcodestr, "):\n")) # unique id which will be used for advicesexecutor and kwargs generated_id = repr(time()).replace('.', '_') # if kwargs is None if kwargs is None and args: kwargs = "kwargs_{0}".format(generated_id) # generate a name ...
"{0}{1}.kwargs = {2}\n".format( indent, joinpoint, kwargs)) ) # return advicesexecutor proceed result start = "start_{0}".format(generated_id) newcodestr = join( (newcodestr, "{0}return {1}()\n".format(indent, start)) ) # compile newcodestr code = compile(newcodestr, __file__, 'single') _globals = {} # define the code ...
= LOAD_CONST newcode[index + 1] = pos & 0xFF newcode[index + 2] = pos >> 8 if name == start: break # stop when start is encountered index += 1 # get code string codestr = bytes(newcode) if PY3 else join(map(chr, newcode)) # get vargs vargs = [ newco.co_argcount, newco.co_nlocals, newco.co_stacksize, newco.co_flags, cod...
value) # update wrapping updating for wrapper_update in WRAPPER_UPDATES: try: value = getattr(function, wrapper_update) except AttributeError: pass else: getattr(interception_fn, wrapper_update).update(value) # set interception, target function and ctx self._interception, self.target, self.ctx = _apply_interception( ta...
def read(f): """ Parse a String and return the data :param f: The file to read :type f: file/str :returns: A dictionary object containing the parsed data from f :raises: SyntaxError - An error occured reading the data. """ try: return PyVDF.reads(f.read()) except AttributeError: pass try: with open(f, 'r') as filec: da...
def reads(s): """ Parse a String and return the data :param s: The string to read :type s: :py:obj:`str` :returns: A dict object containing the data from s :raises: SyntaxError - An error occured reading the data. """ _dict = PyVDF.__UseDict _len = len _whitespace = frozenset('\t ') _newline = frozenset('\n\r') _quote_...
char == '\n': line += 1 # elif char == '\r': # if s[ci + 1] == '\n': # ci += 1 # line += 1 elif char == '{': if grabKey: raise Exception(PyVDF.__ERR_BlockNoKey.format(line, k)) else: keyApp(k) tree[k] = _dict() tree = tree[k] grabKey = 1 elif char == '}': if grabKey: keyPop() tree = data for key in keys: tree = tree[ke...
grabKey = 1 continue ci += 1 except IndexError: if _len(keys) == 0: return data raise Exception(PyVDF.__ERR_EODArray) except AttributeError: raise Exception(PyVDF.__ERR_BadToken.format(line, _max_length))
def formatData(data): """ Format a dictionary object to look like a VDF file :param data: Data :type data: :py:obj:`dict` :returns: A vdf string representation of data """ condensed = PyVDF.__CondensedOutput indentation = PyVDF.__OutputIndentation spacing = PyVDF.__OutputSpacing def loop(array, tab=''): string = '' for...
def writeData(f, data): """ Write a dictionary object to a file :param f: The file to write to :type f: file/string :param data: The data to write to the file :type data: dict """ if not isinstance(data, dict): raise Exception(PyVDF.__ERR_NotDict.format(repr(data))) data = PyVDF.formatData(data) try: f.write(data) exce...
def find(self, path): """ Find a value :param path: The Key path to search for :type path: :py:obj:`str` :returns: The found value or an empty string if not found. """ p = [re.sub('[\[\]]', '', w) for w in PyVDF.__RE_Path_Seperator.findall(path)] array = self.getData() for c in p: try: array = array[c] except KeyError:...
def edit(self, path, value): """ Edit a key value :param path: The path key for the value :type path: :py:obj:`str` :param value: The value to be set :type value: :py:obj:`str` """ _dict = PyVDF.__UseDict p = [re.sub('[\[\]]', '', w) for w in PyVDF.__RE_Path_Seperator.findall(path)] array = self.getData() a = array for...
def _runtime(self, project, base): ''' first runtimes all project type files, like `project/type.vim`, then the specific project file, like `project/type/name.vim`. ''' def run(path_suf): path = '{}/{}'.format(base, path_suf) err = 'error sourcing {}.vim: {{}}'.format(path) return ( self.vim.runtime(path) .cata(L(err.f...
def split_line(what, indent='', cols=79): """Split a line on the closest space, or break the last word with '-'. Args: what(str): text to spli one line of. indent(str): will prepend this indent to the split line, taking it into account in the column count. cols(int): maximum length of the split line. Returns: tuple(str...
try: closest_space = what[:cols].rindex(' ') except ValueError: closest_space = -1 if closest_space > len(indent): what, new_line = ( what[closest_space:], what[:closest_space], ) elif what[cols] == ' ': what, new_line = ( what[cols:], what[:cols], ) else: what, new_line = what[cols - 1:], what[:cols - 1] + '-' return ...
def fit_to_cols(what, indent='', cols=79): """Wrap the given text to the columns, prepending the indent to each line. Args: what(str): text to wrap. indent(str): indentation to use. cols(int): colt to wrap to. Returns: str: Wrapped text """ lines = [] while what: what, next_line = split_line( what=what, cols=cols, inde...
def compress(self, data_list): """Validates the captcha answer and returns the result If no data is provided, this method will simply return None. Otherwise, it will validate that the provided answer and timestamp hash to the supplied hash value, and that the timestamp is within the configured time that captchas are co...
def main(self, din): """ :param din: bit in :return: True if 100% correlation """ self.shr = self.shr[1:] + [din] if self.cooldown > 0: self.cooldown = self.cooldown - 1 return False if self.shr != self.HEADER: return False self.cooldown = self.COOLDOWN_RESET return True
def list(self, options=None, **kwds): """ Endpoint: /photos[/<options>]/list.json Returns a list of Photo objects. The options parameter can be used to narrow down the list. Eg: options={"album": <album_id>} """ option_string = self._build_option_string(options) photos = self._client.get("/photos%s/list.json" % option_...
def share(self, options=None, **kwds): """ Endpoint: /photos[/<options>/share.json Not currently implemented. """ option_string = self._build_option_string(options) return self._client.post("/photos%s/share.json" % option_string, **kwds)["result"]
def update(self, photos, **kwds): """ Endpoint: /photos/<id>/update.json Updates a list of photos with the specified parameters. Returns True if successful. Raises TroveboxError if not. """ ids = [self._extract_id(photo) for photo in photos] return self._client.post("/photos/update.json", ids=ids, **kwds)["result"]
def delete(self, photo, **kwds): """ Endpoint: /photo/<id>/delete.json Deletes a photo. Returns True if successful. Raises a TroveboxError if not. """ return self._client.post("/photo/%s/delete.json" % self._extract_id(photo), **kwds)["result"]
def delete_source(self, photo, **kwds): """ Endpoint: /photo/<id>/source/delete.json Delete the source files of a photo. Returns True if successful. Raises a TroveboxError if not. """ return self._client.post("/photo/%s/source/delete.json" % self._extract_id(photo), **kwds)["result"]
def replace(self, photo, photo_file, **kwds): """ Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace an existing photo. """ with open(photo_file, 'rb') as in_file: result = self._client.post("/photo/%s/replace.json" % self._extract_id(photo), files={'photo': in_file}, **kwds)["result"] retur...
def replace_from_url(self, photo, url, **kwds): """ Endpoint: /photo/<id>replace.json Import a photo from the specified URL to replace an existing photo. """ result = self._client.post("/photo/%s/replace.json" % self._extract_id(photo), photo=url, **kwds)["result"] return Photo(self._client, result)
def update(self, photo, **kwds): """ Endpoint: /photo/<id>/update.json Updates a photo with the specified parameters. Returns the updated photo object. """ result = self._client.post("/photo/%s/update.json" % self._extract_id(photo), **kwds)["result"] return Photo(self._client, result)
def view(self, photo, options=None, **kwds): """ Endpoint: /photo/<id>[/<options>]/view.json Requests all properties of a photo. Can be used to obtain URLs for the photo at a particular size, by using the "returnSizes" parameter. Returns the requested photo object. The options parameter can be used to pass in additiona...
def upload(self, photo_file, **kwds): """ Endpoint: /photo/upload.json Uploads the specified photo filename. """ with open(photo_file, 'rb') as in_file: result = self._client.post("/photo/upload.json", files={'photo': in_file}, **kwds)["result"] return Photo(self._client, result)
def upload_encoded(self, photo_file, **kwds): """ Endpoint: /photo/upload.json Base64-encodes and uploads the specified photo filename. """ with open(photo_file, "rb") as in_file: encoded_photo = base64.b64encode(in_file.read()) result = self._client.post("/photo/upload.json", photo=encoded_photo, **kwds)["result"] ret...
def upload_from_url(self, url, **kwds): """ Endpoint: /photo/upload.json Import a photo from the specified URL """ result = self._client.post("/photo/upload.json", photo=url, **kwds)["result"] return Photo(self._client, result)
def next_previous(self, photo, options=None, **kwds): """ Endpoint: /photo/<id>/nextprevious[/<options>].json Returns a dict containing the next and previous photo lists (there may be more than one next/previous photo returned). The options parameter can be used to narrow down the photos Eg: options={"album": <album_id...
def transform(self, photo, **kwds): """ Endpoint: /photo/<id>/transform.json Performs the specified transformations. eg. transform(photo, rotate=90) Returns the transformed photo. """ result = self._client.post("/photo/%s/transform.json" % self._extract_id(photo), **kwds)["result"] # APIv1 doesn't return the transforme...
def create_query(key, person, event=None, timestamp=None, identity=None, properties=None): """Build and encode query string. :param key: API key for product, found on the "KISSmetrics Settings". :param person: individual performing `event` :param event: event name that was performed :param timestamp: when `event` was p...
def check(self, *args): """ Check that the arguments haven't changed since the last call. Parameters ---------- *args: All but the last argument are inputs to the cached function. The last is the actual value of the function. Returns ------- If arguments unchanged: return the cached answer else: indicate recomputation ...
def load(self): """ Load cache from file using pickle. """ try: with open(self.file_root + '.pkl', "rb") as f: return pickle.load(f) except IOError: raise CacheMissing(self.file_root)
def save(self, *args): """ Save cache to file using pickle. Parameters ---------- *args: All but the last argument are inputs to the cached function. The last is the actual value of the function. """ with open(self.file_root + '.pkl', "wb") as f: pickle.dump(args, f, protocol=pickle.HIGHEST_PROTOCOL)
def main(req_port=None, res_port=None, use_security=False): '''main of queue :param req_port: port for clients :param res_port: port for servers ''' if req_port is None: req_port = env.get_req_port() if res_port is None: res_port = env.get_res_port() auth = None try: context = zmq.Context() frontend_service = context.s...
def tree(self): """ :rtype: cmdtree.tree.CmdTree """ from cmdtree.tree import CmdTree if self._tree is None: self._tree = CmdTree() return self._tree
def _set_fields(self, json_dict): """ Set this object's attributes specified in json_dict """ for key, value in json_dict.items(): if not key.startswith("_"): setattr(self, key, value)
def _replace_fields(self, json_dict): """ Delete this object's attributes, and replace with those in json_dict. """ for key in self._json_dict.keys(): if not key.startswith("_"): delattr(self, key) self._json_dict = json_dict self._set_fields(json_dict)
def _delete_fields(self): """ Delete this object's attributes, including name and id """ for key in self._json_dict.keys(): if not key.startswith("_"): delattr(self, key) self._json_dict = {} self.id = None self.name = None
def register(cls, subclass): """Register a virtual subclass of an ABC.""" if not isinstance(cls, type): raise TypeError("Can only register classes") if issubclass(subclass, cls): return # Already a subclass # Subtle: test for cycles *after* testing for "already a subclass"; # this means we allow X.register(X) and inter...
def main(pub_port=None, sub_port=None): '''main of forwarder :param sub_port: port for subscribers :param pub_port: port for publishers ''' try: if sub_port is None: sub_port = get_sub_port() if pub_port is None: pub_port = get_pub_port() context = zmq.Context(1) frontend = context.socket(zmq.SUB) backend = context.soc...
def update_state_from_api(self): """ Pull and update the current state from the API. """ if self.last_api_call is not None: difference = (datetime.datetime.now() - self.last_api_call).seconds else: # This is the first run, so we need to get the lastest state. difference = 301 if difference >= 300: url = BASE_URL + "/re...
def authenticate(self, reauth=False): """ Authenticate with the API and return an authentication token. """ auth_url = BASE_URL + "/rest/user" payload = {'email': self.email, 'password': self.password} arequest = requests.get(auth_url, params=payload) status = arequest.status_code if status != 200: if reauth: _LOGGER.e...
def get_trackrs(self): """ Extract each Trackr device from the trackrApiInterface state. return a list of all Trackr objects from account. """ trackrs = [] for trackr in self.state: trackrs.append(trackrDevice(trackr, self)) return trackrs
def check_python_version(): """Checks the python version, exists if != 2.7.""" python_major, python_minor = sys.version_info[:2] if python_major != 2 or python_minor != 7: sys.stderr.write("pyGenClean requires python 2.7") sys.exit(1)
def search_records(self, **kwargs): """ rq Search Query in iDigBio Query Format, using Record Query Fields sort field to sort on, pick from Record Query Fields fields a list of fields to return, specified using the fieldName parameter from Fields with type records fields_exclude a list of fields to exclude, specified u...
def search_media(self,**kwargs): """ mq Search Query in iDigBio Query Format, using Media Query Fields rq Search Query in iDigBio Query Format, using Record Query Fields sort field to sort on, pick from Media Query Fields fields a list of fields to return, specified using the fieldName parameter from Fields with type m...
def get_timetable_html (self, module): """ TWINSの表に教室情報を追加したHTMLを返す。""" if not module.startswith("春") and \ not module.startswith("秋"): raise RequestError() module_code, gakkiKbnCode = { "春A": (1, "A"), "春B": (2, "A"), "春C": (3, "A"), "秋A": (4, "B"), "秋B": (5, "B"), "秋C": (6, "B") }.get(module) self.req("RSW0001000-flo...
<head> <meta charset="utf-8"> <title>時間割 (%(module)s)</title> <style> body { font-family: sans-serif; background: #fff; color: #343434; } a{ color: #3f3f3f; text-decoration: none; } .rishu-etc-head, .rishu-koma-head { background: #6a8cc7; } </style> </head><body> <h2>%(module)s 時間割</h2> %(html)s </body></html> """ % lo...
def register_course (self, course_id): """ 履修申請する """ # 何モジュール開講か取得 kdb = twins.kdb.Kdb() first_module = kdb.get_course_info(course_id)["modules"][:2] if not first_module.startswith("春") and \ not first_module.startswith("秋"): raise RequestError() module_code, gakkiKbnCode = { "春A": (1, "A"), "春B": (2, "A"), "春C": (3, ...
def unregister_course (self, course_id): """ 履修申請を取り消す """ course_id = course_id.upper() # 何モジュール開講か取得 kdb = twins.kdb.Kdb() first_module = kdb.get_course_info(course_id)["modules"][:2] if not first_module.startswith("春") and \ not first_module.startswith("秋"): raise RequestError() module_code, gakkiKbnCode = { "春A": (...
if errmsg != "": raise RequestError()
def get_registered_credits (self): """ 登録単位数合計の取得 """ self.req("RSW0001000-flow") r = self.get({ "_eventId": "search", "moduleCode": 1, "gakkiKbnCode": "A" }) html = r.text # XXX for l in html.split("\n"): if "単位</td>" in l: return float(l.strip().replace('<td align="center">', ""). replace("単位</td>", "")) return 0.
def get_registered_courses (self): """ 履修登録済み授業を取得 """ kdb = twins.kdb.Kdb() _reged = [] for x in ((1, "A"), (2, "A"), (3, "A"), (4, "B"), (5, "B"), (6, "B")): self.req("RSW0001000-flow") self.get({ "_eventId": "search", "moduleCode": x[0], "gakkiKbnCode": x[1] }) self.post({"_eventId": "output"}, True) r = self.post({...
def get_achievements_summary (self): """ 履修成績要約の取得 (累計)""" r = self.req("SIW0001200-flow") # XXX ret = {} k = "" for d in pq(r.text)("td"): if d.text is None: continue if k != "": # 全角英字ダメゼッタイ if k == "GPA": k = "GPA" ret[k] = d.text.strip() k = "" continue k = d.text.strip() if k == "履修単位数" or k == "修得単位数" or k == "GP...
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True): """Evaluates by creating a MultiIndex containing evaluated data and index. See `LazyResult` Returns ------- MultiIndex MultiIndex with evaluated data. """ evaluated_data = [v.evaluate(verbose, decode, passes, num_thread...
def tail(self, n=5): """Return MultiIndex with the last n values in each column. Parameters ---------- n : int Number of values. Returns ------- MultiIndex MultiIndex containing the last n values in each column. """ # not computing slice here to use with __getitem__ because we'd need to use len which is eager return Mu...
def dropna(self): """Returns MultiIndex without any rows containing null values according to Baloo's convention. Returns ------- MultiIndex MultiIndex with no null values. """ not_nas = [v.notna() for v in self.values] and_filter = reduce(lambda x, y: x & y, not_nas) return self[and_filter]
def from_pandas(cls, index): """Create baloo MultiIndex from pandas MultiIndex. Parameters ---------- index : pandas.multi.MultiIndex Returns ------- MultiIndex """ from pandas import MultiIndex as PandasMultiIndex check_type(index, PandasMultiIndex) baloo_level_values = [Index.from_pandas(index.get_level_values(level)...
def to_pandas(self): """Convert to pandas MultiIndex. Returns ------- pandas.base.MultiIndex """ if not all(ind.is_raw() for ind in self.values): raise ValueError('Cannot convert to pandas MultiIndex if not evaluated.') from pandas import MultiIndex as PandasMultiIndex arrays = [ind.values for ind in self.values] retur...
def main(): """The main function of the module. These are the steps: 1. Reads the population file (:py:func:`readPopulations`). 2. Extracts the MDS values (:py:func:`extractData`). 3. Plots the MDS values (:py:func:`plotMDS`). """ # Getting and checking the options args = parseArgs() checkArgs(args) # Reads the populat...
def readPopulations(inputFileName, requiredPopulation): """Reads a population file. :param inputFileName: the name of the population file. :param requiredPopulation: the required population. :type inputFileName: str :type requiredPopulation: list :returns: a :py:class:`dict` containing the population of each samples. "...
set(populations.values()) if len(popMissing) != 0: msg = "Population that were asked for doesn't exists in " \ "population file: %s" % str(popMissing) raise ProgramError(msg) return populations
def plotMDS(data, theOrders, theLabels, theColors, theAlphas, theSizes, theMarkers, options): """Plot the MDS data. :param data: the data to plot (MDS values). :param theOrders: the order of the populations to plot. :param theLabels: the names of the populations to plot. :param theColors: the colors of the populations ...
mpl.use("Agg") import matplotlib.pyplot as plt if options.format != "X11": plt.ioff() fig = plt.figure() try: fig.subplots_adjust(right=options.adjust_right, left=options.adjust_left, bottom=options.adjust_bottom, top=options.adjust_top) except ValueError as e: raise ProgramError(e) ax = fig.add_subplot(111) # Setting ...
Show the plot plt.show() else: fileName = options.out + "." + options.format try: plt.savefig(fileName, dpi=300) except IOError: msg = "%(fileName)s: can't write file" % locals() raise ProgramError(msg) except ValueError as e: colorError = False for errorMsg in str(e).split("\n"): if errorMsg.startswith("to_rgb"): colo...
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t...
color colors = [] for color in args.population_colors.split(","): colors.append("#" + color) args.population_colors = colors if len(args.population_colors) < nbPop: msg = "not enough colors for the required populations" raise ProgramError(msg) # Format the point size sizes = [] for size in args.population_sizes.split("...
= "%s: alpha for legend must be between " \ "0 and 1" % str(args.legend_alpha) raise ProgramError(msg) return True
def parallel_apply(f, array, **kwargs): """ Apply a function to an array with openmp parallelisation. Equivalent to `[f(x) for x in array]`, but parallelised if required. Parameters ---------- f: function Univariate function to apply to each element of array array: array-like Array to apply f to parallel: int or bool, ...
to parallel """ precurry = tuple(kwargs.pop('precurry', ())) postcurry = tuple(kwargs.pop('postcurry', ())) parallel = kwargs.pop('parallel', False) tqdm_kwargs = kwargs.pop('tqdm_kwargs', {}) if kwargs: raise TypeError('Unexpected **kwargs: %r' % kwargs) try: # If running in a jupyter notebook then use tqdm_notebook. ...
x in progress(array, **tqdm_kwargs))
def spin(self, use_thread=False): '''call callback for all data forever (until \C-c) :param use_thread: use thread for spin (do not block) ''' if use_thread: if self._thread is not None: raise 'spin called twice' self._thread = threading.Thread(target=self._spin_internal) self._thread.setDaemon(True) self._thread.start...
def vars_(object=None): """ Clean all of the property starts with "_" then return result of vars(object). """ filtered_vars = {} vars_dict = vars(object) for key, value in six.iteritems(vars_dict): if key.startswith("_"): continue filtered_vars[_normalize_arg_name(key)] = value return filtered_vars
def add_cmd(self, name, help=None, func=None): """ If func is None, this is regarded as a sub-parser which can contains sub-command. Else, this is a leaf node in cmd tree which can not add sub-command. :rtype: AParser """ if self.subparsers is None: self.subparsers = self.add_subparsers( title="sub-commands", help=help...
def delete(self, **kwds): """ Endpoint: /photo/<id>/delete.json Deletes this photo. Returns True if successful. Raises a TroveboxError if not. """ result = self._client.photo.delete(self, **kwds) self._delete_fields() return result
def replace(self, photo_file, **kwds): """ Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace this photo. """ result = self._client.photo.replace(self, photo_file, **kwds) self._replace_fields(result.get_fields())
def replace_from_url(self, url, **kwds): """ Endpoint: /photo/<id>replace.json Import a photo from the specified URL to replace this photo. """ result = self._client.photo.replace_from_url(self, url, **kwds) self._replace_fields(result.get_fields())
def update(self, **kwds): """ Endpoint: /photo/<id>/update.json Updates this photo with the specified parameters. """ result = self._client.photo.update(self, **kwds) self._replace_fields(result.get_fields())
def view(self, options=None, **kwds): """ Endpoint: /photo/<id>[/<options>]/view.json Requests all properties of this photo. Can be used to obtain URLs for the photo at a particular size, by using the "returnSizes" parameter. Updates the photo's fields with the response. The options parameter can be used to pass in add...
def next_previous(self, options=None, **kwds): """ Endpoint: /photo/<id>/nextprevious[/<options>].json Returns a dict containing the next and previous photo lists (there may be more than one next/previous photo returned). """ return self._client.photo.next_previous(self, options, **kwds)
def transform(self, **kwds): """ Endpoint: /photo/<id>/transform.json Performs the specified transformations. eg. transform(photo, rotate=90) Updates the photo's fields with the response. """ result = self._client.photo.transform(self, **kwds) self._replace_fields(result.get_fields())
def _copy_body_to_tempfile(cls, environ): """ Copy wsgi.input to a tempfile so it can be reused. """ try: length = int(environ.get('CONTENT_LENGTH', 0)) except ValueError: length = 0 try: fileobj = tempfile.SpooledTemporaryFile(1024*1024) except AttributeError: # pragma: nocover fileobj = tempfile.TemporaryFile() # py2...
def get_rc_creds(): """ Reads ~/.rightscalerc and returns API endpoint and refresh token. Always returns a tuple of strings even if the file is empty - in which case, returns ``('', '')``. """ config = get_config() try: return ( config.get(CFG_SECTION_OAUTH, CFG_OPTION_ENDPOINT), config.get(CFG_SECTION_OAUTH, CFG_OPTIO...
def find_by_name(collection, name, exact=True): """ Searches collection by resource name. :param rightscale.ResourceCollection collection: The collection in which to look for :attr:`name`. :param str name: The name to look for in collection. :param bool exact: A RightScale ``index`` search with a :attr:`name` filter ca...
= collection.index(params=params) if not exact and len(found) > 0: return found for f in found: if f.soul['name'] == name: return f
def kmer_lca_records(seqs_path, one_codex_api_key: 'One Codex API key' = None, fastq: 'input is fastq; disable autodetection' = False, progress: 'show progress bar (sent to stderr)' = False): ''' Parallel lowest common ancestor sequence classification of fasta/q using the One Codex API. Returns Biopython SeqRecords wit...