code stringlengths 1 18.2k |
|---|
decoded using provided schema name, # of course a decoding breakpoint graph object shall be aware of such scheme # (it has to be specified in the `edges_json_schemas` class wide dict) # ############################################################################################################ schema_name = edge_dict.g... |
g_id in edge.multicolor]) except KeyError: raise ValueError( "Error during breakpoint graph deserialization. Deserialized edge reference non-present " "genome in its multicolor") result.__add_bgedge(edge, merge=merge) return result |
def get(request, obj_id=None): """Lists all tags :returns: json """ res = Result() if obj_id: if obj_id == '0': obj = { 'id': 0, 'name': 'TAGLESS', 'artist': False, } else: obj = get_object_or_404(Tag, pk=obj_id).json() res.append(obj) return JsonResponse(res.asDict()) else: if request.GET.get('count'): itags = Tag.obj... |
def post(request): """Creates a tag object :param name: Name for tag :type name: str :returns: json """ res = Result() data = request.POST or json.loads(request.body)['body'] name = data.get('name', None) if not name: res.isError = True res.message = "No name given" return JsonResponse(res.asDict()) tag = Tag.objects.g... |
def put(request, obj_id=None): """Adds tags from objects resolved from guids :param tags: Tags to add :type tags: list :param guids: Guids to add tags from :type guids: list :returns: json """ res = Result() data = request.PUT or json.loads(request.body)['body'] if obj_id: # -- Edit the tag tag = Tag.objects.get(pk=obj... |
def delete(request, obj_id=None): """Removes tags from objects resolved from guids :param tags: Tags to remove :type tags: list :param guids: Guids to remove tags from :type guids: list :returns: json """ res = Result() if obj_id: # -- Delete the tag itself tag = Tag.objects.get(pk=obj_id) guids = [] images = Image.obj... |
def search(request): """ Search for Tag objects and returns a Result object with a list of searialize Tag objects. :param search: Append a "Search for" tag :type search: bool :param zero: Exclude Tags with no items :type zero: bool :param artist: Exclude artist tags :type artist: bool :returns: json """ q = request.GET... |
def merge(request, obj_id): """Merges multiple tags into a single tag and all related objects are reassigned""" res = Result() if request.POST: tags = json.loads(request.POST['tags']) else: tags = json.loads(request.body)['body']['tags'] guids = [] images = Image.objects.filter(tags__id__in=tags) guids += [_.guid for _... |
def _manageTags(tagList, guids, add=True): """ Adds or Removes Guids from Tags """ objects = getObjectsFromGuids(guids) tags = [] for tag in tagList: try: t = Tag.objects.get(pk=int(tag)) except ValueError: t = Tag.objects.get_or_create(name=tag.lower())[0] tags.append(t) if add: return _addTags(tags, objects) else: re... |
def _addTags(tags, objects): """ Adds tags to objects """ for t in tags: for o in objects: o.tags.add(t) return True |
def _removeTags(tags, objects): """ Removes tags from objects """ for t in tags: for o in objects: o.tags.remove(t) return True |
def parse(self, xsl='text'): """ TODO: add double-quoted string literals that allows for escaped double quotes https://gist.github.com/prathe/2439752 or http://www.metaltoad.com/blog/regex-quoted-string-escapable-quotes """ try: cmd_text, option_text = xsl.split(None, 1) except ValueError: cmd_text = xsl option_text = ... |
text.lower().split(';'))): if mc in META_COMMANDS: # store in stack order self.meta_commands = [mc] + self.meta_commands else: raise ParseError("unknown meta command %s" % self.text) else: self.text = text |
def p0(self, e): """Returns top level w:p node""" body = self.body(e) p = self.p(e) if body == p.getparent(): return p else: raise ElementNotFound("could not find top level w:p element in %s" % e) |
def _short_ts_regexp(): '''Generates regexp for parsing of shortened relative timestamps, as shown in the table.''' ts_re = ['^'] for k in it.chain(_short_ts_days, _short_ts_s): ts_re.append(r'(?P<{0}>\d+{0}\s*)?'.format(k)) return re.compile(''.join(ts_re), re.I | re.U) |
def parse_timestamp(ts_str): '''Match time either in human-readable format (as accepted by dateutil), or same time-offset format, as used in the table (e.g. "NdMh ago", or just "NdMh").''' assert isinstance(ts_str, bytes), [type(ts_str), repr(ts_str)] ts_str = ts_str.replace('_', ' ') # Try to parse time offset in shor... |
= 'y' if not match.group('Y') else 'Y' tpl, ts_str = '%{}-%m-%d'.format(tpl), match.group('date') if match.group('time'): tpl_time = ['%H', '%M', '%S'] ts_str_time = match.group('time').split(':') ts_str += ' ' + ':'.join(ts_str_time) tpl += ' ' + ':'.join(tpl_time[:len(ts_str_time)]) try: ts = timezone.make_aware(date... |
def _get(self, timeout): """ Get a resource from the pool. If timeout is ``None`` waits indefinitely. :param timeout: Time in seconds to wait for a resource. :type timeout: int :return: A resource. :rtype: :class:`_ResourceTracker` :raises PoolEmptyError: When timeout has elapsed and unable to retrieve resource. """ wi... |
def _get_tracker(self, resource): """ Return the resource tracker that is tracking ``resource``. :param resource: A resource. :return: A resource tracker. :rtype: :class:`_ResourceTracker` """ with self._lock: for rt in self._reference_queue: if rt is not None and resource is rt.resource: return rt raise UnknownResourc... |
def _harvest_lost_resources(self): """Return lost resources to pool.""" with self._lock: for i in self._unavailable_range(): rtracker = self._reference_queue[i] if rtracker is not None and rtracker.available(): self.put_resource(rtracker.resource) |
def _make_resource(self): """ Returns a resource instance. """ with self._lock: for i in self._unavailable_range(): if self._reference_queue[i] is None: rtracker = _ResourceTracker( self._factory(**self._factory_arguments)) self._reference_queue[i] = rtracker self._size += 1 return rtracker raise PoolFullError |
def _put(self, rtracker): """ Put a resource back in the queue. :param rtracker: A resource. :type rtracker: :class:`_ResourceTracker` :raises PoolFullError: If pool is full. :raises UnknownResourceError: If resource can't be found. """ with self._lock: if self._available < self.capacity: for i in self._unavailable_ran... |
def _remove(self, rtracker): """ Remove a resource from the pool. :param rtracker: A resource. :type rtracker: :class:`_ResourceTracker` """ with self._lock: i = self._reference_queue.index(rtracker) self._reference_queue[i] = None self._size -= 1 |
def _unavailable_range(self): """ Return a generator for the indices of the unavailable region of ``_reference_queue``. """ with self._lock: i = self._resource_end j = self._resource_start if j < i or self.empty(): j += self.maxsize for k in range(i, j): yield k % self.maxsize |
def get_resource(self, resource_wrapper=None): """ Returns a ``Resource`` instance. :param resource_wrapper: A Resource subclass. :return: A ``Resource`` instance. :raises PoolEmptyError: If attempt to get resource fails or times out. """ rtracker = None if resource_wrapper is None: resource_wrapper = self._resource_wr... |
that will have this resource removed. This ensures there # will be space for _make_resource() to place a newly created # resource. with self._lock: self._remove(rtracker) rtracker = self._make_resource() # Ensure all resources leave pool with same attributes. # normalize_connection() is used since it calls # normalize_... |
def put_resource(self, resource): """ Adds a resource back to the pool or discards it if the pool is full. :param resource: A resource object. :raises UnknownResourceError: If resource was not made by the pool. """ rtracker = self._get_tracker(resource) try: self._put(rtracker) except PoolFullError: self._remove(rtrack... |
def wrap_resource(self, pool, resource_wrapper): """ Return a resource wrapped in ``resource_wrapper``. :param pool: A pool instance. :type pool: :class:`CuttlePool` :param resource_wrapper: A wrapper class for the resource. :type resource_wrapper: :class:`Resource` :return: A wrapped resource. :rtype: :class:`Resource... |
def close(self): """ Returns the resource to the resource pool. """ if self._resource is not None: self._pool.put_resource(self._resource) self._resource = None self._pool = None |
def send(self, message, fragment_size=None, mask=False): """ Send a message. If `fragment_size` is specified, the message is fragmented into multiple frames whose payload size does not extend `fragment_size`. """ for frame in self.message_to_frames(message, fragment_size, mask): self.send_frame(frame) |
def recv(self): """ Receive a message. A message may consist of multiple (ordered) data frames. A control frame may be delivered at any time, also when expecting the next continuation frame of a fragmented message. These control frames are handled immediately by handle_control_frame(). """ fragments = [] while not len(... |
def handle_control_frame(self, frame): """ Handle a control frame as defined by RFC 6455. """ if frame.opcode == OPCODE_CLOSE: self.close_frame_received = True code, reason = frame.unpack_close() if self.close_frame_sent: self.onclose(code, reason) self.sock.close() raise SocketClosed(True) else: self.close_params = (c... |
def receive_forever(self): """ Receive and handle messages in an endless loop. A message may consist of multiple data frames, but this is not visible for onmessage(). Control messages (or control frames) are handled automatically. """ while True: try: self.onmessage(self.recv()) except (KeyboardInterrupt, SystemExit, S... |
def send_ping(self, payload=''): """ Send a PING control frame with an optional payload. """ self.send_frame(ControlFrame(OPCODE_PING, payload), lambda: self.onping(payload)) self.ping_payload = payload self.ping_sent = True |
def close(self, code=None, reason=''): """ Close the socket by sending a CLOSE frame and waiting for a response close message, unless such a message has already been received earlier (prior to calling this function, for example). The onclose() handler is called after the response has been received, but before the socke... |
def get_by_string(cls, fields, query): '''Get object by numeric id or exact and unique part of specified attrs (name, title, etc).''' try: pk = int(query) except ValueError: pass else: return cls.objects.get(pk=pk) obj = list(cls.objects.filter(reduce( op.or_, list(Q(**{'{}__icontains'.format(f): query}) for f in field... |
def handler(self): 'Handler function' from feedjack import filters # shouldn't be imported globally, as they may depend on models proc_func = getattr(filters, self.handler_name or self.name, None) if proc_func is None: if '.' not in self.handler_name: raise ImportError('Processing function not available: {0}'.format(se... |
def handler(self): 'Parametrized handler function' return ft.partial(self.base.handler, parameter=self.parameter)\ if self.parameter else self.base.handler |
def calculate_check_interval( self, max_interval, ewma_factor, max_days=None, max_updates=None, ewma=0, ewma_ts=None, add_partial=None ): '''Calculate interval for checks as average time (ewma) between updates for specified period.''' if not add_partial: posts_base = self.posts.only('date_modified').order_by('date_modi... |
= ts, (ts - ewma_ts).total_seconds() ewma = ewma_factor * interval + (1 - ewma_factor) * ewma return min(timedelta(max_interval).total_seconds(), ewma) |
def update_handler(feeds): '''Update all cross-referencing filters results for feeds and others, related to them. Intended to be called from non-Feed update hooks (like new Post saving).''' # Check if this call is a result of actions initiated from # one of the hooks in a higher frame (resulting in recursion). if Feed.... |
def similar(self, threshold, **criterias): '''Find text-based field matches with similarity (1-levenshtein/length) higher than specified threshold (0 to 1, 1 being an exact match)''' # XXX: use F from https://docs.djangoproject.com/en/1.8/ref/models/expressions/ meta = self.model._meta funcs, params = list(), list() fo... |
fits, the comparison itself funcs.append('levenshtein({0}, %s) / CAST(length({0}) AS numeric) < %s'.format(name)) params.extend((val, val, float(1 - threshold))) return self.extra(where=funcs, params=params) |
def _filtering_result_checked(self, by_or): '''Check if post passes all / at_least_one (by_or parameter) filter(s). Filters are evaluated on only-if-necessary ("lazy") basis.''' filters, results = it.imap(set, ( self.feed.filters.all(), self.filtering_results.values_list('filter', flat=True) )) # Check if conclusion ca... |
them (perform actual filtering). # Note that independent filters applied first, since # crossrefs should be more resource-hungry in general. for filter_obj in sorted(filters.difference(results), key=op.attrgetter('base.crossref')): filter_op = FilterResult(filter=filter_obj, post=self, result=filter_obj.handler(self)) ... |
def connect(self): """Connect to the Redis server if necessary. :rtype: :class:`~tornado.concurrent.Future` :raises: :class:`~tredis.exceptions.ConnectError` :class:`~tredis.exceptinos.RedisError` """ future = concurrent.Future() if self.connected: raise exceptions.ConnectError('already connected') LOGGER.debug('%s con... |
def execute(self, command, future): """Execute a command after connecting if necessary. :param bytes command: command to execute after the connection is established :param tornado.concurrent.Future future: future to resolve when the command's response is received. """ LOGGER.debug('execute(%r, %r)', command, future) if... |
def _on_closed(self): """Invoked when the connection is closed""" LOGGER.error('Redis connection closed') self.connected = False self._on_close() self._stream = None |
def _on_connected(self, stream_future, connect_future): """Invoked when the socket stream has connected, setting up the stream callbacks and invoking the on connect callback if set. :param stream_future: The connection socket future :type stream_future: :class:`~tornado.concurrent.Future` :param stream_future: The conn... |
def _write(self, command, future): """Write a command to the socket :param Command command: the Command data structure """ def on_written(): self._on_written(command, future) try: self._stream.write(command.command, callback=on_written) except iostream.StreamClosedError as error: future.set_exception(exceptions.Connect... |
def connect(self): """Connect to the Redis server or Cluster. :rtype: tornado.concurrent.Future """ LOGGER.debug('Creating a%s connection to %s:%s (db %s)', ' cluster node' if self._clustering else '', self._hosts[0]['host'], self._hosts[0]['port'], self._hosts[0].get( 'db', DEFAULT_DB)) self._connect_future = concurre... |
def close(self): """Close any open connections to Redis. :raises: :exc:`tredis.exceptions.ConnectionError` """ if not self._connected.is_set(): raise exceptions.ConnectionError('not connected') self._closing = True if self._clustering: for host in self._cluster.keys(): self._cluster[host].close() elif self._connection:... |
def ready(self): """Indicates that the client is connected to the Redis server or cluster and is ready for use. :rtype: bool """ if self._clustering: return (all([c.connected for c in self._cluster.values()]) and len(self._cluster)) return (self._connection and self._connection.connected) |
def _create_cluster_connection(self, node): """Create a connection to a Redis server. :param node: The node to connect to :type node: tredis.cluster.ClusterNode """ LOGGER.debug('Creating a cluster connection to %s:%s', node.ip, node.port) conn = _Connection( node.ip, node.port, 0, self._read, self._on_closed, self.io_... |
def _encode_resp(self, value): """Dynamically build the RESP payload based upon the list provided. :param mixed value: The list of command parts to encode :rtype: bytes """ if isinstance(value, bytes): return b''.join( [b'$', ascii(len(value)).encode('ascii'), CRLF, value, CRLF]) elif isinstance(value, str): # pragma: ... |
def _eval_expectation(command, response, future): """Evaluate the response from Redis to see if it matches the expected response. :param command: The command that is being evaluated :type command: tredis.client.Command :param bytes response: The response value to check :param future: The future representing the executi... |
def _execute(self, parts, expectation=None, format_callback=None): """Really execute a redis command :param list parts: The list of command parts :param mixed expectation: Optional response expectation :rtype: :class:`~tornado.concurrent.Future` :raises: :exc:`~tredis.exceptions.SubscribedError` """ future = concurrent... |
def _on_cluster_discovery(self, future): """Invoked when the Redis server has responded to the ``CLUSTER_NODES`` command. :param future: The future containing the response from Redis :type future: tornado.concurrent.Future """ LOGGER.debug('_on_cluster_discovery(%r)', future) common.maybe_raise_exception(future) nodes ... |
def _on_closed(self): """Invoked by connections when they are closed.""" self._connected.clear() if not self._closing: if self._on_close_callback: self._on_close_callback() else: raise exceptions.ConnectionError('closed') |
def _on_cluster_data_moved(self, response, command, future): """Process the ``MOVED`` response from a Redis cluster node. :param bytes response: The response from the Redis server :param command: The command that was being executed :type command: tredis.client.Command :param future: The execution future :type future: t... |
def _on_connected(self, future): """Invoked when connections have been established. If the client is in clustering mode, it will kick of the discovery step if needed. If not, it will select the configured database. :param future: The connection future :type future: tornado.concurrent.Future """ if future.exception(): s... |
def _on_read_only_error(self, command, future): """Invoked when a Redis node returns an error indicating it's in read-only mode. It will use the ``INFO REPLICATION`` command to attempt to find the master server and failover to that, reissuing the command to that server. :param command: The command that was being execut... |
self._on_connected) if self._clustering: command.connection.set_readonly(True) LOGGER.debug('%s is read-only, need to failover to new master', command.connection.name) cmd = Command( self._build_command(['INFO', 'REPLICATION']), self._connection, None, common.format_info_response) self.io_loop.add_future(failover_futur... |
def _read(self, command, future): """Invoked when a command is executed to read and parse its results. It will loop on the IOLoop until the response is complete and then set the value of the response in the execution future. :param command: The command that was being executed :type command: tredis.client.Command :param... |
def _pick_cluster_host(self, value): """Selects the Redis cluster host for the specified value. :param mixed value: The value to use when looking for the host :rtype: tredis.client._Connection """ crc = crc16.crc16(self._encode_resp(value[1])) % HASH_SLOTS for host in self._cluster.keys(): for slot in self._cluster[hos... |
def parse_lines(stream, separator=None): """ Takes each line of a stream, creating a generator that yields tuples of line, row - where row is the line split by separator (or by whitespace if separator is None. :param stream: :param separator: (optional) :return: generator """ separator = None if separator is None else ... |
def parse_buffer(stream, separator=None): """ Returns a dictionary of the lines of a stream, an array of rows of the stream (split by separator), and an array of the columns of the stream (also split by separator) :param stream: :param separator: :return: dict """ rows = [] lines = [] for line, row in parse_lines(strea... |
def display(result, stream): """ Intelligently print the result (or pass if result is None). :param result: :return: None """ if result is None: return elif isinstance(result, basestring): pass elif isinstance(result, collections.Mapping): result = u'\n'.join(u'%s=%s' % (k, v) for k, v in result.iteritems() if v is not... |
def safe_evaluate(command, glob, local): """ Continue to attempt to execute the given command, importing objects which cause a NameError in the command :param command: command for eval :param glob: globals dict for eval :param local: locals dict for eval :return: command result """ while True: try: return eval(command,... |
def int_to_gematria(num, gershayim=True): """convert integers between 1 an 999 to Hebrew numerals. - set gershayim flag to False to ommit gershayim """ # 1. Lookup in specials if num in specialnumbers['specials']: retval = specialnumbers['specials'][num] return _add_gershayim(retval) if gershayim else retval # 2. Gener... |
def get_urls_from_onetab(onetab): """ Get video urls from a link to the onetab shared page. Args: onetab (str): Link to a onetab shared page. Returns: list: List of links to the videos. """ html = requests.get(onetab).text soup = BeautifulSoup(html, 'lxml') divs = soup.findAll('div', {'style': 'padding-left: 24px; ' 'p... |
def from_dict(cls, d): """Used to create an instance of this class from a pstats dict item""" stats = [] for (filename, lineno, name), stat_values in d.iteritems(): if len(stat_values) == 5: ncalls, ncall_nr, total_time, cum_time, subcall_stats = stat_values else: ncalls, ncall_nr, total_time, cum_time = stat_values su... |
def to_dict(self): """Convert back to the pstats dictionary representation (used for saving back as pstats binary file)""" if self.subcall is not None: if isinstance(self.subcall, dict): subcalls = self.subcall else: subcalls = {} for s in self.subcall: subcalls.update(s.to_dict()) return {(self.filename, self.line_num... |
def exclude_functions(self, *funcs): """ Excludes the contributions from the following functions. """ for f in funcs: f.exclude = True run_time_s = sum(0 if s.exclude else s.own_time_s for s in self.stats) cProfileFuncStat.run_time_s = run_time_s |
def get_top(self, stat, n): """Return the top n values when sorting by 'stat'""" return sorted(self.stats, key=lambda x: getattr(x, stat), reverse=True)[:n] |
def save_pstat(self, path): """ Save the modified pstats file """ stats = {} for s in self.stats: if not s.exclude: stats.update(s.to_dict()) with open(path, 'wb') as f: marshal.dump(stats, f) |
def safe_int(value): """ Tries to convert a value to int; returns 0 if conversion failed """ try: result = int(value) if result < 0: raise NegativeDurationError( 'Negative values in duration strings are not allowed!' ) except NegativeDurationError as exc: raise exc except (TypeError, ValueError): result = 0 return resu... |
def _parse(value, strict=True): """ Preliminary duration value parser strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration value exceed allowed values """ pattern = r'(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)' match = re.match(pattern, value) if not match: raise Va... |
def to_iso8601(value, strict=True, force_int=True): """ converts duration value to ISO8601 string accepts integers, hh:mm:ss or mm:ss strings, timedelta objects strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration string exceed allowed values """ # split seconds to larger unit... |
force_int: seconds = '{:02}'.format(int(seconds)) else: # 9 chars long w/leading 0, 6 digits after decimal seconds = '%09.6f' % seconds time += '{}S'.format(seconds) return 'P' + date + time |
def to_seconds(value, strict=True, force_int=True): """ converts duration value to integer seconds strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration value exceed allowed values """ if isinstance(value, int): return value # assuming it's seconds elif isinstance(value, timede... |
def to_timedelta(value, strict=True): """ converts duration string to timedelta strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration string exceed allowed values """ if isinstance(value, int): return timedelta(seconds=value) # assuming it's seconds elif isinstance(value, timed... |
def to_tuple(value, strict=True, force_int=True): """ converts duration value to tuple of integers strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration value exceed allowed values """ if isinstance(value, int): seconds = value minutes, seconds = divmod(seconds, 60) hours, minu... |
def name_url(provider, cloud, method_name): """ Get a URL for a method in a driver """ snake_parts = method_name.split('_') if len(snake_parts) <= 1: return False # Convention for libcloud is ex_ are extended methods if snake_parts[0] == 'ex': extra = True method_name = method_name.replace('ex_', '', 1) else: extra = F... |
def contains_frame(data): """ Read the frame length from the start of `data` and check if the data is long enough to contain the entire frame. """ if len(data) < 2: return False b2 = struct.unpack('!B', data[1])[0] payload_len = b2 & 0x7F payload_start = 2 if payload_len == 126: if len(data) > 4: payload_len = struct.u... |
def mask(key, original): """ Mask an octet string using the given masking key. The following masking algorithm is used, as defined in RFC 6455: for each octet: j = i MOD 4 transformed-octet-i = original-octet-i XOR masking-key-octet-j """ if len(key) != 4: raise ValueError('invalid masking key "%s"' % key) key = map(or... |
def pack(self): """ Pack the frame into a string according to the following scheme: +-+-+-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127) | | |1|2|3| |K| | | +-+-+-+-+-----... |
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data continued ... | +---------------------------------------------------------------+ """ header = struct.pack('!B', (self.final << 7) | (self.rsv1 << 6) | (self.rsv2 << 5) | (self.rsv3 << 4) | (self.opcode & 0xf)) mask = bool(self.masking_key) ... |
+ self.masking_key + self.mask_payload() return header + self.payload |
def fragment(self, fragment_size, mask=False): """ Fragment the frame into a chain of fragment frames: - An initial frame with non-zero opcode - Zero or more frames with opcode = 0 and final = False - A final frame with opcode = 0 and final = True The first and last frame may be the same frame, having a non-zero opcode... |
generated masking key. """ frames = [] for start in xrange(0, len(self.payload), fragment_size): payload = self.payload[start:start + fragment_size] frames.append(Frame(OPCODE_CONTINUATION, payload, mask=mask, final=False)) frames[0].opcode = self.opcode frames[-1].final = True return frames |
def unpack_close(self): """ Unpack a close message into a status code and a reason. If no payload is given, the code is None and the reason is an empty string. """ if self.payload: code = struct.unpack('!H', str(self.payload[:2]))[0] reason = str(self.payload[2:]) else: code = None reason = '' return code, reason |
def readn(self, n): """ Keep receiving data until exactly `n` bytes have been read. """ data = '' while len(data) < n: received = self.sock.recv(n - len(data)) if not len(received): raise socket.error('no data read from socket') data += received return data |
def quality_comparator(video_data): """Custom comparator used to choose the right format based on the resolution.""" def parse_resolution(res: str) -> Tuple[int, ...]: return tuple(map(int, res.split('x'))) raw_resolution = video_data['resolution'] resolution = parse_resolution(raw_resolution) return resolution |
def _mic_required(target_info): """ Checks the MsvAvFlags field of the supplied TargetInfo structure to determine in the MIC flags is set :param target_info: The TargetInfo structure to check :return: a boolean value indicating that the MIC flag is set """ if target_info is not None and target_info[TargetInfo.NTLMSSP_A... |
def initialize_security_context(self): """ Idiomatic Python implementation of initialize_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server """ # Generate the NTLM Negotiate Request negoti... |
def wrap_message(self, message): """ Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if 'confidentiality' was negotiated, otherwise the message is left untouched. :return: A tuple containing the message signature and the optionally encrypted message """ if not self.is... |
def unwrap_message(self, message, signature): """ Verifies the supplied signature against the message and decrypts the message if 'confidentiality' was negotiated. A SignatureException is raised if the signature cannot be parsed or the version is unsupported A SequenceException is raised if the sequence number in the s... |
def parse_options(): """ Parse command line arguments. Returns: options, args """ parser = argparse.ArgumentParser(description='Video downloader by radzak.', prog='RTVdownloader') urls_group = parser.add_mutually_exclusive_group(required=True) urls_group.add_argument('urls', type=str, metavar='URL', default=[], nargs='... |
def get_article_url(self): """ Get the url of the TVP Info article itself, not the url of the preview with the 'Przejdź do artykułu' hyperlink. Returns: (str): Url of the article with the video. """ html = requests.get(self.url).text soup = BeautifulSoup(html, 'lxml') div = soup.find('div', class_='more-back') if div: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.