text
stringlengths
81
112k
Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>. Input images can be given as: 1. paths to NIfTI image files or as 2. Numpy arrays. The ROI value must be given as a dictionary of lists of indexes for each ROI Outputs a float number represe...
Generate a new Skybellpy token. def gen_token(): """Generate a new Skybellpy token.""" return ''.join( random.choice( string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(32))
Validate the setting and value. def _validate_setting(setting, value): """Validate the setting and value.""" if setting not in CONST.ALL_SETTINGS: raise SkybellException(ERROR.INVALID_SETTING, setting) if setting == CONST.SETTINGS_DO_NOT_DISTURB: if value not in CONST.SETTINGS_DO_NOT_DISTU...
Refresh the devices json object data. def refresh(self): """Refresh the devices json object data.""" # Update core device data new_device_json = self._device_request() _LOGGER.debug("Device Refresh Response: %s", new_device_json) # Update avatar url new_avatar_json = se...
Update the internal device json data. def update(self, device_json=None, info_json=None, settings_json=None, avatar_json=None): """Update the internal device json data.""" if device_json: UTILS.update(self._device_json, device_json) if avatar_json: UTILS....
Update stored activities and update caches as required. def _update_activities(self): """Update stored activities and update caches as required.""" self._activities = self._activities_request() _LOGGER.debug("Device Activities Response: %s", self._activities) if not self._activities: ...
Update our cached list of latest activity events. def _update_events(self): """Update our cached list of latest activity events.""" events = self._skybell.dev_cache(self, CONST.EVENT) or {} for activity in self._activities: event = activity.get(CONST.EVENT) created_at =...
Return device activity information. def activities(self, limit=1, event=None): """Return device activity information.""" activities = self._activities or [] # Filter our activity array if requested if event: activities = list( filter( lam...
Validate the settings and then send the PATCH request. def _set_setting(self, settings): """Validate the settings and then send the PATCH request.""" for key, value in settings.items(): _validate_setting(key, value) try: self._settings_request(method="patch", json_data=...
Return lat and lng tuple. def location(self): """Return lat and lng tuple.""" location = self._device_json.get(CONST.LOCATION, {}) return (location.get(CONST.LOCATION_LAT, 0), location.get(CONST.LOCATION_LNG, 0))
Get the wifi status. def wifi_status(self): """Get the wifi status.""" return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK)
Get if do not disturb is enabled. def do_not_disturb(self): """Get if do not disturb is enabled.""" return bool(strtobool(str(self._settings_json.get( CONST.SETTINGS_DO_NOT_DISTURB))))
Set do not disturb. def do_not_disturb(self, enabled): """Set do not disturb.""" self._set_setting( { CONST.SETTINGS_DO_NOT_DISTURB: str(enabled).lower() })
Set the motion sensor state. def motion_sensor(self, enabled): """Set the motion sensor state.""" if enabled is True: value = CONST.SETTINGS_MOTION_POLICY_ON elif enabled is False: value = CONST.SETTINGS_MOTION_POLICY_OFF else: raise SkybellException(...
Get devices LED color. def led_rgb(self): """Get devices LED color.""" return (int(self._settings_json.get(CONST.SETTINGS_LED_R)), int(self._settings_json.get(CONST.SETTINGS_LED_G)), int(self._settings_json.get(CONST.SETTINGS_LED_B)))
Set devices LED color. def led_rgb(self, color): """Set devices LED color.""" if (not isinstance(color, (list, tuple)) or not all(isinstance(item, int) for item in color)): raise SkybellException(ERROR.COLOR_VALUE_NOT_VALID, color) self._set_setting( { ...
Configures remote access Parameters ---------- remote_base : str base URL path for remote repository username : str user name for remote repository password : str password for local repository def remote(self, remote_base=None, username=None,...
Returns file name, downloading if remote access configured. Parameters ---------- filetype : str type of file keyword arguments : keywords to fully specify path Notes ----- Path templates are defined in $DIMAGE_DIR/data/dimage_paths.ini ...
Download a file from url via http, and put it at path Parameters ---------- url : str URL of file to download path : str local path to put file in def download_url_to_path(self, url, path, force=False): """ Download a file from url via http, an...
Configures remote access def remote(self, username=None, password=None, inquire=None): """ Configures remote access """ self.set_netloc(sdss=True) # simplifies things to have a single sdss machine in .netrc self.set_auth(username=username, password=password, inquire=inquire) self.set_...
Reset all streams def reset(self): ''' Reset all streams ''' # reset the main stream if self.stream: self.stream.reset() # reset the initial stream (otherwise old 'adds' remain in the new stream) if self.initial_stream: self.initial_stream.reset()
Adds a filepath into the list of tasks to download def add(self, filetype, **kwargs): """ Adds a filepath into the list of tasks to download""" location = self.location(filetype, **kwargs) source = self.url(filetype, sasdir='sas' if not self.public else '', **kwargs) if 'full' not in k...
Sets the download streams def set_stream(self): """ Sets the download streams """ if not self.auth: raise AccessError("Please use the remote() method to set rsync authorization or use remote(public=True) for public data") elif not self.initial_stream.task: raise AccessE...
Start the rsync download def commit(self, offset=None, limit=None, dryrun=False): """ Start the rsync download """ self.stream.command = "rsync -avRK --files-from={path} {source} {destination}" self.stream.append_tasks_to_streamlets(offset=offset, limit=limit) self.stream.commit_stream...
Returns account balance after this entry. :return: Decimal def balance(self) -> Decimal: """ Returns account balance after this entry. :return: Decimal """ return sum_queryset(AccountEntry.objects.filter(account=self.account, timestamp__lte=self.timestamp).exclude(timest...
Returns account balance before specified datetime (excluding entries on the datetime). :param t: datetime :return: Decimal def get_balance(self, t: datetime): """ Returns account balance before specified datetime (excluding entries on the datetime). :param t: datetime :r...
Returns True if all of following conditions are True: a) entry type is settlement b) entry has been recorded to this account c) invoice to be settled has been set d) entry has not been settled (=child set empty) :param e: AccountEntry (settlement) :return: bool def needs...
Returns receivables account. Receivables account is assumed to be the one were invoice rows were recorded. :return: Account or None def receivables_account(self) -> Account: """ Returns receivables account. Receivables account is assumed to be the one were invoice rows were recorded. :r...
Returns entries related to this invoice on specified account. :param acc: Account :param cls: AccountEntry class :return: QuerySet def get_entries(self, acc: Account, cls=AccountEntry) -> QuerySet: """ Returns entries related to this invoice on specified account. :param ...
Returns balances of items of the invoice. :param acc: Account :return: list (AccountEntry, Decimal) in item id order def get_item_balances(self, acc: Account) -> list: """ Returns balances of items of the invoice. :param acc: Account :return: list (AccountEntry, Decimal)...
Returns unpaid items of the invoice in payback priority order. :param acc: Account :return: list (AccountEntry, Decimal) in payback priority order def get_unpaid_items(self, acc: Account) -> list: """ Returns unpaid items of the invoice in payback priority order. :param acc: Acc...
Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]] def MakeRanges(codes): """Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]""" ranges = [] last = -100 for c in codes: if c == last+1: ranges[-1][1] = c else: ranges.append([c, c]) last = c return ranges
Print the ranges as an array of type named name. def PrintRanges(type, name, ranges): """Print the ranges as an array of type named name.""" print "static const %s %s[] = {" % (type, name,) for lo, hi in ranges: print "\t{ %d, %d }," % (lo, hi) print "};"
Print the data structures for the group of codes. Return a UGroup literal for the group. def PrintGroup(name, codes): """Print the data structures for the group of codes. Return a UGroup literal for the group.""" # See unicode_groups.h for a description of the data structure. # Split codes into 16-bit rang...
Finds unpaid items in the invoice and generates entries to receivables account. Settlement is matched to invoice items based on entry types payback order. Generated payment entries have 'parent' field pointing to settlement, so that if settlement is (ever) deleted the payment entries will get deleted as wel...
Settles credit note. Records settling account entries for both original invoice and the credit note (negative entries for the credit note). Default timestamp for account entries is 'created' time of the credit note, can be overriden by kwargs. :param credit_note: Credit note to settle :param debit_note:...
Read the path template file. def _input_templates(self): """Read the path template file. """ foo = self._config.read([self._pathfile]) if len(foo) == 1: for k, v in self._config.items('paths'): self.templates[k] = v else: raise ValueError(...
Lookup the keyword arguments needed for a given path name Parameters: name (str): The name of the path Returns: A list of keywords needed for filepath generation def lookup_keys(self, name): ''' Lookup the keyword arguments needed for a given path name ...
check special functions for kwargs Checks the content of the special functions (%methodname) for any keyword arguments referenced within Parameters: name (str): A path key name Returns: A list of keyword arguments found in any special fu...
find source code of a given method Find and extract the source code of a given method in a module. Uses inspect.findsource to get all source code and performs some selection magic to identify method source code. Doing it this way because inspect.getsource returns wrong method. ...
Extract keywords from an example path def extract(self, name, example): ''' Extract keywords from an example path ''' # if pathlib not available do nothing if not pathlib: return None # ensure example is a string if isinstance(example, pathlib.Path): ex...
Return the directory containing a file of a given type. Parameters ---------- filetype : str File type parameter. Returns ------- dir : str Directory containing the file. def dir(self, filetype, **kwargs): """Return the directory contain...
Return the directory containing a file of a given type. Parameters ---------- filetype : str File type parameter. Returns ------- name : str Name of a file with no directory information. def name(self, filetype, **kwargs): """Return the ...
Checks if the given type of file exists locally Parameters ---------- filetype : str File type parameter. remote : bool If True, checks for remote existence of the file Returns ------- exists : bool Boolean indicating if the ...
Expand a wildcard path locally Parameters ---------- filetype : str File type parameter. as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection ...
Checks if the local directory contains any of the type of file Parameters ---------- filetype : str File type parameter. Returns ------- any : bool Boolean indicating if the any files exist in the expanded path on disk. def any(self, filetype, *...
Returns random one of the given type of file Parameters ---------- filetype : str File type parameter. as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random sel...
Returns random number of the given type of file Parameters ---------- filetype : str File type parameter. num : int The number of files to return as_url: bool Boolean to return SAS urls refine: str Regular expression str...
Returns a list of files filterd by a regular expression Parameters ---------- filelist : list A list of files to filter on. regex : str The regular expression string to filter your list filterdir: {'in', 'out'} Indicates the filter to be inc...
Return the full name of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The full path to the file. def full(self, filetype, **kwargs): """Return the full name of a given type of ...
Call the special functions found in a template path Calls special functions indicated by %methodname found in the sdss_paths.ini template file, and replaces the %location in the path with the returned content. Parameters: filetype (str): template name of fil...
Return the location of the relative sas path of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The relative sas path to the file. def location(self, filetype, base_dir=None, **kwargs): ...
Return the url of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The sas url to the file. def url(self, filetype, base_dir=None, sasdir='sas', **kwargs): """Return the url of a ...
Print plate ID, accounting for 5-6 digit plate IDs. Parameters ---------- filetype : str File type parameter. plateid : int or str Plate ID number. Will be converted to int internally. Returns ------- plateid6 : str Plate ID ...
Returns plate subdirectory in :envvar:`PLATELIST_DIR` of the form: ``NNNNXX/NNNNNN``. Parameters ---------- filetype : str File type parameter. plateid : int or str Plate ID number. Will be converted to int internally. Returns ------- pl...
Returns :envvar:`SPECTRO_REDUX` or :envvar:`BOSS_SPECTRO_REDUX` depending on the value of `run2d`. Parameters ---------- filetype : str File type parameter. run2d : int or str 2D Reduction ID. Returns ------- spectrodir : str ...
Returns definition subdirectory in :envvar:`PLATELIST_DIR` of the form: ``NNNNXX``. Parameters ---------- filetype : str File type parameter. designid : int or str Design ID number. Will be converted to int internally. Returns ------- de...
A convenient wrapper to log and perform system calls. Parameters ---------- command : str The system command to run. It will be split internally by shlex.split(). test : bool, optional Set this to true to not actually run the commands. logger : logging.l...
create, edit or delete a change list Create, edit or delete a change list. A change list is a group of files to be reviewed and submitted together, plus a textual description of the change. Change lists are referred to by simple alphanumeric names. Changes must be reviewed before they can be submitted. In the ...
undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. def undo(ui, repo, clname, **opts): """undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating th...
apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a clean client, disabling the code review plugin, ...
download a change from the code review server Download prints a description of the given change list followed by its diff, downloaded from the code review server. def download(ui, repo, clname, **opts): """download a change from the code review server Download prints a description of the given change list follo...
assign files to or remove files from a change list Assign files to or (with -d) remove files from a change list. The -d option only removes files from the change list. It does not edit them or remove them from the repository. def file(ui, repo, clname, pat, *pats, **opts): """assign files to or remove files from...
apply gofmt to modified files Applies gofmt to the modified files in the repository that match the given patterns. def gofmt(ui, repo, *pats, **opts): """apply gofmt to modified files Applies gofmt to the modified files in the repository that match the given patterns. """ if codereview_disabled: raise hg_ut...
mail a change for review Uploads a patch to the code review server and then sends mail to the reviewer and CC list asking for a review. def mail(ui, repo, *pats, **opts): """mail a change for review Uploads a patch to the code review server and then sends mail to the reviewer and CC list asking for a review. "...
alias for hg p --short def ps(ui, repo, *pats, **opts): """alias for hg p --short """ opts['short'] = True return pending(ui, repo, *pats, **opts)
alias for hg p --quick def pq(ui, repo, *pats, **opts): """alias for hg p --quick """ opts['quick'] = True return pending(ui, repo, *pats, **opts)
show pending changes Lists pending changes followed by a list of unassigned but modified files. def pending(ui, repo, *pats, **opts): """show pending changes Lists pending changes followed by a list of unassigned but modified files. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) quick ...
submit change to remote repository Submits change to remote repository. Bails out if the local repository is not in sync with the remote one. def submit(ui, repo, *pats, **opts): """submit change to remote repository Submits change to remote repository. Bails out if the local repository is not in sync with the ...
synchronize with remote repository Incorporates recent changes from the remote repository into the local repository. def sync(ui, repo, **opts): """synchronize with remote repository Incorporates recent changes from the remote repository into the local repository. """ if codereview_disabled: raise hg_util.A...
upload diffs to the code review server Uploads the current modifications for a given change to the server. def upload(ui, repo, name, **opts): """upload diffs to the code review server Uploads the current modifications for a given change to the server. """ if codereview_disabled: raise hg_util.Abort(coderevie...
Run MySend1 maybe twice, because Rietveld is unreliable. def MySend(request_path, payload=None, content_type="application/octet-stream", timeout=None, force_auth=True, **kwargs): """Run MySend1 maybe twice, because Rietveld is unreliable.""" try: return MySend1(request_path, payload, content_type, timeout, f...
Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for larg...
Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. def G...
Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCrede...
Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: http://aspn.activestate...
Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, retu...
Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A stri...
Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patche...
Creates a new urllib request. def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in sel...
Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authenti...
Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token...
Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obta...
Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: fo...
Save the cookie jar after authentication. def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save()
Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add...
Show an "are you sure?" prompt if there are unknown files. def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: p...
Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the...
Uploads the base files (and if necessary, the current ones as well). def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): ...
Returns true if the filename has an image extension. def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/")
Returns true if the guessed mimetyped isnt't in text group. def IsBinary(self, filename): """Returns true if the guessed mimetyped isnt't in text group.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False # e.g. README, "real" binaries usually have an extension # special case for ...
Get relative path of a file according to the current directory, given its logical path in the repo. def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), (filename, self.subdir) retur...
Return a list of files unknown to the VCS. def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if ...
Converts string to Unicode code point ('263A' => 0x263a). Args: s: string to convert Returns: Unicode code point Raises: InputError: the string is not a valid Unicode value. def _UInt(s): """Converts string to Unicode code point ('263A' => 0x263a). Args: s: string to convert Returns: ...
Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range. def _URange(s): """Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [...
Parses a Unicode continuation field. These are of the form '<Name, First>' or '<Name, Last>'. Instead of giving an explicit range in a single table entry, some Unicode tables use two entries, one for the first code value in the range and one for the last. The first entry's description is '<Name, First>' inst...
Generic Unicode table text file reader. The reader takes care of stripping out comments and also parsing the two different ways that the Unicode tables specify code ranges (using the .. notation and splitting the range across multiple lines). Each non-comment line in the table is expected to have the given ...
Returns list of Unicode code groups equivalent under case folding. Each group is a sorted list of code points, and the list of groups is sorted by first code point in the group. Args: unicode_dir: Unicode data directory Returns: list of Unicode code groups def CaseGroups(unicode_dir=_UNICODE_DIR):...
Returns dict mapping script names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping script names to code lists def Scripts(unicode_dir=_UNICODE_DIR): """Returns dict mapping script names to code lists. Args: unicode_dir: Unicode data directory Returns: dict ma...
Returns dict mapping category names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping category names to code lists def Categories(unicode_dir=_UNICODE_DIR): """Returns dict mapping category names to code lists. Args: unicode_dir: Unicode data directory Returns: ...