text
stringlengths
81
112k
Emits next multipart reader object. async def next(self) -> Any: """Emits next multipart reader object.""" item = await self.stream.next() if self.stream.at_eof(): await self.release() return item
Reads body part data. decode: Decodes data following by encoding method from Content-Encoding header. If it missed data remains untouched async def read(self, *, decode: bool=False) -> Any: """Reads body part data. decode: Decodes data following by encoding ...
Reads body part content chunk of the specified size. size: chunk size async def read_chunk(self, size: int=chunk_size) -> bytes: """Reads body part content chunk of the specified size. size: chunk size """ if self._at_eof: return b'' if self._length: ...
Reads body part by line by line. async def readline(self) -> bytes: """Reads body part by line by line.""" if self._at_eof: return b'' if self._unread: line = self._unread.popleft() else: line = await self._content.readline() if line.startsw...
Like read(), but reads all the data to the void. async def release(self) -> None: """Like read(), but reads all the data to the void.""" if self._at_eof: return while not self._at_eof: await self.read_chunk(self.chunk_size)
Like read(), but assumes that body part contains text data. async def text(self, *, encoding: Optional[str]=None) -> str: """Like read(), but assumes that body part contains text data.""" data = await self.read(decode=True) # see https://www.w3.org/TR/html5/forms.html#multipart/form-data-encodi...
Like read(), but assumes that body parts contains JSON data. async def json(self, *, encoding: Optional[str]=None) -> Any: """Like read(), but assumes that body parts contains JSON data.""" data = await self.read(decode=True) if not data: return None encoding = encoding or s...
Like read(), but assumes that body parts contains form urlencoded data. async def form(self, *, encoding: Optional[str]=None) -> List[Tuple[str, str]]: """Like read(), but assumes that body parts contains form urlencoded data. """ data = await self.read(decode...
Decodes data according the specified Content-Encoding or Content-Transfer-Encoding headers value. def decode(self, data: bytes) -> bytes: """Decodes data according the specified Content-Encoding or Content-Transfer-Encoding headers value. """ if CONTENT_TRANSFER_ENCODING in self...
Returns charset parameter from Content-Type header or default. def get_charset(self, default: str) -> str: """Returns charset parameter from Content-Type header or default.""" ctype = self.headers.get(CONTENT_TYPE, '') mimetype = parse_mimetype(ctype) return mimetype.parameters.get('cha...
Returns name specified in Content-Disposition header or None if missed or header is malformed. def name(self) -> Optional[str]: """Returns name specified in Content-Disposition header or None if missed or header is malformed. """ _, params = parse_content_disposition( ...
Constructs reader instance from HTTP response. :param response: :class:`~aiohttp.client.ClientResponse` instance def from_response(cls, response: 'ClientResponse') -> Any: """Constructs reader instance from HTTP response. :param response: :class:`~aiohttp.client.ClientResponse` instance ...
Emits the next multipart body part. async def next(self) -> Any: """Emits the next multipart body part.""" # So, if we're at BOF, we need to skip till the boundary. if self._at_eof: return await self._maybe_release_last_part() if self._at_bof: await self....
Reads all the body parts to the void till the final boundary. async def release(self) -> None: """Reads all the body parts to the void till the final boundary.""" while not self._at_eof: item = await self.next() if item is None: break await item.relea...
Dispatches the response by the `Content-Type` header, returning suitable reader instance. :param dict headers: Response headers def _get_part_reader(self, headers: 'CIMultiDictProxy[str]') -> Any: """Dispatches the response by the `Content-Type` header, returning suitable reader instan...
Ensures that the last read body part is read completely. async def _maybe_release_last_part(self) -> None: """Ensures that the last read body part is read completely.""" if self._last_part is not None: if not self._last_part.at_eof(): await self._last_part.release() ...
Wrap boundary parameter value in quotes, if necessary. Reads self.boundary and returns a unicode sting. def _boundary_value(self) -> str: """Wrap boundary parameter value in quotes, if necessary. Reads self.boundary and returns a unicode sting. """ # Refer to RFCs 7231, 7230, ...
Adds a new body part to multipart writer. def append_payload(self, payload: Payload) -> Payload: """Adds a new body part to multipart writer.""" # compression encoding = payload.headers.get(CONTENT_ENCODING, '').lower() # type: Optional[str] # noqa if encoding and encoding not in ('de...
Helper to append JSON part. def append_json( self, obj: Any, headers: Optional['MultiMapping[str]']=None ) -> Payload: """Helper to append JSON part.""" if headers is None: headers = CIMultiDict() return self.append_payload(JsonPayload(obj, h...
Helper to append form urlencoded part. def append_form( self, obj: Union[Sequence[Tuple[str, str]], Mapping[str, str]], headers: Optional['MultiMapping[str]']=None ) -> Payload: """Helper to append form urlencoded part.""" assert isinstance...
Size of the payload. def size(self) -> Optional[int]: """Size of the payload.""" if not self._parts: return 0 total = 0 for part, encoding, te_encoding in self._parts: if encoding or te_encoding or part.size is None: return None tota...
Write body. async def write(self, writer: Any, close_boundary: bool=True) -> None: """Write body.""" if not self._parts: return for part, encoding, te_encoding in self._parts: await writer.write(b'--' + self._boundary + b'\r\n') await wri...
Update destination host, port and connection type (ssl). def update_host(self, url: URL) -> None: """Update destination host, port and connection type (ssl).""" # get host/port if not url.host: raise InvalidURL(url) # basic auth info username, password = url.user, u...
Convert request version to two elements tuple. parser HTTP version '1.1' => (1, 1) def update_version(self, version: Union[http.HttpVersion, str]) -> None: """Convert request version to two elements tuple. parser HTTP version '1.1' => (1, 1) """ if isinstance(version, str): ...
Update request headers. def update_headers(self, headers: Optional[LooseHeaders]) -> None: """Update request headers.""" self.headers = CIMultiDict() # type: CIMultiDict[str] # add host netloc = cast(str, self.url.raw_host) if helpers.is_ipv6_address(netloc): netlo...
Update request cookies header. def update_cookies(self, cookies: Optional[LooseCookies]) -> None: """Update request cookies header.""" if not cookies: return c = SimpleCookie() if hdrs.COOKIE in self.headers: c.load(self.headers.get(hdrs.COOKIE, '')) ...
Set request content encoding. def update_content_encoding(self, data: Any) -> None: """Set request content encoding.""" if not data: return enc = self.headers.get(hdrs.CONTENT_ENCODING, '').lower() if enc: if self.compress: raise ValueError( ...
Analyze transfer-encoding header. def update_transfer_encoding(self) -> None: """Analyze transfer-encoding header.""" te = self.headers.get(hdrs.TRANSFER_ENCODING, '').lower() if 'chunked' in te: if self.chunked: raise ValueError( 'chunked can no...
Set basic auth. def update_auth(self, auth: Optional[BasicAuth]) -> None: """Set basic auth.""" if auth is None: auth = self.auth if auth is None: return if not isinstance(auth, helpers.BasicAuth): raise TypeError('BasicAuth() tuple is required inste...
Support coroutines that yields bytes objects. async def write_bytes(self, writer: AbstractStreamWriter, conn: 'Connection') -> None: """Support coroutines that yields bytes objects.""" # 100 response if self._continue is not None: await writer.drain() ...
Start response processing. async def start(self, connection: 'Connection') -> 'ClientResponse': """Start response processing.""" self._closed = False self._protocol = connection.protocol self._connection = connection with self._timer: while True: # r...
Read response payload. async def read(self) -> bytes: """Read response payload.""" if self._body is None: try: self._body = await self.content.read() for trace in self._traces: await trace.send_response_chunk_received(self._body) ...
Read response payload and decode. async def text(self, encoding: Optional[str]=None, errors: str='strict') -> str: """Read response payload and decode.""" if self._body is None: await self.read() if encoding is None: encoding = self.get_encoding() ...
Read and decodes JSON response. async def json(self, *, encoding: str=None, loads: JSONDecoder=DEFAULT_JSON_DECODER, content_type: Optional[str]='application/json') -> Any: """Read and decodes JSON response.""" if self._body is None: await self.read() ...
Enables automatic chunked transfer encoding. def enable_chunked_encoding(self, chunk_size: Optional[int]=None) -> None: """Enables automatic chunked transfer encoding.""" self._chunked = True if hdrs.CONTENT_LENGTH in self._headers: raise RuntimeError("You can't enable chunked enco...
Enables response compression encoding. def enable_compression(self, force: Optional[Union[bool, ContentCoding]]=None ) -> None: """Enables response compression encoding.""" # Backwards compatibility for when force was a bool <0.17. if type(f...
Set or update response cookie. Sets new cookie or updates existent with new value. Also updates only those params which are not None. def set_cookie(self, name: str, value: str, *, expires: Optional[str]=None, domain: Optional[str]=None, max_age...
Delete cookie. Creates new empty expired cookie. def del_cookie(self, name: str, *, domain: Optional[str]=None, path: str='/') -> None: """Delete cookie. Creates new empty expired cookie. """ # TODO: do we need domain/path here? se...
The value of Last-Modified HTTP header, or None. This header is represented as a `datetime` object. def last_modified(self) -> Optional[datetime.datetime]: """The value of Last-Modified HTTP header, or None. This header is represented as a `datetime` object. """ httpdate = sel...
Default handler for Expect header. Just send "100 Continue" to client. raise HTTPExpectationFailed if value of header is not "100-continue" async def _default_expect_handler(request: Request) -> None: """Default handler for Expect header. Just send "100 Continue" to client. raise HTTPExpectationF...
Construct url for route with additional params. def url_for(self, *args: str, **kwargs: str) -> URL: """Construct url for route with additional params.""" return self._resource.url_for(*args, **kwargs)
Add static files view. prefix - url prefix path - folder with files def add_static(self, prefix: str, path: PathLike, *, name: Optional[str]=None, expect_handler: Optional[_ExpectHandler]=None, chunk_size: int=256 * 1024, show...
Shortcut for add_route with method HEAD def add_head(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with method HEAD """ return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs)
Shortcut for add_route with method OPTIONS def add_options(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with method OPTIONS """ return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs)
Shortcut for add_route with method GET, if allow_head is true another route is added allowing head requests to the same endpoint def add_get(self, path: str, handler: _WebHandler, *, name: Optional[str]=None, allow_head: bool=True, **kwargs: Any) -> AbstractRoute: """ ...
Shortcut for add_route with method POST def add_post(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with method POST """ return self.add_route(hdrs.METH_POST, path, handler, **kwargs)
Shortcut for add_route with method PUT def add_put(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with method PUT """ return self.add_route(hdrs.METH_PUT, path, handler, **kwargs)
Shortcut for add_route with method PATCH def add_patch(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with method PATCH """ return self.add_route(hdrs.METH_PATCH, path, handler, **kwargs)
Shortcut for add_route with method DELETE def add_delete(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with method DELETE """ return self.add_route(hdrs.METH_DELETE, path, handler, **kwargs)
Shortcut for add_route with ANY methods for a class-based view def add_view(self, path: str, handler: AbstractView, **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with ANY methods for a class-based view """ return self.add_route(hdrs.METH_ANY, path, handler...
Append routes to route table. Parameter should be a sequence of RouteDef objects. def add_routes(self, routes: Iterable[AbstractRouteDef]) -> None: """Append routes to route table. Parameter should be a sequence of RouteDef objects. """ for route_def in routes: rou...
Parses RFC 5322 headers from a stream. Line continuations are supported. Returns list of header name and value pairs. Header name is in upper case. def parse_headers( self, lines: List[bytes] ) -> Tuple['CIMultiDictProxy[str]', RawHeaders, Opti...
extra info from connection transport def get_extra_info(self, name: str, default: Any=None) -> Any: """extra info from connection transport""" conn = self._response.connection if conn is None: return default transport = conn.transport if transport is None: ...
Returns an apparently legit user-agent, if not requested one of a specific style. Defaults to a Chrome-style User-Agent. def user_agent(style=None) -> _UserAgent: """Returns an apparently legit user-agent, if not requested one of a specific style. Defaults to a Chrome-style User-Agent. """ global u...
Bytes representation of the HTML content. (`learn more <http://www.diveintopython3.net/strings.html>`_). def raw_html(self) -> _RawHTML: """Bytes representation of the HTML content. (`learn more <http://www.diveintopython3.net/strings.html>`_). """ if self._html: ret...
Unicode representation of the HTML content (`learn more <http://www.diveintopython3.net/strings.html>`_). def html(self) -> _BaseHTML: """Unicode representation of the HTML content (`learn more <http://www.diveintopython3.net/strings.html>`_). """ if self._html: retu...
The encoding string to be used, extracted from the HTML and :class:`HTMLResponse <HTMLResponse>` headers. def encoding(self) -> _Encoding: """The encoding string to be used, extracted from the HTML and :class:`HTMLResponse <HTMLResponse>` headers. """ if self._encoding: ...
`PyQuery <https://pythonhosted.org/pyquery/>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`. def pq(self) -> PyQuery: """`PyQuery <https://pythonhosted.org/pyquery/>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`. """ if se...
`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`. def lxml(self) -> HtmlElement: """`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`. """ if self._lxml is None: try: ...
Given a CSS Selector, returns a list of :class:`Element <Element>` objects or a single one. :param selector: CSS Selector to use. :param clean: Whether or not to sanitize the found HTML of ``<script>`` and ``<style>`` tags. :param containing: If specified, only return elements that cont...
Given an XPath selector, returns a list of :class:`Element <Element>` objects or a single one. :param selector: XPath Selector to use. :param clean: Whether or not to sanitize the found HTML of ``<script>`` and ``<style>`` tags. :param first: Whether or not to return just the first resu...
Search the :class:`Element <Element>` (multiple times) for the given parse template. :param template: The Parse template to use. def search_all(self, template: str) -> _Result: """Search the :class:`Element <Element>` (multiple times) for the given parse template. :param templ...
All found links on page, in as–is form. def links(self) -> _Links: """All found links on page, in as–is form.""" def gen(): for link in self.find('a'): try: href = link.attrs['href'].strip() if href and not (href.startswith('#') and ...
Makes a given link absolute. def _make_absolute(self, link): """Makes a given link absolute.""" # Parse the link with stdlib. parsed = urlparse(link)._asdict() # If link is relative, then join it with base_url. if not parsed['netloc']: return urljoin(self.base_url,...
All found links on page, in absolute form (`learn more <https://www.navegabem.com/absolute-or-relative-links.html>`_). def absolute_links(self) -> _Links: """All found links on page, in absolute form (`learn more <https://www.navegabem.com/absolute-or-relative-links.html>`_). """ ...
The base URL for the page. Supports the ``<base>`` tag (`learn more <https://www.w3schools.com/tags/tag_base.asp>`_). def base_url(self) -> _URL: """The base URL for the page. Supports the ``<base>`` tag (`learn more <https://www.w3schools.com/tags/tag_base.asp>`_).""" # Support for <b...
Returns a dictionary of the attributes of the :class:`Element <Element>` (`learn more <https://www.w3schools.com/tags/ref_attributes.asp>`_). def attrs(self) -> _Attrs: """Returns a dictionary of the attributes of the :class:`Element <Element>` (`learn more <https://www.w3schools.com/tags/ref_a...
Attempts to find the next page, if there is one. If ``fetch`` is ``True`` (default), returns :class:`HTML <HTML>` object of next page. If ``fetch`` is ``False``, simply returns the next URL. def next(self, fetch: bool = False, next_symbol: _NextSymbol = DEFAULT_NEXT_SYMBOL) -> _Next: """Attempt...
Handle page creation and js rendering. Internal use for render/arender methods. async def _async_render(self, *, url: str, script: str = None, scrolldown, sleep: int, wait: float, reload, content: Optional[str], timeout: Union[float, int], keep_page: bool): """ Handle page creation and js rendering. Internal u...
Reloads the response in Chromium, and replaces HTML content with an updated version, with JavaScript executed. :param retries: The number of times to retry loading the page in Chromium. :param script: JavaScript to execute upon page load (optional). :param wait: The number of seconds to...
Change response enconding and replace it by a HTMLResponse. def response_hook(self, response, **kwargs) -> HTMLResponse: """ Change response enconding and replace it by a HTMLResponse. """ if not response.encoding: response.encoding = DEFAULT_ENCODING return HTMLResponse._from_respo...
If a browser was created close it first. def close(self): """ If a browser was created close it first. """ if hasattr(self, "_browser"): self.loop.run_until_complete(self._browser.close()) super().close()
Partial original request func and run it in a thread. def request(self, *args, **kwargs): """ Partial original request func and run it in a thread. """ func = partial(super().request, *args, **kwargs) return self.loop.run_in_executor(self.thread_pool, func)
Pass in all the coroutines you want to run, it will wrap each one in a task, run it and wait for the result. Return a list with all results, this is returned in the same order coros are passed in. def run(self, *coros): """ Pass in all the coroutines you want to run, it will wrap each o...
img_tensor: N, C, H, W def add_depth_channel(img_tensor, pad_mode): ''' img_tensor: N, C, H, W ''' img_tensor[:, 1] = get_depth_tensor(pad_mode) img_tensor[:, 2] = img_tensor[:, 0] * get_depth_tensor(pad_mode)
:param s: [src_sequence, batch_size, src_dim] :return: [src_sequence, batch_size. hidden_dim] def get_pre_compute(self, s): ''' :param s: [src_sequence, batch_size, src_dim] :return: [src_sequence, batch_size. hidden_dim] ''' hidden_dim = self.hidden_dim src_dim ...
:param s: [src_sequence_length, batch_size, src_dim] :param h: [batch_size, tgt_dim] or [tgt_sequence_length, batch_size, tgt_dim] :param mask: [src_sequence_length, batch_size]\ or [tgt_sequence_length, src_sequence_length, batch_sizse] :param pre_compute: [src_sequence_length, bat...
:param s: [src_sequence_length, batch_size, src_dim] :param prob: [src_sequence_length, batch_size]\ or [tgt_sequence_length, src_sequence_length, batch_size] :return: [batch_size, src_dim] or [tgt_sequence_length, batch_size, src_dim] def get_att(self, s, prob): ''' :param ...
Get shape of variable. Return type is tuple. def shape(tensor): ''' Get shape of variable. Return type is tuple. ''' temp_s = tensor.get_shape() return tuple([temp_s[i].value for i in range(0, len(temp_s))])
Get variable by name. def get_variable(name, temp_s): ''' Get variable by name. ''' return tf.Variable(tf.zeros(temp_s), name=name)
Dropout except test. def dropout(tensor, drop_prob, is_training): ''' Dropout except test. ''' if not is_training: return tensor return tf.nn.dropout(tensor, 1.0 - drop_prob)
Calculate time span. def get_elapsed(self, restart=True): ''' Calculate time span. ''' end = time.time() span = end - self.__start if restart: self.__start = end return span
return 18000x128x128 np array def do_tta_predict(args, model, ckp_path, tta_num=4): ''' return 18000x128x128 np array ''' model.eval() preds = [] meta = None # i is tta index, 0: no change, 1: horizon flip, 2: vertical flip, 3: do both for flip_index in range(tta_num): print('f...
Partitioning MNIST def partition_dataset(): """ Partitioning MNIST """ dataset = datasets.MNIST( './data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307, ), (0.3081, )) ])) size =...
Gradient averaging. def average_gradients(model): """ Gradient averaging. """ size = float(dist.get_world_size()) for param in model.parameters(): dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM, group=0) param.grad.data /= size
Distributed Synchronous SGD Example def run(params): """ Distributed Synchronous SGD Example """ rank = dist.get_rank() torch.manual_seed(1234) train_set, bsz = partition_dataset() model = Net() model = model optimizer = optim.SGD(model.parameters(), lr=params['learning_rate'], momentum=par...
Load graph def graph_loads(graph_json): ''' Load graph ''' layers = [] for layer in graph_json['layers']: layer_info = Layer(layer['type'], layer['input'], layer['output'], layer['size']) layer_info.is_delete = layer['is_delete'] layers.append(layer_info) graph = Graph(g...
Set size. def set_size(self, graph_id, size): ''' Set size. ''' if self.graph_type == LayerType.attention.value: if self.input[0] == graph_id: self.size = size if self.graph_type == LayerType.rnn.value: self.size = size if self.gra...
Clear size def clear_size(self): ''' Clear size ''' if self.graph_type == LayerType.attention.value or \ LayerType.rnn.value or LayerType.self_attention.value: self.size = None
valid the topology def is_topology(self, layers=None): ''' valid the topology ''' if layers is None: layers = self.layers layers_nodle = [] result = [] for i, layer in enumerate(layers): if layer.is_delete is False: layers_...
Judge whether is legal for layers def is_legal(self, layers=None): ''' Judge whether is legal for layers ''' if layers is None: layers = self.layers for layer in layers: if layer.is_delete is False: if len(layer.input) != layer.input_size...
Mutation for a graph def mutation(self, only_add=False): ''' Mutation for a graph ''' types = [] if self.layer_num() < self.max_layer_num: types.append(0) types.append(1) if self.layer_num() > 5 and only_add is False: types.append(2) ...
Main function of SMAC for CLI interface Returns ------- instance optimizer def _main_cli(self): """Main function of SMAC for CLI interface Returns ------- instance optimizer """ self.logger.info("SMAC call...
TODO: this is urgly, we put all the initialization work in this method, because initialization relies on search space, also because update_search_space is called at the beginning. NOTE: updating search space is not supported. Parameters ---------- search_space: searc...
receive_trial_result Parameters ---------- parameter_id: int parameter id parameters: parameters value: value Raises ------ RuntimeError Received parameter id not in total_data def receive_t...
Convert the values of type `loguniform` back to their initial range Also, we convert categorical: categorical values in search space are changed to list of numbers before, those original values will be changed back in this function Parameters ---------- challenge...
generate one instance of hyperparameters Parameters ---------- parameter_id: int parameter id Returns ------- list new generated parameters def generate_parameters(self, parameter_id): """generate one instance of hyperpar...
generate mutiple instances of hyperparameters Parameters ---------- parameter_id_list: list list of parameter id Returns ------- list list of new generated parameters def generate_multiple_parameters(self, parameter_id_list): ...
Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper def lovasz_grad(gt_sorted): """ Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(...
IoU for foreground class binary: 1 foreground, 0 background def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True): """ IoU for foreground class binary: 1 foreground, 0 background """ if not per_image: preds, labels = (preds,), (labels,) ious = [] for pred, label i...