code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def remove(self, *tokens: str) -> None: from wdom.web_node import WdomElement _removed_tokens = [] for token in tokens: self._validate_token(token) if token in self: self._list.remove(token) _removed_tokens.append(token) if...
Remove tokens from list.
def toggle(self, token: str) -> None: self._validate_token(token) if token in self: self.remove(token) else: self.add(token)
Add or remove token to/from list. If token is in this list, the token will be removed. Otherwise add it to list.
def contains(self, token: str) -> bool: self._validate_token(token) return token in self
Return if the token is in the list or not.
def html(self) -> str: if self._owner and self.name in self._owner._special_attr_boolean: return self.name else: value = self.value if isinstance(value, str): value = html_.escape(value) return '{name}="{value}"'.format(name=self.n...
Return string representation of this. Used in start tag of HTML representation of the Element node.
def html(self) -> str: if isinstance(self.value, bool): val = 'true' if self.value else 'false' else: val = str(self.value) return 'draggable="{}"'.format(val)
Return html representation.
def getNamedItem(self, name: str) -> Optional[Attr]: return self._dict.get(name, None)
Get ``Attr`` object which has ``name``. If does not have ``name`` attr, return None.
def setNamedItem(self, item: Attr) -> None: from wdom.web_node import WdomElement if not isinstance(item, Attr): raise TypeError('item must be an instance of Attr') if isinstance(self._owner, WdomElement): self._owner.js_exec('setAttribute', item.name, # type: i...
Set ``Attr`` object in this collection.
def removeNamedItem(self, item: Attr) -> Optional[Attr]: from wdom.web_node import WdomElement if not isinstance(item, Attr): raise TypeError('item must be an instance of Attr') if isinstance(self._owner, WdomElement): self._owner.js_exec('removeAttribute', item....
Set ``Attr`` object and return it (if exists).
def item(self, index: int) -> Optional[Attr]: if 0 <= index < len(self): return self._dict[tuple(self._dict.keys())[index]] return None
Return ``index``-th attr node.
def toString(self) -> str: return ' '.join(attr.html for attr in self._dict.values())
Return string representation of collections.
def start_tag(self) -> str: tag = '<' + self.tag attrs = self._get_attrs_by_string() if attrs: tag = ' '.join((tag, attrs)) return tag + '>'
Return HTML start tag.
def insertAdjacentHTML(self, position: str, html: str) -> None: df = self._parse_html(html) pos = position.lower() if pos == 'beforebegin': self.before(df) elif pos == 'afterbegin': self.prepend(df) elif pos == 'beforeend': self.append...
Parse ``html`` to DOM and insert to ``position``. ``position`` is a case-insensive string, and must be one of "beforeBegin", "afterBegin", "beforeEnd", or "afterEnd".
def getAttribute(self, attr: str) -> _AttrValueType: if attr == 'class': if self.classList: return self.classList.toString() return None attr_node = self.getAttributeNode(attr) if attr_node is None: return None return attr_node...
Get attribute of this node as string format. If this node does not have ``attr``, return None.
def getAttributeNode(self, attr: str) -> Optional[Attr]: return self.attributes.getNamedItem(attr)
Get attribute of this node as Attr format. If this node does not have ``attr``, return None.
def hasAttribute(self, attr: str) -> bool: if attr == 'class': return bool(self.classList) return attr in self.attributes
Return True if this node has ``attr``.
def setAttribute(self, attr: str, value: _AttrValueType) -> None: self._set_attribute(attr, value)
Set ``attr`` and ``value`` in this node.
def removeAttributeNode(self, attr: Attr) -> Optional[Attr]: return self.attributes.removeNamedItem(attr)
Remove ``Attr`` node from this node.
def style(self, style: _AttrValueType) -> None: if isinstance(style, str): self.__style._parse_str(style) elif style is None: self.__style._parse_str('') elif isinstance(style, CSSStyleDeclaration): self.__style._owner = None if style._own...
Set style attribute of this node. If argument ``style`` is string, it will be parsed to ``CSSStyleDeclaration``.
def draggable(self) -> Union[bool, str]: if not self.hasAttribute('draggable'): return False return self.getAttribute('draggable')
Get ``draggable`` property.
def draggable(self, value: Union[bool, str]) -> None: if value is False: self.removeAttribute('draggable') else: self.setAttribute('draggable', value)
Set ``draggable`` property. ``value`` is boolean or string.
def form(self) -> Optional['HTMLFormElement']: if self.__form: return self.__form parent = self.parentNode while parent: if isinstance(parent, HTMLFormElement): return parent else: parent = parent.parentNode ret...
Get ``HTMLFormElement`` object related to this node.
def on_event_pre(self, e: Event) -> None: super().on_event_pre(e) ct_msg = e.init.get('currentTarget', dict()) if e.type in ('input', 'change'): # Update user inputs if self.type.lower() == 'checkbox': self._set_attribute('checked', ct_msg.get('ch...
Set values set on browser before calling event listeners.
def control(self) -> Optional[HTMLElement]: id = self.getAttribute('for') if id: if self.ownerDocument: return self.ownerDocument.getElementById(id) elif isinstance(id, str): from wdom.document import getElementById return ...
Return related HTMLElement object.
def on_event_pre(self, e: Event) -> None: super().on_event_pre(e) ct_msg = e.init.get('currentTarget', dict()) if e.type in ('input', 'change'): self._set_attribute('value', ct_msg.get('value')) _selected = ct_msg.get('selectedOptions', []) self._sele...
Set values set on browser before calling event listeners.
def selectedOptions(self) -> NodeList: return NodeList(list(opt for opt in self.options if opt.selected))
Return all selected option nodes.
def on_event_pre(self, e: Event) -> None: super().on_event_pre(e) ct_msg = e.init.get('currentTarget', dict()) if e.type in ('input', 'change'): # Update user inputs self._set_text_content(ct_msg.get('value') or '')
Set values set on browser before calling event listeners.
def NewTagClass(class_name: str, tag: str = None, bases: Union[type, Iterable] = (Tag, ), **kwargs: Any) -> type: if tag is None: tag = class_name.lower() if not isinstance(type, tuple): if isinstance(bases, Iterable): bases = tuple(bases) ...
Generate and return new ``Tag`` class. If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of the new class. ``bases`` should be a tuple of base classes. If it is empty, use ``Tag`` class for a base class. Other keyword arguments are used for class variables of the new class. ...
def _clone_node(self) -> 'Tag': clone = type(self)() for attr in self.attributes: clone.setAttribute(attr, self.getAttribute(attr)) for c in self.classList: clone.addClass(c) clone.style.update(self.style) # TODO: should clone event listeners??? ...
Need to copy class, not tag. So need to re-implement copy.
def textContent(self, text: str) -> None: # type: ignore if self._inner_element: self._inner_element.textContent = text else: # Need a trick to call property of super-class super().textContent = text
Set text content to inner node.
def html(self) -> str: if self._inner_element: return self.start_tag + self._inner_element.html + self.end_tag return super().html
Get whole html representation of this node.
def innerHTML(self) -> str: if self._inner_element: return self._inner_element.innerHTML return super().innerHTML
Get innerHTML of the inner node.
def start_server(app: web.Application = None, port: int = None, address: str = None, **kwargs: Any) -> HTTPServer: app = app or get_app() port = port if port is not None else config.port address = address if address is not None else config.address server = app.listen(port, address...
Start server with ``app`` on ``localhost:port``. If port is not specified, use command line option of ``--port``.
def get(self) -> None: from wdom.document import get_document logger.info('connected') self.write(get_document().build())
Return whole html representation of the root document.
async def terminate(self) -> None: await asyncio.sleep(config.shutdown_wait) # stop server and close loop if no more connection exists if not is_connected(): stop_server(self.application.server) self.application.loop.stop()
Terminate server if no more connection exists.
def on_close(self) -> None: logger.info('WebSocket CLOSED') if self in connections: # Remove this connection from connection-list connections.remove(self) # close if auto_shutdown is enabled and there is no more connection if config.auto_shutdown and not ...
Execute when connection closed.
def log_request(self, handler: web.RequestHandler) -> None: if 'log_function' in self.settings: self.settings['log_function'](handler) return status = handler.get_status() if status < 400: log_method = logger.info elif status < 500: ...
Handle access log.
def add_static_path(self, prefix: str, path: str) -> None: pattern = prefix if not pattern.startswith('/'): pattern = '/' + pattern if not pattern.endswith('/(.*)'): pattern = pattern + '/(.*)' self.add_handlers( r'.*', # add static path for ...
Add path to serve static files. ``prefix`` is used for url prefix to serve static files and ``path`` is a path to the static file directory. ``prefix = '/_static'`` is reserved for the server, so do not use it for your app.
def add_favicon_path(self, path: str) -> None: spec = web.URLSpec( '/(favicon.ico)', StaticFileHandler, dict(path=path) ) # Need some check handlers = self.handlers[0][1] handlers.append(spec)
Add path to serve favicon file. ``path`` should be a directory, which contains favicon file (``favicon.ico``) for your app.
def _exec_action(self, method, type, chaincodeID, function, args, id, secure_context=None, confidentiality_level=CHAINCODE_CONFIDENTIAL_PUB, ...
Private method to implement the deploy, invoke and query actions Following http://www.jsonrpc.org/specification. :param method: Chaincode action to exec. MUST within DEFAULT_CHAINCODE_METHODS. :param type: chaincode language type: 1 for golang, 2 for node. :param chaincodeID: M...
def chaincode_deploy(self, chaincode_path=DEFAULT_CHAINCODE_PATH, type=CHAINCODE_LANG_GO, function=DEFAULT_CHAINCODE_INIT_FUNC, args=DEFAULT_CHAINCODE_INIT_ARGS, id=1, secure_context=None, confid...
POST host:port/chaincode { "jsonrpc": "2.0", "method": "deploy", "params": { "type": 1, "chaincodeID":{ "path":"github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02" }, "ctorMsg": { "fun...
def chaincode_query(self, chaincode_name, type=CHAINCODE_LANG_GO, function="query", args=["a"], id=1, secure_context=None, confidentiality_level=CHAINCODE_CONFIDENTIAL_PUB, metadata=None): ...
{ "jsonrpc": "2.0", "method": "query", "params": { "type": 1, "chaincodeID":{ "name":"52b0d803fc395b5e34d8d4a7cd69fb6aa00099b8fabed83504ac1c5d61a425aca5b3ad3bf96643ea4fdaac132c417c37b00f88fa800de7ece387d008a76d3586" }, ...
def get_connection(self, *args, **kwargs): conn = super(SSLAdapter, self).get_connection(*args, **kwargs) if conn.assert_hostname != self.assert_hostname: conn.assert_hostname = self.assert_hostname return conn
Ensure assert_hostname is set correctly on our pool We already take care of a normal poolmanager via init_poolmanager But we still need to take care of when there is a proxy poolmanager
def chain_list(self): res = self._get(self._url("/chain")) return self._result(res, True)
GET /chain Use the Chain API to retrieve the current state of the blockchain. The returned BlockchainInfo message is defined inside fabric.proto. message BlockchainInfo { uint64 height = 1; bytes currentBlockHash = 2; bytes previousBlockHash = 3; } ...
def peer_list(self): res = self._get(self._url("/network/peers")) return self._result(res, True)
GET /network/peers Use the Network APIs to retrieve information about the network of peer nodes comprising the blockchain network. ```golang message PeersMessage { repeated PeerEndpoint peers = 1; } message PeerEndpoint { PeerID ID = 1; ...
def transaction_get(self, tran_uuid): res = self._get(self._url("/transactions/{0}", tran_uuid)) return self._result(res, json=True)
GET /transactions/{UUID} Use the /transactions/{UUID} endpoint to retrieve an individual transaction matching the UUID from the blockchain. The returned transaction message is defined inside fabric.proto. ```golang message Transaction { enum Type { U...
def watch_dir(path: str) -> None: _compile_exclude_patterns() if config.autoreload or config.debug: # Add files to watch for autoreload p = pathlib.Path(path) p.resolve() _add_watch_path(p)
Add ``path`` to watch for autoreload.
def open_browser(url: str, browser: str = None) -> None: if '--open-browser' in sys.argv: # Remove open browser to prevent making new tab on autoreload sys.argv.remove('--open-browser') if browser is None: browser = config.browser if browser in _browsers: webbrowser.get(...
Open web browser.
def enrollmentID_get(self, enrollment_id): res = self._get(self._url("/registrar/{0}", enrollment_id)) return self._result(res, True)
GET /registrar/{enrollmentID} Use the Registrar APIs to manage end user registration with the CA. ```golang message Block { uint32 version = 1; google.protobuf.Timestamp Timestamp = 2; repeated Transaction transactions = 3; bytes stateHash = 4; ...
def parse_style_decl(style: str, owner: AbstractNode = None ) -> CSSStyleDeclaration: _style = CSSStyleDeclaration(style, owner=owner) return _style
Make CSSStyleDeclaration from style string. :arg AbstractNode owner: Owner of the style.
def parse_style_rules(styles: str) -> CSSRuleList: rules = CSSRuleList() for m in _style_rule_re.finditer(styles): rules.append(CSSStyleRule(m.group(1), parse_style_decl(m.group(2)))) return rules
Make CSSRuleList object from style string.
def cssText(self) -> str: text = '; '.join('{0}: {1}'.format(k, v) for k, v in self.items()) if text: text += ';' return text
String-representation.
def removeProperty(self, prop: str) -> str: removed_prop = self.get(prop) # removed_prop may be False or '', so need to check it is None if removed_prop is not None: del self[prop] return removed_prop
Remove the css property.
def setProperty(self, prop: str, value: str, priority: str = None ) -> None: self[prop] = value
Set property as the value. The third argument ``priority`` is not implemented yet.
def cssText(self) -> str: _style = self.style.cssText if _style: return '{0} {{{1}}}'.format(self.selectorText, _style) return ''
Return string representation of this rule.
def set_loglevel(level: Union[int, str, None] = None) -> None: if level is not None: lv = level_to_int(level) elif config.logging: lv = level_to_int(config.logging) elif config.debug: lv = logging.DEBUG else: lv = logging.INFO root_logger.setLevel(lv) _log_ha...
Set proper log-level. :arg Optional[int, str] level: Level to be set. If None, use proper log level from command line option. Default value is ``logging.INFO``.
def parse_command_line() -> Namespace: import tornado.options parser.parse_known_args(namespace=config) set_loglevel() # set new log level based on commanline option for k, v in vars(config).items(): if k.startswith('log'): tornado.options.options.__setattr__(k, v) return c...
Parse command line options and set them to ``config``. This function skips unknown command line options. After parsing options, set log level and set options in ``tornado.options``.
def suppress_logging() -> None: from wdom import options options.root_logger.removeHandler(options._log_handler) options.root_logger.addHandler(logging.NullHandler())
Suppress log output to stdout. This function is intended to be used in test's setup. This function removes log handler of ``wdom`` logger and set NullHandler to suppress log.
def reset() -> None: from wdom.document import get_new_document, set_document from wdom.element import Element from wdom.server import _tornado from wdom.window import customElements set_document(get_new_document()) _tornado.connections.clear() _tornado.set_application(_tornado.Applica...
Reset all wdom objects. This function clear all connections, elements, and resistered custom elements. This function also makes new document/application and set them.
def _ipaddress_match(ipname, host_ip): # OpenSSL may add a trailing newline to a subjectAltName's IP address ip = ipaddress.ip_address(six.text_type(ipname.rstrip())) return ip == host_ip
Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope").
def _dnsname_match(dn, hostname, max_wildcards=1): pats = [] if not dn: return False split_dn = dn.split(r'.') leftmost, remainder = split_dn[0], split_dn[1:] wildcards = leftmost.count('*') if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing...
Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3
def match_hostname(cert, hostname): if not cert: raise ValueError("empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " "CERT_OPTIONAL or CERT_REQUIRED") try: host_ip = ipaddress.ip_address(six.text_type...
Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing.
def _ensure_node(node: Union[str, AbstractNode]) -> AbstractNode: if isinstance(node, str): return Text(node) elif isinstance(node, Node): return node else: raise TypeError('Invalid type to append: {}'.format(node))
Ensure to be node. If ``node`` is string, convert it to ``Text`` node.
def previousSibling(self) -> Optional[AbstractNode]: parent = self.parentNode if parent is None: return None return parent.childNodes.item(parent.childNodes.index(self) - 1)
Return the previous sibling of this node. If there is no previous sibling, return ``None``.
def ownerDocument(self) -> Optional[AbstractNode]: if self.nodeType == Node.DOCUMENT_NODE: return self elif self.parentNode: return self.parentNode.ownerDocument return None
Return the owner document of this node. Owner document is an ancestor document node of this node. If this node (or node tree including this node) is not appended to any document node, this property returns ``None``. :rtype: Document or None
def index(self, node: AbstractNode) -> int: if node in self.childNodes: return self.childNodes.index(node) elif isinstance(node, Text): for i, n in enumerate(self.childNodes): # should consider multiple match? if isinstance(n, Text) and n....
Return index of the node. If the node is not a child of this node, raise ``ValueError``.
def insertBefore(self, node: AbstractNode, ref_node: AbstractNode) -> AbstractNode: return self._insert_before(node, ref_node)
Insert a node just before the reference node.
def replaceChild(self, new_child: AbstractNode, old_child: AbstractNode) -> AbstractNode: return self._replace_child(new_child, old_child)
Replace an old child with new child.
def cloneNode(self, deep: bool=False) -> AbstractNode: if deep: return self._clone_node_deep() return self._clone_node()
Return new copy of this node. If optional argument ``deep`` is specified and is True, new node has clones of child nodes of this node (if presents).
def item(self, index: int) -> Optional[Node]: if not isinstance(index, int): raise TypeError( 'Indeces must be integer, not {}'.format(type(index))) return self.__nodes[index] if 0 <= index < self.length else None
Return item with the index. If the index is negative number or out of the list, return None.
def namedItem(self, name: str) -> Optional[Node]: for n in self: if n.getAttribute('id') == name: return n for n in self: if n.getAttribute('name') == name: return n return None
TODO.
def children(self) -> NodeList: return NodeList([e for e in self.childNodes if e.nodeType == Node.ELEMENT_NODE])
Return list of child nodes. Currently this is not a live object.
def firstElementChild(self) -> Optional[AbstractNode]: for child in self.childNodes: if child.nodeType == Node.ELEMENT_NODE: return child return None
First Element child node. If this node has no element child, return None.
def lastElementChild(self) -> Optional[AbstractNode]: for child in reversed(self.childNodes): # type: ignore if child.nodeType == Node.ELEMENT_NODE: return child return None
Last Element child node. If this node has no element child, return None.
def prepend(self, *nodes: Union[str, AbstractNode]) -> None: node = _to_node_list(nodes) if self.firstChild: self.insertBefore(node, self.firstChild) else: self.appendChild(node)
Insert new nodes before first child node.
def append(self, *nodes: Union[AbstractNode, str]) -> None: node = _to_node_list(nodes) self.appendChild(node)
Append new nodes after last child node.
def nextElementSibling(self) -> Optional[AbstractNode]: if self.parentNode is None: return None siblings = self.parentNode.childNodes for i in range(siblings.index(self) + 1, len(siblings)): n = siblings[i] if n.nodeType == Node.ELEMENT_NODE: ...
Next Element Node. If this node has no next element node, return None.
def before(self, *nodes: Union[AbstractNode, str]) -> None: if self.parentNode: node = _to_node_list(nodes) self.parentNode.insertBefore(node, self)
Insert nodes before this node. If nodes contains ``str``, it will be converted to Text node.
def after(self, *nodes: Union[AbstractNode, str]) -> None: if self.parentNode: node = _to_node_list(nodes) _next_node = self.nextSibling if _next_node is None: self.parentNode.appendChild(node) else: self.parentNode.insertB...
Append nodes after this node. If nodes contains ``str``, it will be converted to Text node.
def replaceWith(self, *nodes: Union[AbstractNode, str]) -> None: if self.parentNode: node = _to_node_list(nodes) self.parentNode.replaceChild(node, self)
Replace this node with nodes. If nodes contains ``str``, it will be converted to Text node.
def insertData(self, offset: int, string: str) -> None: self._insert_data(offset, string)
Insert ``string`` at offset on this node.
def deleteData(self, offset: int, count: int) -> None: self._delete_data(offset, count)
Delete data by offset to count letters.
def replaceData(self, offset: int, count: int, string: str) -> None: self._replace_data(offset, count, string)
Replace data from offset to count by string.
def html(self) -> str: if self.parentNode and self.parentNode._should_escape_text: return html.escape(self.data) return self.data
Return html-escaped string representation of this node.
def create_event(msg: EventMsgDict) -> Event: proto = msg.get('proto', '') cls = proto_dict.get(proto, Event) e = cls(msg['type'], msg) return e
Create Event from JSOM msg and set target nodes. :arg EventTarget currentTarget: Current event target node. :arg EventTarget target: Node which emitted this event first. :arg dict init: Event options.
def getData(self, type: str) -> str: return self.__data.get(normalize_type(type), '')
Get data of type format. If this DataTransfer object does not have `type` data, return empty string. :arg str type: Data format of the data, like 'text/plain'.
def setData(self, type: str, data: str) -> None: type = normalize_type(type) if type in self.__data: del self.__data[type] self.__data[type] = data
Set data of type format. :arg str type: Data format of the data, like 'text/plain'.
def clearData(self, type: str = '') -> None: type = normalize_type(type) if not type: self.__data.clear() elif type in self.__data: del self.__data[type]
Remove data of type foramt. If type argument is omitted, remove all data.
def addEventListener(self, event: str, listener: _EventListenerType ) -> None: self._add_event_listener(event, listener)
Add event listener to this node. ``event`` is a string which determines the event type when the new listener called. Acceptable events are same as JavaScript, without ``on``. For example, to add a listener which is called when this node is clicked, event is ``'click``.
def removeEventListener(self, event: str, listener: _EventListenerType ) -> None: self._remove_event_listener(event, listener)
Remove an event listener of this node. The listener is removed only when both event type and listener is matched.
def on_response(self, msg: Dict[str, str]) -> None: response = msg.get('data', False) if response: task = self.__tasks.pop(msg.get('reqid'), False) if task and not task.cancelled() and not task.done(): task.set_result(msg.get('data'))
Run when get response from browser.
def js_exec(self, method: str, *args: Union[int, str, bool]) -> None: if self.connected: self.ws_send(dict(method=method, params=args))
Execute ``method`` in the related node on browser. Other keyword arguments are passed to ``params`` attribute. If this node is not in any document tree (namely, this node does not have parent node), the ``method`` is not executed.
def js_query(self, query: str) -> Awaitable: if self.connected: self.js_exec(query, self.__reqid) fut = Future() # type: Future[str] self.__tasks[self.__reqid] = fut self.__reqid += 1 return fut f = Future() # type: Future[None] ...
Send query to related DOM on browser. :param str query: single string which indicates query type.
def ws_send(self, obj: Dict[str, Union[Iterable[_T_MsgItem], _T_MsgItem]] ) -> None: from wdom import server if self.ownerDocument is not None: obj['target'] = 'node' obj['id'] = self.wdom_id server.push_message(obj)
Send ``obj`` as message to the related nodes on browser. :arg dict obj: Message is serialized by JSON object and send via WebSocket connection.
def generate_url(query, first, recent, country_code): query = '+'.join(query.split()) url = 'http://www.bing.com/search?q=' + query + '&first=' + first if recent in ['h', 'd', 'w', 'm', 'y']: # A True/False would be enough. This is just to maintain consistancy with google. url = url + '&filters...
(str, str) -> str A url in the required format is generated.
def generate_news_url(query, first, recent, country_code): query = '+'.join(query.split()) url = 'http://www.bing.com/news/search?q=' + query + '&first' + first if recent in ['h', 'd', 'w', 'm', 'y']: # A True/False would be enough. This is just to maintain consistancy with google. url = url + ...
(str, str) -> str A url in the required format is generated.
def try_cast_int(s): try: temp = re.findall('\d', str(s)) temp = ''.join(temp) return int(temp) except: return s
(str) -> int All the digits in a given string are concatenated and converted into a single number.
def generate_url(query, num, start, recent, country_code): query = '+'.join(query.split()) url = 'https://www.google.com/search?q=' + query + '&num=' + num + '&start=' + start if recent in ['h', 'd', 'w', 'm', 'y']: url += '&tbs=qdr:' + recent if country_code is not None: url += '&g...
(str, str, str) -> str A url in the required format is generated.
def estimate_cp(ts, method="mean", Q=1, penalty_value=0.175): """ ts: time series method: look for a single changepoint in 'mean' , 'var', 'mean and var' or use binary segmentatiom to detect multiple changepoints in mean (binseg). Q: Number of change po...
Estimate changepoints in a time series by using R.
def estimate_cp_pval(ts, method="mean"): """ ts: time series method: look for a single changepoint in 'mean' , 'var', 'mean and var' Returns: returns index of the changepoint, and pvalue. Here pvalue = 1 means statistically significant """ robjects.r("library(...
Estimate changepoints in a time series by using R.
def get_ts_stats_significance(self, x, ts, stat_ts_func, null_ts_func, B=1000, permute_fast=False, label_ts=''): stats_ts, pvals, nums = ts_stats_significance( ts, stat_ts_func, null_ts_func, B=B, permute_fast=permute_fast) return stats_ts, pvals, nums
Returns the statistics, pvalues and the actual number of bootstrap samples.