code stringlengths 1 18.2k |
|---|
self[saveframe].keys(): if ind.startswith(u"loop_"): if list(self[saveframe][ind][0]) == chemshifts_loop: chem_shifts_dict = OrderedDict() for entry in self[saveframe][ind][1]: residue_id = entry[aminoacid_seq_id] chem_shifts_dict.setdefault(residue_id, OrderedDict()) chem_shifts_dict[residue_id][u"AA3Code"] = entry[am... |
def _build_file(self, cif_str): """Build :class:`~nmrstarlib.nmrstarlib.CIFFile` object. :param cif_str: NMR-STAR-formatted string. :type cif_str: :py:class:`str` or :py:class:`bytes` :return: instance of :class:`~nmrstarlib.nmrstarlib.CIFFile`. :rtype: :class:`~nmrstarlib.nmrstarlib.CIFFile` """ odict = self comment_c... |
def print_file(self, f=sys.stdout, file_format="cif", tw=0): """Print :class:`~nmrstarlib.nmrstarlib.CIFFile` into a file or stdout. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `cif` or `json`. :param int tw: Tab width. :return: None :rtype: :py:obj:`None` """ if file_format ... |
def GET(self, func, data): """Send GET request to execute Ndrive API :param func: The function name you want to execute in Ndrive API. :param params: Parameter data for HTTP request. :returns: metadata when success or False when failed """ if func not in ['getRegisterUserInfo']: s, message = self.checkAccount() if s is... |
def POST(self, func, data): """Send POST request to execute Ndrive API :param func: The function name you want to execute in Ndrive API. :param params: Parameter data for HTTP request. :returns: ``metadata`` when success or ``False`` when failed """ s, message = self.checkAccount() if s is False: return False, message ... |
def getRegisterUserInfo(self, svctype = "Android NDrive App ver", auth = 0): """Retrieve information about useridx :param svctype: Information about the platform you are using right now. :param auth: Authentication type :return: ``True`` when success or ``False`` when failed """ data = {'userid': self.user_id, 'svctype... |
def uploadFile(self, file_obj, full_path, overwrite = False): """Upload a file as Ndrive really do. >>> nd.uploadFile('~/flower.png','/Picture/flower.png',True) This function imitates the process when Ndrive uploads a local file to its server. The process follows 7 steps: 1. POST /CheckStatus.ndrive 2. POST /GetDiskSpa... |
s = self.checkUpload(file_obj, full_path, overwrite) if s is True: self.put(file_obj, full_path, overwrite) |
def getDiskSpace(self): """Get disk space information. >>> disk_info = nd.getDiskSpace() :return: ``metadata`` if success or ``error message`` :metadata: - expandablespace - filemaxsize - largefileminsize - largefileunusedspace - largefileusedspace - paymentspace - totallargespace - totalspace - unusedspace - usedspace... |
def checkUpload(self, file_obj, full_path = '/', overwrite = False): """Check whether it is possible to upload a file. >>> s = nd.checkUpload('~/flower.png','/Picture/flower.png') :param file_obj: A file-like object to check whether possible to upload. You can pass a string as a file_obj or a real file object. :param s... |
now, 'dstresource': full_path, 'userid': self.user_id, 'useridx': self.useridx, } s, metadata = self.POST('checkUpload', data) if not s: print metadata return s |
def downloadFile(self, from_path, to_path = ''): """Download a file. >>> nd.downloadFile('/Picture/flower.png', '~/flower.png') :param from_path: The full path to download the file to, *including the file name*. If the destination directory does not yet exist, it will be created. :param to_path: The full path of a file... |
def put(self, file_obj, full_path, overwrite = False): """Upload a file. >>> nd.put('./flower.png','/Picture/flower.png') >>> nd.put(open('./flower.png','r'),'/Picture/flower.png') :param file_obj: A file-like object to check whether possible to upload. You can pass a string as a file_obj or a real file object. :param ... |
'XMLHttpRequest', 'NDriveSvcType': 'NHN/DRAGDROP Ver', } r = self.session.put(url = url, data = content, headers = headers) r.encoding = 'utf-8' message = json.loads(r.text)['message'] if message != 'success': print "Error put: " + message return False else: print "Success put: " + file_obj.name return True |
def delete(self, full_path): """Delete a file in full_path >>> nd.delete('/Picture/flower.png') :param full_path: The full path to delete the file to, *including the file name*. :return: ``True`` if success to delete the file or ``False`` """ now = datetime.datetime.now().isoformat() url = nurls['delete'] + full_path h... |
def getList(self, full_path, type = 1, dept = 0, sort = 'name', order = 'asc', startnum = 0, pagingrow = 1000, dummy = 56184): """Get a list of files >>> nd_list = nd.getList('/', type=3) >>> print nd_list There are 5 kinds of ``type``: - 1 => only directories with idxfolder property - 2 => only files - 3 => directorie... |
:param full_path: The full path to get the file list. :param type: 1, 2, 3, 4 or 5 :param depth: Dept for file list :param sort: name => 이름 :param order: Order by (asc, desc) :return: metadata (list of dict) or False when failed to get list :metadata: - u'copyright': u'N', - u'creationdate': u'2013-05-12T21:17:23+09:00... |
'type': type, 'dept': dept, 'sort': sort, 'order': order, 'startnum': startnum, 'pagingrow': pagingrow, 'userid': self.user_id, 'useridx': self.useridx, 'dummy': dummy, } s, metadata = self.POST('getList', data) if s is True: return metadata else: print metadata return False |
def doMove(self, from_path, to_path, overwrite = False, bShareFireCopy = 'false', dummy = 56147): """Move a file. >>> nd.doMove('/Picture/flower.png', '/flower.png') :param from_path: The path to the file or folder to be moved. :param to_path: The destination path of the file or folder to be copied. File name should be... |
def makeDirectory(self, full_path, dummy = 40841): """Make a directory >>> nd.makeDirectory('/test') :param full_path: The full path to get the directory property. Should be end with '/'. :return: ``True`` when success to make a directory or ``False`` """ if full_path[-1] is not '/': full_path += '/' data = {'dstresour... |
def makeShareUrl(self, full_path, passwd): """Make a share url of directory >>> nd.makeShareUrl('/Picture/flower.png', PASSWORD) Args: full_path: The full path of directory to get share url. Should be end with '/'. ex) /folder/ passwd: Access password for shared directory Returns: URL: share url for a directory False: ... |
def getFileLink(self, full_path): """Get a link of file >>> file_link = nd.getFileLink('/Picture/flower.png') :param full_path: The full path of file to get file link. Path should start and end with '/'. :return: ``Shared url`` or ``False`` if failed to share a file or directory through url """ prop = self.getProperty(... |
def createFileLink(self, resourceno): """Make a link of file If you don't know ``resourceno``, you'd better use ``getFileLink``. :param resourceno: Resource number of a file to create link :return: ``Shared url`` or ``False`` when failed to share a file """ data = {'_callback': 'window.__jindo_callback._8920', 'resourc... |
def getProperty(self, full_path, dummy = 56184): """Get a file property :param full_path: The full path to get the file or directory property. :return: ``metadata`` if success or ``False`` if failed to get property :metadata: - creationdate - exif - filelink - filelinkurl - filetype => 1: document, 2: image, 3: video, ... |
def getVersionList(self, full_path, startnum = 0, pagingrow = 50, dummy = 54213): """Get a version list of a file or dierectory. :param full_path: The full path to get the file or directory property. Path should start with '/' :param startnum: Start version index. :param pagingrow: Max # of version list in one page. :r... |
def setProperty(self, full_path, protect, dummy = 7046): """Set property of a file. :param full_path: The full path to get the file or directory property. :param protect: 'Y' or 'N', 중요 표시 :return: ``True`` when success to set property or ``False`` """ data = {'orgresource': full_path, 'protect': protect, 'userid': sel... |
def getMusicAlbumList(self, tagtype = 0, startnum = 0, pagingrow = 100, dummy = 51467): """Get music album list. :param tagtype: ? :return: ``metadata`` or ``False`` :metadata: - u'album':u'Greatest Hits Coldplay', - u'artist':u'Coldplay', - u'href':u'/Coldplay - Clocks.mp3', - u'musiccount':1, - u'resourceno':12459548... |
def doSearch(self, filename, filetype = None, type = 3, full_path = '/', sharedowner = 'A', datatype = 'all', sort = 'update', order = 'desc', searchtype = 'filesearch', startnum = 0, pagingrow = 100, includeworks = 'N', bodysearch = 'N', dummy = 36644): """Get music album list. There are 4 kinds in ``type``: - 1 : onl... |
full_path: Directory path to search recursively. :param sharedowner: File priority to search. (P: priority files only, A: all files.) :param datatype: Data type of a file to search :param sort: Order criteria of search result. ('update', 'date' ...) :param order: Order of files. ('desc' or 'inc') :param searchtype: ???... |
""" data = {'filename': filename, 'filetype': filetype, 'dstresource': full_path, 'sharedowner': sharedowner, 'datatype': datatype, 'sort': sort, 'order': order, 'searchtype': searchtype, 'startnum': startnum, 'pagingrow': pagingrow, 'includeworks': includeworks, 'bodysearch': bodysearch, 'userid': self.user_id, 'useri... |
def _choose_read_fs(authority, cache, read_path, version_check, hasher): ''' Context manager returning the appropriate up-to-date readable filesystem Use ``cache`` if it is a valid filessystem and has a file at ``read_path``, otherwise use ``authority``. If the file at ``read_path`` is out of date, update the file in `... |
def _get_write_fs(): ''' Context manager returning a writable filesystem Use a temporary directory and clean on exit. .. todo:: Evaluate options for using a cached memoryFS or streaming object instead of an OSFS(tmp). This could offer significant performance improvements. Writing to the cache is less of a problem since... |
def _prepare_write_fs(read_fs, cache, read_path, readwrite_mode=True): ''' Prepare a temporary filesystem for writing to read_path The file will be moved to write_path on close if modified. ''' with _get_write_fs() as write_fs: # If opening in read/write or append mode, make sure file data is # accessible if readwrite_... |
def get_local_path( authority, cache, update, version_check, hasher, read_path, write_path=None, cache_on_write=False): ''' Context manager for retrieving a system path for I/O and updating on change Parameters ---------- authority : object :py:mod:`pyFilesystem` filesystem object to use as the authoritative, up-to-dat... |
) ): _makedirs(cache.fs, fs.path.dirname(write_path)) fs.utils.copyfile( write_fs, read_path, cache.fs, write_path) _makedirs(authority.fs, fs.path.dirname(write_path)) fs.utils.copyfile( cache.fs, write_path, authority.fs, write_path) else: _makedirs(authority.fs, fs.path.dirname(write_path)) fs.utils.copyfile( write_... |
def make_view(robot): """ 为一个 BaseRoBot 生成 Django view。 :param robot: 一个 BaseRoBot 实例。 :return: 一个标准的 Django view """ assert isinstance(robot, BaseRoBot),\ "RoBot should be an BaseRoBot instance." @csrf_exempt def werobot_view(request): timestamp = request.GET.get("timestamp", "") nonce = request.GET.get("nonce", "") s... |
def text_cleanup(data, key, last_type): """ I strip extra whitespace off multi-line strings if they are ready to be stripped!""" if key in data and last_type == STRING_TYPE: data[key] = data[key].strip() return data |
def rst_to_json(text): """ I convert Restructured Text with field lists into Dictionaries! TODO: Convert to text node approach. """ records = [] last_type = None key = None data = {} directive = False lines = text.splitlines() for index, line in enumerate(lines): # check for directives if len(line) and line.strip().sta... |
False continue # Work on multi-line strings if len(line) and line[0].startswith(" ") and directive == False: if not isinstance(data[key], str): # Not a string so continue on continue value = line.strip() if not len(value): # empty string, continue on continue # add next line data[key] += "\n{}".format(value) continue i... |
def type_converter(text): """ I convert strings into integers, floats, and strings! """ if text.isdigit(): return int(text), int try: return float(text), float except ValueError: return text, STRING_TYPE |
def command_line_runner(): """ I run functions from the command-line! """ filename = sys.argv[-1] if not filename.endswith(".rst"): print("ERROR! Please enter a ReStructuredText filename!") sys.exit() print(rst_to_json(file_opener(filename))) |
def packb(obj, **kwargs): """wrap msgpack.packb, setting use_bin_type=True by default""" kwargs.setdefault('use_bin_type', True) return msgpack.packb(obj, **kwargs) |
def play(cls, file_path, on_done=None, logger=None): """ Play an audio file. :param file_path: the path to the file to play. :param on_done: callback when audio playback completes. """ pygame.mixer.init() try: pygame.mixer.music.load(file_path) except pygame.error as e: if logger is not None: logger.warning(str(e)) ret... |
def play_async(cls, file_path, on_done=None): """ Play an audio file asynchronously. :param file_path: the path to the file to play. :param on_done: callback when audio playback completes. """ thread = threading.Thread( target=AudioPlayer.play, args=(file_path, on_done,)) thread.start() |
def extract(self, disp): """ Extraction operation @param displacement vector in index space @return the part of the domain that is exposed by the shift """ res = copy.deepcopy(self) for i in range(self.ndims): d = disp[i] s = self.domain[i] if d > 0: res.domain[i] = slice(s.start, d) elif d < 0: res.domain[i] = slice(d... |
def home(self): """Return to initial position (row=0, column=0)""" self.row = 0 self.column = 0 self.command(Command.RETURN_HOME) msleep(2) |
def visible(self, status): """Turn the display on/off (quickly)""" self._display_control = ByteUtil.apply_flag(self._display_control, Command.DISPLAY_ON, status) self.command(self._display_control) |
def cursor(self, status): """Turn underline cursor visibility on/off""" self._display_control = ByteUtil.apply_flag(self._display_control, Command.CURSOR_ON, status) self.command(self._display_control) |
def blink(self, status): """Turn blink cursor visibility on/off""" self._display_control = ByteUtil.apply_flag(self._display_control, Command.BLINKING_ON, status) self.command(self._display_control) |
def left_to_right(self): """This is for text that flows Left to Right""" self._entry_mode |= Command.MODE_INCREMENT self.command(self._entry_mode) |
def right_to_left(self): """This is for text that flows Right to Left""" self._entry_mode &= ~Command.MODE_INCREMENT self.command(self._entry_mode) |
def get_available_name(self, name, max_length=None): """Return relative path to name placed in random directory""" tempdir = tempfile.mkdtemp(dir=self.base_location) name = os.path.join( os.path.basename(tempdir), os.path.basename(name), ) method = super(TempFileSystemStorage, self).get_available_name return method(nam... |
def menu(items, heading): '''Takes list of dictionaries and prints a menu. items parameter should be in the form of a list, containing dictionaries with the keys: {"key", "text", "function"}. Typing the key for a menuitem, followed by return, will run "function". ''' heading = "\n"*5 + heading # A little vertical paddi... |
def yn_prompt(text): ''' Takes the text prompt, and presents it, takes only "y" or "n" for answers, and returns True or False. Repeats itself on bad input. ''' text = "\n"+ text + "\n('y' or 'n'): " while True: answer = input(text).strip() if answer != 'y' and answer != 'n': continue elif answer == 'y': return True eli... |
def underline(text): '''Takes a string, and returns it underscored.''' text += "\n" for i in range(len(text)-1): text += "=" text += "\n" return text |
def get_event_time_as_utc(voevent, index=0): """ Extracts the event time from a given `WhereWhen.ObsDataLocation`. Returns a datetime (timezone-aware, UTC). Accesses a `WhereWhere.ObsDataLocation.ObservationLocation` element and returns the AstroCoords.Time.TimeInstant.ISOTime element, converted to a (UTC-timezoned) da... |
Index of the ObsDataLocation to extract an ISOtime from. Returns: :class:`datetime.datetime`: Datetime representing the event-timestamp, converted to UTC (timezone aware). """ try: od = voevent.WhereWhen.ObsDataLocation[index] ol = od.ObservationLocation coord_sys = ol.AstroCoords.attrib['coord_system_id'] timesys_iden... |
def get_event_position(voevent, index=0): """Extracts the `AstroCoords` from a given `WhereWhen.ObsDataLocation`. Note that a packet may include multiple 'ObsDataLocation' entries under the 'WhereWhen' section, for example giving locations of an object moving over time. Most packets will have only one, however, so the ... |
def get_grouped_params(voevent): """ Fetch grouped Params from the `What` section of a voevent as an omdict. This fetches 'grouped' Params, i.e. those enclosed in a Group element, and returns them as a nested dict-like structure, keyed by GroupName->ParamName->AttribName. Note that since multiple Params may share the s... |
def get_toplevel_params(voevent): """ Fetch ungrouped Params from the `What` section of a voevent as an omdict. This fetches 'toplevel' Params, i.e. those not enclosed in a Group element, and returns them as a nested dict-like structure, keyed like ParamName->AttribName. Note that since multiple Params may share the sa... |
""" result = OrderedDict() w = deepcopy(voevent.What) lxml.objectify.deannotate(w) return _get_param_children_as_omdict(w) |
def pull_astro_coords(voevent, index=0): """ Deprecated alias of :func:`.get_event_position` """ import warnings warnings.warn( """ The function `pull_astro_coords` has been renamed to `get_event_position`. This alias is preserved for backwards compatibility, and may be removed in a future release. """, FutureWarning) ... |
def pull_isotime(voevent, index=0): """ Deprecated alias of :func:`.get_event_time_as_utc` """ import warnings warnings.warn( """ The function `pull_isotime` has been renamed to `get_event_time_as_utc`. This alias is preserved for backwards compatibility, and may be removed in a future release. """, FutureWarning) retu... |
def pull_params(voevent): """ Attempts to load the `What` section of a voevent as a nested dictionary. .. warning:: Deprecated due to `Missing name attributes` issues. `Param` or `Group` entries which are missing the `name` attribute will be entered under a dictionary key of ``None``. This means that if there are multi... |
for ungrouped Params you'll need something like:: what_dict[None]['ParamName']['value'] """ import warnings warnings.warn( """ The function `pull_params` has been deprecated in favour of the split functions `get_toplevel_params` and `get_grouped_params`, due to possible name-shadowing issues when combining multilevel-n... |
def prettystr(subtree): """Print an element tree with nice indentation. Prettyprinting a whole VOEvent often doesn't seem to work, probably for issues relating to whitespace cf. http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output This function is a quick workaround for prettyprinting a su... |
async def request(self, method, path, json=None): """Make a request to the API.""" url = 'https://{}:{}/api/'.format(self.host, self.port) url += path.format(site=self.site) try: async with self.session.request(method, url, json=json) as res: if res.content_type != 'application/json': raise ResponseError( 'Invalid cont... |
def start(self): """ Start the MQTT client. """ self.thread_handler.run(target=self.start_blocking) self.thread_handler.start_run_loop() |
def start_blocking(self, run_event): """ Start the MQTT client, as a blocking method. :param run_event: a run event object provided by the thread handler. """ topics = [("hermes/intent/#", 0), ("hermes/hotword/#", 0), ("hermes/asr/#", 0), ("hermes/nlu/#", 0), ("snipsmanager/#", 0)] self.log_info("Connecting to {} on po... |
def on_connect(self, client, userdata, flags, result_code): """ Callback when the MQTT client is connected. :param client: the client being connected. :param userdata: unused. :param flags: unused. :param result_code: result code. """ self.log_info("Connected with result code {}".format(result_code)) self.state_handler... |
def on_disconnect(self, client, userdata, result_code): """ Callback when the MQTT client is disconnected. In this case, the server waits five seconds before trying to reconnected. :param client: the client being disconnected. :param userdata: unused. :param result_code: result code. """ self.log_info("Disconnected wit... |
def on_message(self, client, userdata, msg): """ Callback when the MQTT client received a new message. :param client: the MQTT client. :param userdata: unused. :param msg: the MQTT message. """ if msg is None: return self.log_info("New message on topic {}".format(msg.topic)) self.log_debug("Payload {}".format(msg.paylo... |
msg.topic == MQTT_TOPIC_ASR + "startListening": self.state_handler.set_state(State.asr_start_listening) elif msg.topic == MQTT_TOPIC_ASR + "textCaptured": self.state_handler.set_state(State.asr_text_captured) if msg.payload is not None: self.log_debug("Text captured: {}".format(str(msg.payload))) if self.handle_done_li... |
def list(self, identity_id, per_page=20, page=1): """ Get a list of tokens :param identity_id: The ID of the identity to retrieve tokens for :param per_page: The number of results per page returned :param page: The page number of the results :return: dict of REST API output with headers attached :rtype: :class:`~datasi... |
def create(self, identity_id, service, token): """ Create the token :param identity_id: The ID of the identity to retrieve :param service: The service that the token is linked to :param token: The token provided by the the service :param expires_at: Set an expiry for this token :return: dict of REST API output with hea... |
def update(self, identity_id, service, token=None): """ Update the token :param identity_id: The ID of the identity to retrieve :return: dict of REST API output with headers attached :rtype: :class:`~datasift.request.DictResponse` :raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.... |
def _func_router(self, msg, fname, **config): """ This method routes the messages based on the params and calls the appropriate method to process the message. The utility of the method is to cope up with the major message change during different releases. """ FNAME = 'handle_%s_autocloud_%s' if ('compose_id' in msg['ms... |
def get_sesames(email, password, device_ids=None, nicknames=None, timeout=5): """Return list of available Sesame objects.""" sesames = [] account = CandyHouseAccount(email, password, timeout=timeout) for sesame in account.sesames: if device_ids is not None and sesame['device_id'] not in device_ids: continue if nickname... |
def pulse(self): """ Calls when_rotated callback if detected changes """ new_b_value = self.gpio_b.is_active new_a_value = self.gpio_a.is_active value = self.table_values.value(new_b_value, new_a_value, self.old_b_value, self.old_a_value) self.old_b_value = new_b_value self.old_a_value = new_a_value if value != 0: self... |
def default_versions(self, default_versions): ''' Set archive default read versions Parameters ---------- default_versions: dict Dictionary of archive_name, version pairs. On read/download, archives in this dictionary will download the specified version by default. Before assignment, archive_names are checked and norma... |
def create( self, archive_name, authority_name=None, versioned=True, raise_on_err=True, metadata=None, tags=None, helper=False): ''' Create a DataFS archive Parameters ---------- archive_name: str Name of the archive authority_name: str Name of the data service to use as the archive's data authority versioned: bool If ... |
def get_archive(self, archive_name, default_version=None): ''' Retrieve a data archive Parameters ---------- archive_name: str Name of the archive to retrieve default_version: version str or :py:class:`~distutils.StrictVersion` giving the default version number to be used on read operations Returns ------- archive: obj... |
def batch_get_archive(self, archive_names, default_versions=None): ''' Batch version of :py:meth:`~DataAPI.get_archive` Parameters ---------- archive_names: list Iterable of archive names to retrieve default_versions: str, object, or dict Default versions to assign to each returned archive. May be a dict with archive n... |
{} for res in responses: res['archive_name'] = self._normalize_archive_name( res['archive_name']) archive_name = res['archive_name'] if hasattr(default_versions, 'get'): # Get version number from default_versions or # self._default_versions if key not present. default_version = default_versions.get( archive_name, self.... |
def listdir(self, location, authority_name=None): ''' List archive path components at a given location .. Note :: When using listdir on versioned archives, listdir will provide the version numbers when a full archive path is supplied as the location argument. This is because DataFS stores the archive path as a director... |
is attached or if :py:attr:`DefaultAuthorityName` is assigned). Returns ------- list Archive path components that exist at the given "directory" location on the specified authority Raises ------ ValueError A ValueError is raised if the authority is ambiguous or invalid ''' authority_name, location = self._normalize_arc... |
def search(self, *query, **kwargs): ''' Searches based on tags specified by users Parameters --------- query: str tags to search on. If multiple terms, provided in comma delimited string format prefix: str start of archive name. Providing a start string improves search speed. ''' prefix = kwargs.get('prefix') if prefix... |
def _validate_archive_name(self, archive_name): ''' Utility function for creating and validating archive names Parameters ---------- archive_name: str Name of the archive from which to create a service path Returns ------- archive_path: str Internal path used by services to reference archive data ''' archive_name = fs.... |
def hash_file(f): ''' Utility function for hashing file contents Overload this function to change the file equality checking algorithm Parameters ---------- f: file-like File-like object or file path from which to compute checksum value Returns ------- checksum: dict dictionary with {'algorithm': 'md5', 'checksum': hex... |
def html_list(data): """Convert dict into formatted HTML.""" if data is None: return None as_li = lambda v: "<li>%s</li>" % v items = [as_li(v) for v in data] return mark_safe("<ul>%s</ul>" % ''.join(items)) |
def check_pypi(modeladmin, request, queryset): """Update latest package info from PyPI.""" for p in queryset: if p.is_editable: logger.debug("Ignoring version update '%s' is editable", p.package_name) else: p.update_from_pypi() |
def queryset(self, request, queryset): """Filter based on whether an update (of any sort) is available.""" if self.value() == '-1': return queryset.filter(latest_version__isnull=True) elif self.value() == '0': return ( queryset .filter( current_version__isnull=False, latest_version__isnull=False, latest_version=F('curr... |
def _updateable(self, obj): """Return True if there are available updates.""" if obj.latest_version is None or obj.is_editable: return None else: return obj.latest_version != obj.current_version |
def available_updates(self, obj): """Print out all versions ahead of the current one.""" from package_monitor import pypi package = pypi.Package(obj.package_name) versions = package.all_versions() return html_list([v for v in versions if v > obj.current_version]) |
def get_agent(msg): """ Handy hack to handle legacy messages where 'agent' was a list. """ agent = msg['msg']['agent'] if isinstance(agent, list): agent = agent[0] return agent |
def run_suite(case, config, summary): """ Run the full suite of verification tests """ config["name"] = case model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case) bench_dir = os.path.join(livvkit.bench_dir, config['data_dir'], case) tabs = [] case_summary = LIVVDict() model_cases = functions.collect_cas... |
def _analyze_case(model_dir, bench_dir, config): """ Runs all of the verification checks on a particular case """ bundle = livvkit.verification_model_module model_out = functions.find_file(model_dir, "*"+config["output_ext"]) bench_out = functions.find_file(bench_dir, "*"+config["output_ext"]) model_config = functions.... |
def _print_summary(case, summary): """ Show some statistics from the run """ for dof, data in summary.items(): b4b = data["Bit for Bit"] conf = data["Configurations"] stdout = data["Std. Out Files"] print(" " + case + " " + str(dof)) print(" --------------------") print(" Bit for bit matches : " + str(b4b[0]) + " of " ... |
def _summarize_result(result, summary): """ Trim out some data to return for the index page """ if "Bit for Bit" not in summary: summary["Bit for Bit"] = [0, 0] if "Configurations" not in summary: summary["Configurations"] = [0, 0] if "Std. Out Files" not in summary: summary["Std. Out Files"] = 0 # Get the number of bi... |
= None total_count = 0 failure_count = 0 for elem in result: if elem["Title"] == "Configuration Comparison" and elem["Type"] == "Diff": elem_data = elem["Data"] summary_data = summary["Configurations"] total_count += 1 failed = False for section_name, varlist in elem_data.items(): for var, val in varlist.items(): if no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.