code
stringlengths
1
18.2k
def notify_task(self, task_id, **kwargs): """ Notify PNC about a BPM task event. Accepts polymorphic JSON {\"eventType\": \"string\"} based on \"eventType\" field. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiv...
def start_r_creation_task_with_single_url(self, body, **kwargs): """ Start Repository Creation task with url autodetect (internal vs. external). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >...
def copy_file_or_flo(input_, output, buffer_size=64 * 1024, cb=None): """ Copy a file name or file-like-object to another file name or file-like object""" assert bool(input_) assert bool(output) input_opened = False output_opened = False try: if isinstance(input_, string_types): if not os.path.isdir(os.path.dirname(inp...
def configure(self, config=None, **kwargs): """ We expect all of our config (apart from the ENGINE) to be in a dictionary called 'config' in our INSTALLED_BACKENDS entry """ self.config = config or {} for key in ['messaging_token', 'number']: if key not in self.config: msg = "Tropo backend config must set '%s'; config ...
def execute_tropo_program(self, program): """ Ask Tropo to execute a program for us. We can't do this directly; we have to ask Tropo to call us back and then give Tropo the program in the response body to that request from Tropo. But we can pass data to Tropo and ask Tropo to pass it back to us when Tropo calls us back...
for the format we're using to call Tropo, pass it data, and ask them to call us back. :param program: A Tropo program, i.e. a dictionary with a 'tropo' key whose value is a list of dictionaries, each representing a Tropo command. """ # The signer will also "pickle" the data structure for us signed_program = signing.dum...
(or Tropo) are down: response.raise_for_status() result = json.loads(response.content) if not result['success']: raise Exception("Tropo error: %s" % result.get('error', 'unknown'))
def send(self, id_, text, identities, context=None): """ Send messages when using RapidSMS 0.14.0 or later. We can send multiple messages in one Tropo program, so we do that. :param id_: Unused, included for compatibility with RapidSMS. :param string text: The message text to send. :param identities: A list of identiti...
have to send each one as a separate `message` command. commands.append( { 'message': { 'say': {'value': text}, 'to': identity, 'from': from_, 'channel': 'TEXT', 'network': 'SMS' } } ) program = { 'tropo': commands, } self.execute_tropo_program(program)
def dotted(self): """Return just the tract number, excluding the state and county, in the dotted format""" v = str(self.geoid.tract).zfill(6) return v[0:4] + '.' + v[4:]
def subclass(cls, vt_code, vt_args): """Return a dynamic subclass that has the extra parameters built in""" from geoid import get_class import geoid.census parser = get_class(geoid.census, vt_args.strip('/')).parse cls = type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_code, 'parser': parser}) globals()[cls.__nam...
def _open(self, path, skip_to_end = True, offset = None): """Open `path`, optionally seeking to the end if `skip_to_end` is True.""" fh = os.fdopen(os.open(path, os.O_RDONLY | os.O_NONBLOCK)) # If the file is being opened for the first time, jump to the end. # Otherwise, it is being reopened after a rotation, and we wa...
def _read(self, limit = None): """Checks the file for new data and refills the buffer if it finds any.""" # The code that used to be here was self._fh.read(limit) # However, this broke on OSX. os.read, however, works fine, but doesn't # take the None argument or have any way to specify "read to the end". # This emulate...
def hasBeenRotated(self): """Returns a boolean indicating whether the file has been removed and recreated during the time it has been open.""" try: # If the inodes don't match, it means the file has been replaced. # The inode number cannot be recycled as long as we hold the # filehandle open, so this test can be truste...
def reopen(self): """Reopens the file. Usually used after it has been rotated.""" # Read any remaining content in the file and store it in a buffer. self._read() # Close it to ensure we don't leak file descriptors self._close() # Reopen the file. try: self._open(self._path, skip_to_end = False) return True except OSErr...
def readlines(self): """A generator producing lines from the file.""" # If the file is not open, there's nothing to return if not self._fh: raise StopIteration at_eof = False while True: # Clean the buffer sometimes. if self._bufoffset > (self._maxreadsize / 2): self._buf = self._buf[self._bufoffset:] self._bufoffset =...
except ValueError: # Reached the end of the buffer without finding any newlines. if not at_eof: # Line is longer than the half the buffer size? - Nope logger.warning("Skipping over longline at %s:%d", self._path, self._offset) self._bufoffset = len(self._buf) - 1 self._longline = True raise StopIteration
def _rescan(self, skip_to_end = True): """Check for new files, deleted files, and rotated files.""" # Get listing of matching files. paths = [] for single_glob in self._globspec: paths.extend(glob.glob(single_glob)) # Remove files that don't appear in the new list. for path in self._tailedfiles.keys(): if path not in p...
def poll(self, force_rescan = False): """A generator producing (path, line) tuples with lines seen since the last time poll() was called. Will not block. Checks for new/deleted/rotated files every `interval` seconds, but will check every time if `force_rescan` is True. (default False)""" # Check for new, deleted, and r...
path in filereaders.keys(): lines = filereaders[path] try: line, offset = lines.next() except StopIteration: # Reached end the of this file. del filereaders[path] break yield (path, offset), line
def offsets(self): """A generator producing a (path, offset) tuple for all tailed files.""" for path, tailedfile in self._tailedfiles.iteritems(): yield path, tailedfile._offset
def connectTo(self, remoteRouteName): """ Set the name of the route which will be added to outgoing boxes. """ self.remoteRouteName = remoteRouteName # This route must not be started before its router is started. If # sender is None, then the router is not started. When the router is # started, it will start this route...
def sendBox(self, box): """ Add the route and send the box. """ if self.remoteRouteName is _unspecified: raise RouteNotConnected() if self.remoteRouteName is not None: box[_ROUTE] = self.remoteRouteName.encode('ascii') self.router._sender.sendBox(box)
def bindRoute(self, receiver, routeName=_unspecified): """ Create a new route to associate the given route name with the given receiver. @type routeName: C{unicode} or L{NoneType} @param routeName: The identifier for the newly created route. If C{None}, boxes with no route in them will be delivered to this receiver. @r...
def startReceivingBoxes(self, sender): """ Initialize route tracking objects. """ self._sender = sender for routeName, route in self._unstarted.iteritems(): # Any route which has been bound but which does not yet have a # remote route name should not yet be started. These will be # started in Route.connectTo. if route....
def ampBoxReceived(self, box): """ Dispatch the given box to the L{IBoxReceiver} associated with the route indicated by the box, or handle it directly if there is no route. """ route = box.pop(_ROUTE, None) self._routes[route].receiver.ampBoxReceived(box)
def stopReceivingBoxes(self, reason): """ Stop all the L{IBoxReceiver}s which have been added to this router. """ for routeName, route in self._routes.iteritems(): route.stop(reason) self._routes = None
def _s3bukt(self): """ Overrides the original _s3bukt method to get the bucket without vlaidation when the return to the original validation is not a 404. :return: """ from boto.exception import S3ResponseError import time try: (b, ctime) = self._tlocal.s3bukt if time.time() - ctime > 60: raise AttributeError return b ...
def push_build(id, tag_prefix): """ Push build to Brew """ req = swagger_client.BuildRecordPushRequestRest() req.tag_prefix = tag_prefix req.build_record_id = id response = utils.checked_api_call(pnc_api.build_push, 'push', body=req) if response: return utils.format_json_list(response)
def push_build_set(id, tag_prefix): """ Push build set to Brew """ req = swagger_client.BuildConfigSetRecordPushRequestRest() req.tag_prefix = tag_prefix req.build_config_set_record_id = id response = utils.checked_api_call(pnc_api.build_push, 'push_record_set', body=req) if response: return utils.format_json_list(resp...
def push_build_status(id): """ Get status of Brew push. """ response = utils.checked_api_call(pnc_api.build_push, 'status', build_record_id=id) if response: return utils.format_json(response)
def create_transient(self, input_stream, original_name, length=None): '''Create TransientFile and file on FS from given input stream and original file name.''' ext = os.path.splitext(original_name)[1] transient = self.new_transient(ext) if not os.path.isdir(self.transient_root): os.makedirs(self.transient_root) self._c...
def new_transient(self, ext=''): '''Creates empty TransientFile with random name and given extension. File on FS is not created''' name = random_name(self.transient_length) + ext return TransientFile(self.transient_root, name, self)
def get_transient(self, name): '''Restores TransientFile object with given name. Should be used when form is submitted with file name and no file''' # security checks: basically no folders are allowed assert not ('/' in name or '\\' in name or name[0] in '.~') transient = TransientFile(self.transient_root, name, self) ...
def store(self, transient_file, persistent_file): '''Makes PersistentFile from TransientFile''' #for i in range(5): # persistent_file = PersistentFile(self.persistent_root, # persistent_name, self) # if not os.path.exists(persistent_file.path): # break #else: # raise Exception('Unable to find free file name') dirname =...
def _sign_payload(self, payload): """使用 appkey 对 payload 进行签名,返回新的请求参数 """ app_key = self._app_key t = int(time.time() * 1000) requestStr = { 'header': self._req_header, 'model': payload } data = json.dumps({'requestStr': json.dumps(requestStr)}) data_str = '{}&{}&{}&{}'.format(self._req_token, t, app_key, data) sign =...
def request(self, action, payload, timeout=3): """ 虾米 API 请求流程: 1. 获取一个 token:随便访问一个网页,服务端会 set cookie。 根据观察,这个 token 一般是 7 天过期 2. 对请求签名:见 _sign_payload 方法 3. 发送请求 """ if self._req_token is None: # 获取 token self._fetch_token() url = _gen_url(action) params = self._sign_payload(payload) response = self.http.get(url, par...
def login(self, email, password): """ :password: user password md5 digest """ payload = { 'account': email, 'password': password } code, msg, rv = self.request( 'mtop.alimusic.xuser.facade.xiamiuserservice.login', payload ) if code == 'SUCCESS': # TODO: 保存 refreshToken 和过期时间等更多信息 # 根据目前观察,token 过期时间有三年 accessToken = rv...
def playlist_detail(self, playlist_id): """获取歌单详情 如果歌单歌曲数超过 100 时,该接口的 songs 字段不会包含所有歌曲, 但是它有个 allSongs 字段,会包含所有歌曲的 ID。 """ action = 'mtop.alimusic.music.list.collectservice.getcollectdetail' payload = {'listId': playlist_id} code, msg, rv = self.request(action, payload) return rv['data']['data']['collectDetail']
def user_playlists(self, user_id, page=1, limit=30): """ NOTE: 用户歌单有可能是仅自己可见 """ action = 'mtop.alimusic.music.list.collectservice.getcollectbyuser' payload = { 'userId': user_id, 'pagingVO': { 'page': page, 'pageSize': limit } } code, msg, rv = self.request(action, payload) # TODO: 支持获取更多 return rv['data']['data']['co...
def update_favorite_song(self, song_id, op): """ :param str op: `add` or `del` """ op = 'un' if op == 'del' else '' action = 'mtop.alimusic.fav.songfavoriteservice.{}favoritesong'.format(op) payload = { 'songId': song_id } code, msg, rv = self.request(action, payload) return rv['data']['data']['status'] == 'true'
def update_playlist_song(self, playlist_id, song_id, op): """从播放列表删除或者增加一首歌曲 如果歌曲不存在与歌单中,删除时返回 True;如果歌曲已经存在于 歌单,添加时也返回 True。 """ action = 'mtop.alimusic.music.list.collectservice.{}songs'.format( 'delete' if op == 'del' else 'add') payload = { 'listId': playlist_id, 'songIds': [song_id] } code, msg, rv = self.request(...
def add_dependency(self, id, **kwargs): """ Adds a dependency to the specified config This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>...
def add_product_version(self, id, **kwargs): """ Associates a product version to the specified config This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ppr...
def clone(self, id, **kwargs): """ Clones an existing Build Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread...
def get_all_by_product_id(self, product_id, **kwargs): """ Gets all Build Configurations of a Product This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ppr...
def get_all_by_project_id(self, project_id, **kwargs): """ Gets all Build Configurations of a Project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ppr...
def get_builds(self, id, **kwargs): """ Get all BuildRecords (running and archived) associated with this Build Configuration, returns empty list if no build records are found This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked ...
def get_dependencies(self, id, **kwargs): """ Get the direct dependencies of the specified configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
def get_product_versions(self, id, **kwargs): """ Get associated Product Versions of the specified Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respons...
def get_revision(self, id, rev, **kwargs): """ Get specific audited revision of this build configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
def get_revisions(self, id, **kwargs): """ Gets audited revisions of this build configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(resp...
def get_supported_generic_parameters(self, **kwargs): """ Gets the minimal set of supported genericParameters and their description for the BuildConfiguration. There can be also other supported parameters not know by core. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, pl...
def remove_dependency(self, id, dependency_id, **kwargs): """ Removes a configuration from the specified config set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(resp...
def remove_product_version(self, id, product_version_id, **kwargs): """ Removes a product version from the specified config set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_f...
def trigger(self, id, **kwargs): """ Triggers a build of a specific Build Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) ...
Valid only for temporary builds. :param str rebuild_mode: Rebuild Modes: FORCE: always rebuild the configuration; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated; :return: BuildRecordSingleton If the metho...
def trigger_audited(self, id, rev, **kwargs): """ Triggers a build of a specific Build Configuration in a specific revision This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_funct...
if the build fails? :param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds. :param str rebuild_mode: Rebuild Modes: FORCE: always rebuild the configuration; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY...
def update_and_get_audited(self, id, **kwargs): """ Updates an existing Build Configuration and returns BuildConfigurationAudited entity This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def c...
def debug_break(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d = {'_frame': frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal recieved : entering p...
def trace(fn): # pragma: no cover """ Prints parameteters and return values of the each call of the wrapped function. Usage: decorate appropriate function or method: @trace def myf(): ... """ def wrapped(*args, **kwargs): msg = [] msg.append('Enter {}('.format(fn.__name__)) if args: msg.append(', '.join([str(x) for x i...
def patch_file_open(): # pragma: no cover """A Monkey patch to log opening and closing of files, which is useful for debugging file descriptor exhaustion.""" openfiles = set() oldfile = builtins.file class newfile(oldfile): def __init__(self, *args, **kwargs): self.x = args[0] all_fds = count_open_fds() print('### {} O...
def traceit(frame, event, arg): """ Trace every lie of a program. Use: import sys sys.settrace(traceit) :param frame: :param event: :param arg: :return: """ import linecache try: if event == "line": lineno = frame.f_lineno filename = frame.f_globals.get("__file__") if (filename.endswith(".pyc") or filename.endswith(".p...
def login(client, credentials): """ Authenticate using the given L{AMP} instance. The protocol must be connected to a server with responders for L{PasswordLogin} and L{PasswordChallengeResponse}. @param client: A connected L{AMP} instance which will be used to issue authentication commands. @param credentials: An objec...
def determineFrom(cls, challenge, password): """ Create a nonce and use it, along with the given challenge and password, to generate the parameters for a response. @return: A C{dict} suitable to be used as the keyword arguments when calling this command. """ nonce = secureRandom(16) response = _calcResponse(challenge, ...
def checkPassword(self, password): """ Check the given plaintext password against the response in this credentials object. @type password: C{str} @param password: The known correct password associated with C{self.username}. @return: A C{bool}, C{True} if this credentials object agrees with the given password, C{False} ...
def passwordLogin(self, username): """ Generate a new challenge for the given username. """ self.challenge = secureRandom(16) self.username = username return {'challenge': self.challenge}
def _login(self, credentials): """ Actually login to our portal with the given credentials. """ d = self.portal.login(credentials, None, IBoxReceiver) def cbLoggedIn((interface, avatar, logout)): self.logout = logout self.boxReceiver = avatar self.boxReceiver.startReceivingBoxes(self.boxSender) return {} d.addCallback(...
def passwordChallengeResponse(self, cnonce, response): """ Verify the response to a challenge. """ return self._login(_AMPUsernamePassword( self.username, self.challenge, cnonce, response))
def connectionLost(self, reason): """ If a login has happened, perform a logout. """ AMP.connectionLost(self, reason) if self.logout is not None: self.logout() self.boxReceiver = self.logout = None
def on_position_changed(self, position): """bind position changed signal with this""" if not self._lyric: return pos = find_previous(position*1000 + 300, self._pos_list) if pos is not None and pos != self._pos: self.current_sentence = self._pos_s_map[pos] self._pos = pos
def on_song_changed(self, song): """bind song changed signal with this""" if song is None or song.lyric is None: self._lyric = None self._pos_s_map = {} else: self._lyric = song.lyric.content self._pos_s_map = parse(self._lyric) self._pos_list = sorted(list(self._pos_s_map.keys())) self._pos = None self.current_sentenc...
def sanitizeStructTime(struct): """ Convert struct_time tuples with possibly invalid values to valid ones by substituting the closest valid value. """ maxValues = (9999, 12, 31, 23, 59, 59) minValues = (1, 1, 1, 0, 0, 0) newstruct = [] for value, maxValue, minValue in zip(struct[:6], maxValues, minValues): newstruct.ap...
def _timedeltaToSignHrMin(offset): """ Return a (sign, hour, minute) triple for the offset described by timedelta. sign is a string, either "+" or "-". In the case of 0 offset, sign is "+". """ minutes = round((offset.days * 3600000000 * 24 + offset.seconds * 1000000 + offset.microseconds) / 60000000.0) if minutes < 0:...
def fromHumanly(klass, humanStr, tzinfo=None, now=None): """Return a new Time instance from a string a human might type. @param humanStr: the string to be parsed. @param tzinfo: A tzinfo instance indicating the timezone to assume if none is specified in humanStr. If None, assume UTC. @param now: A Time instance to be c...
continue try: return creator(klass, match, tzinfo, now) except ValueError: continue raise ValueError, 'could not parse date: %r' % (humanStr,)
def fromISO8601TimeAndDate(klass, iso8601string, tzinfo=None): """Return a new Time instance from a string formated as in ISO 8601. If the given string contains no timezone, it is assumed to be in the timezone specified by the parameter `tzinfo`, or UTC if tzinfo is None. An input string with an explicit timezone will ...
tzhour = groups.pop('tzhour') tzmin = groups.pop('tzmin') if tzhour is not None: return FixedOffset(int(tzhour), int(tzmin or 0)) return tzinfo or FixedOffset(0, 0) def coerceGroups(): groups['month'] = groups['month1'] or groups['month2'] groups['week'] = groups['week1'] or groups['week2'] # don't include fractional s...
59), # Sometime in the 22nd century AD, two leap seconds will be # required every year. In the 25th century AD, four every # year. We'll ignore that for now though because it would be # tricky to get right and we certainly don't need it for our # target applications. In other words, post-singularity # Martian users, pl...
ValueError, '%s must be in %i..%i' % (group, min, max) def determineResolution(): if match.group('fractionalsec') is not None: return max(datetime.timedelta.resolution, datetime.timedelta( microseconds=1 * 10 ** -len( match.group('fractionalsec')) * 1000000)) for testGroup, resolution in [ ('second', datetime.timedelta...
(groups['week'],)) dtime = datetime.datetime( groups['year'], 1, 4, groups['hour'], groups['minute'], groups['second'], int(round(groups['fractionalsec'] * 1000000)), tzinfo=tzinfo ) dtime -= datetime.timedelta(days = dtime.weekday()) dtime += datetime.timedelta( days = (groups['week']-1) * 7 + groups['weekday'] - 1) i...
groups['second'], int(round(groups['fractionalsec'] * 1000000)), tzinfo=tzinfo ) match = klass.iso8601pattern.match(iso8601string) if match is None: raise ValueError( '%r could not be parsed as an ISO 8601 date and time' % (iso8601string,)) groups = match.groupdict() coerceGroups() if match.group('hour') is not None: t...
def fromStructTime(klass, structTime, tzinfo=None): """Return a new Time instance from a time.struct_time. If tzinfo is None, structTime is in UTC. Otherwise, tzinfo is a datetime.tzinfo instance coresponding to the timezone in which structTime is. Many of the functions in the standard time module return these things. ...
def fromDatetime(klass, dtime): """Return a new Time instance from a datetime.datetime instance. If the datetime instance does not have an associated timezone, it is assumed to be UTC. """ self = klass.__new__(klass) if dtime.tzinfo is not None: self._time = dtime.astimezone(FixedOffset(0, 0)).replace(tzinfo=None) else...
def fromPOSIXTimestamp(klass, secs): """Return a new Time instance from seconds since the POSIX epoch. The POSIX epoch is midnight Jan 1, 1970 UTC. According to POSIX, leap seconds don't exist, so one UTC day is exactly 86400 seconds, even if it wasn't. @param secs: a number of seconds, represented as an integer, long ...
def fromRFC2822(klass, rfc822string): """ Return a new Time instance from a string formated as described in RFC 2822. @type rfc822string: str @raise ValueError: if the timestamp is not formatted properly (or if certain obsoleted elements of the specification are used). @return: a new L{Time} """ # parsedate_tz is going...
// 60)) self.resolution = datetime.timedelta(seconds=1) return self
def asDatetime(self, tzinfo=None): """Return this time as an aware datetime.datetime instance. The returned datetime object has the specified tzinfo, or a tzinfo describing UTC if the tzinfo parameter is None. """ if tzinfo is None: tzinfo = FixedOffset(0, 0) if not self.isTimezoneDependent(): return self._time.replace...
def asRFC2822(self, tzinfo=None, includeDayOfWeek=True): """Return this Time formatted as specified in RFC 2822. RFC 2822 specifies the format of email messages. RFC 2822 says times in email addresses should reflect the local timezone. If tzinfo is a datetime.tzinfo instance, the returned formatted string will reflect ...
rfcoffset) return rfcstring
def asISO8601TimeAndDate(self, includeDelimiters=True, tzinfo=None, includeTimezone=True): """Return this time formatted as specified by ISO 8861. ISO 8601 allows optional dashes to delimit dates and colons to delimit times. The parameter includeDelimiters (default True) defines the inclusion of these delimiters in the...
% (timeSep,) else: sign, hour, min = _timedeltaToSignHrMin(dtime.utcoffset()) timezone = '%s%02i%s%02i' % (sign, hour, timeSep, min) else: timezone = '' microsecond = ('%06i' % (dtime.microsecond,)).rstrip('0') if microsecond: microsecond = '.' + microsecond parts = [ ('%04i' % (dtime.year,), datetime.timedelta(days=36...
def asStructTime(self, tzinfo=None): """Return this time represented as a time.struct_time. tzinfo is a datetime.tzinfo instance coresponding to the desired timezone of the output. If is is the default None, UTC is assumed. """ dtime = self.asDatetime(tzinfo) if tzinfo is None: return dtime.utctimetuple() else: return ...
def asHumanly(self, tzinfo=None, now=None, precision=Precision.MINUTES): """Return this time as a short string, tailored to the current time. Parts of the date that can be assumed are omitted. Consequently, the output string depends on the current time. This is the format used for displaying dates in most user visible ...
Time.Precision.MINUTES or Time.Precision.SECONDS') if now is None: now = Time().asDatetime(tzinfo) else: now = now.asDatetime(tzinfo) dtime = self.asDatetime(tzinfo) # Same day? if dtime.date() == now.date(): if self.isAllDay(): return 'all day' return dtime.strftime(timeFormat).lower() else: res = str(dtime.date().day...
def getBounds(self, tzinfo=None): """ Return a pair describing the bounds of self. This returns a pair (min, max) of Time instances. It is not quite the same as (self, self + self.resolution). This is because timezones are insignificant for instances with a resolution greater or equal to 1 day. To illustrate the proble...
UTC 05:00. The example instance T above is before this, but obviously it is today. The min and max times this returns are such that all potentially matching instances are within this range. However, this range might contain unmatching instances. As an example of this, if 'today' is April first 2005, then Time.fromISO86...
def oneDay(self): """Return a Time instance representing the day of the start of self. The returned new instance will be set to midnight of the day containing the first instant of self in the specified timezone, and have a resolution of datetime.timedelta(days=1). """ day = self.__class__.fromDatetime(self.asDatetime()...
def get_logger(name, file_name=None, stream=None, template=None, propagate=False, level=None): """Get a logger by name. """ logger = logging.getLogger(name) running_tests = ( 'test' in sys.argv # running with setup.py or sys.argv[0].endswith('py.test')) # running with py.test if running_tests and not level: # testing w...