repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
quantmind/pulsar
pulsar/apps/wsgi/formdata.py
HttpBodyReader._waiting_expect
def _waiting_expect(self): '''``True`` when the client is waiting for 100 Continue. ''' if self._expect_sent is None: if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue': return True self._expect_sent = '' return False
python
def _waiting_expect(self): '''``True`` when the client is waiting for 100 Continue. ''' if self._expect_sent is None: if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue': return True self._expect_sent = '' return False
[ "def", "_waiting_expect", "(", "self", ")", ":", "if", "self", ".", "_expect_sent", "is", "None", ":", "if", "self", ".", "environ", ".", "get", "(", "'HTTP_EXPECT'", ",", "''", ")", ".", "lower", "(", ")", "==", "'100-continue'", ":", "return", "True"...
``True`` when the client is waiting for 100 Continue.
[ "True", "when", "the", "client", "is", "waiting", "for", "100", "Continue", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L82-L89
train
quantmind/pulsar
pulsar/apps/wsgi/formdata.py
MultipartPart.base64
def base64(self, charset=None): '''Data encoded as base 64''' return b64encode(self.bytes()).decode(charset or self.charset)
python
def base64(self, charset=None): '''Data encoded as base 64''' return b64encode(self.bytes()).decode(charset or self.charset)
[ "def", "base64", "(", "self", ",", "charset", "=", "None", ")", ":", "return", "b64encode", "(", "self", ".", "bytes", "(", ")", ")", ".", "decode", "(", "charset", "or", "self", ".", "charset", ")" ]
Data encoded as base 64
[ "Data", "encoded", "as", "base", "64" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L318-L320
train
quantmind/pulsar
pulsar/apps/wsgi/formdata.py
MultipartPart.feed_data
def feed_data(self, data): """Feed new data into the MultiPart parser or the data stream""" if data: self._bytes.append(data) if self.parser.stream: self.parser.stream(self) else: self.parser.buffer.extend(data)
python
def feed_data(self, data): """Feed new data into the MultiPart parser or the data stream""" if data: self._bytes.append(data) if self.parser.stream: self.parser.stream(self) else: self.parser.buffer.extend(data)
[ "def", "feed_data", "(", "self", ",", "data", ")", ":", "if", "data", ":", "self", ".", "_bytes", ".", "append", "(", "data", ")", "if", "self", ".", "parser", ".", "stream", ":", "self", ".", "parser", ".", "stream", "(", "self", ")", "else", ":...
Feed new data into the MultiPart parser or the data stream
[ "Feed", "new", "data", "into", "the", "MultiPart", "parser", "or", "the", "data", "stream" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L329-L336
train
quantmind/pulsar
examples/proxyserver/manage.py
server
def server(name='proxy-server', headers_middleware=None, server_software=None, **kwargs): '''Function to Create a WSGI Proxy Server.''' if headers_middleware is None: headers_middleware = [x_forwarded_for] wsgi_proxy = ProxyServerWsgiHandler(headers_middleware) kwargs['server_software'] = server_software or SERVER_SOFTWARE return wsgi.WSGIServer(wsgi_proxy, name=name, **kwargs)
python
def server(name='proxy-server', headers_middleware=None, server_software=None, **kwargs): '''Function to Create a WSGI Proxy Server.''' if headers_middleware is None: headers_middleware = [x_forwarded_for] wsgi_proxy = ProxyServerWsgiHandler(headers_middleware) kwargs['server_software'] = server_software or SERVER_SOFTWARE return wsgi.WSGIServer(wsgi_proxy, name=name, **kwargs)
[ "def", "server", "(", "name", "=", "'proxy-server'", ",", "headers_middleware", "=", "None", ",", "server_software", "=", "None", ",", "**", "kwargs", ")", ":", "if", "headers_middleware", "is", "None", ":", "headers_middleware", "=", "[", "x_forwarded_for", "...
Function to Create a WSGI Proxy Server.
[ "Function", "to", "Create", "a", "WSGI", "Proxy", "Server", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L241-L248
train
quantmind/pulsar
examples/proxyserver/manage.py
TunnelResponse.request
async def request(self): '''Perform the Http request to the upstream server ''' request_headers = self.request_headers() environ = self.environ method = environ['REQUEST_METHOD'] data = None if method in ENCODE_BODY_METHODS: data = DataIterator(self) http = self.wsgi.http_client try: await http.request(method, environ['RAW_URI'], data=data, headers=request_headers, version=environ['SERVER_PROTOCOL'], pre_request=self.pre_request) except Exception as exc: self.error(exc)
python
async def request(self): '''Perform the Http request to the upstream server ''' request_headers = self.request_headers() environ = self.environ method = environ['REQUEST_METHOD'] data = None if method in ENCODE_BODY_METHODS: data = DataIterator(self) http = self.wsgi.http_client try: await http.request(method, environ['RAW_URI'], data=data, headers=request_headers, version=environ['SERVER_PROTOCOL'], pre_request=self.pre_request) except Exception as exc: self.error(exc)
[ "async", "def", "request", "(", "self", ")", ":", "request_headers", "=", "self", ".", "request_headers", "(", ")", "environ", "=", "self", ".", "environ", "method", "=", "environ", "[", "'REQUEST_METHOD'", "]", "data", "=", "None", "if", "method", "in", ...
Perform the Http request to the upstream server
[ "Perform", "the", "Http", "request", "to", "the", "upstream", "server" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L112-L130
train
quantmind/pulsar
examples/proxyserver/manage.py
TunnelResponse.pre_request
def pre_request(self, response, exc=None): """Start the tunnel. This is a callback fired once a connection with upstream server is established. """ if response.request.method == 'CONNECT': self.start_response( '200 Connection established', [('content-length', '0')] ) # send empty byte so that headers are sent self.future.set_result([b'']) # proxy - server connection upstream = response.connection # client - proxy connection dostream = self.connection # Upgrade downstream connection dostream.upgrade(partial(StreamTunnel.create, upstream)) # # upstream upgrade upstream.upgrade(partial(StreamTunnel.create, dostream)) response.fire_event('post_request') # abort the event raise AbortEvent else: response.event('data_processed').bind(self.data_processed) response.event('post_request').bind(self.post_request)
python
def pre_request(self, response, exc=None): """Start the tunnel. This is a callback fired once a connection with upstream server is established. """ if response.request.method == 'CONNECT': self.start_response( '200 Connection established', [('content-length', '0')] ) # send empty byte so that headers are sent self.future.set_result([b'']) # proxy - server connection upstream = response.connection # client - proxy connection dostream = self.connection # Upgrade downstream connection dostream.upgrade(partial(StreamTunnel.create, upstream)) # # upstream upgrade upstream.upgrade(partial(StreamTunnel.create, dostream)) response.fire_event('post_request') # abort the event raise AbortEvent else: response.event('data_processed').bind(self.data_processed) response.event('post_request').bind(self.post_request)
[ "def", "pre_request", "(", "self", ",", "response", ",", "exc", "=", "None", ")", ":", "if", "response", ".", "request", ".", "method", "==", "'CONNECT'", ":", "self", ".", "start_response", "(", "'200 Connection established'", ",", "[", "(", "'content-lengt...
Start the tunnel. This is a callback fired once a connection with upstream server is established.
[ "Start", "the", "tunnel", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L157-L184
train
quantmind/pulsar
pulsar/utils/pylib/protocols.py
Protocol.connection_lost
def connection_lost(self, exc=None): """Fires the ``connection_lost`` event. """ if self._loop.get_debug(): self.producer.logger.debug('connection lost %s', self) self.event('connection_lost').fire(exc=exc)
python
def connection_lost(self, exc=None): """Fires the ``connection_lost`` event. """ if self._loop.get_debug(): self.producer.logger.debug('connection lost %s', self) self.event('connection_lost').fire(exc=exc)
[ "def", "connection_lost", "(", "self", ",", "exc", "=", "None", ")", ":", "if", "self", ".", "_loop", ".", "get_debug", "(", ")", ":", "self", ".", "producer", ".", "logger", ".", "debug", "(", "'connection lost %s'", ",", "self", ")", "self", ".", "...
Fires the ``connection_lost`` event.
[ "Fires", "the", "connection_lost", "event", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/protocols.py#L163-L168
train
quantmind/pulsar
pulsar/utils/pylib/protocols.py
ProtocolConsumer.start
def start(self, request=None): """Starts processing the request for this protocol consumer. There is no need to override this method, implement :meth:`start_request` instead. If either :attr:`connection` or :attr:`transport` are missing, a :class:`RuntimeError` occurs. For server side consumer, this method simply fires the ``pre_request`` event. """ self.connection.processed += 1 self.producer.requests_processed += 1 self.event('post_request').bind(self.finished_reading) self.request = request or self.create_request() try: self.fire_event('pre_request') except AbortEvent: if self._loop.get_debug(): self.producer.logger.debug('Abort request %s', request) else: self.start_request()
python
def start(self, request=None): """Starts processing the request for this protocol consumer. There is no need to override this method, implement :meth:`start_request` instead. If either :attr:`connection` or :attr:`transport` are missing, a :class:`RuntimeError` occurs. For server side consumer, this method simply fires the ``pre_request`` event. """ self.connection.processed += 1 self.producer.requests_processed += 1 self.event('post_request').bind(self.finished_reading) self.request = request or self.create_request() try: self.fire_event('pre_request') except AbortEvent: if self._loop.get_debug(): self.producer.logger.debug('Abort request %s', request) else: self.start_request()
[ "def", "start", "(", "self", ",", "request", "=", "None", ")", ":", "self", ".", "connection", ".", "processed", "+=", "1", "self", ".", "producer", ".", "requests_processed", "+=", "1", "self", ".", "event", "(", "'post_request'", ")", ".", "bind", "(...
Starts processing the request for this protocol consumer. There is no need to override this method, implement :meth:`start_request` instead. If either :attr:`connection` or :attr:`transport` are missing, a :class:`RuntimeError` occurs. For server side consumer, this method simply fires the ``pre_request`` event.
[ "Starts", "processing", "the", "request", "for", "this", "protocol", "consumer", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/protocols.py#L216-L237
train
quantmind/pulsar
pulsar/utils/log.py
process_global
def process_global(name, val=None, setval=False): '''Access and set global variables for the current process.''' p = current_process() if not hasattr(p, '_pulsar_globals'): p._pulsar_globals = {'lock': Lock()} if setval: p._pulsar_globals[name] = val else: return p._pulsar_globals.get(name)
python
def process_global(name, val=None, setval=False): '''Access and set global variables for the current process.''' p = current_process() if not hasattr(p, '_pulsar_globals'): p._pulsar_globals = {'lock': Lock()} if setval: p._pulsar_globals[name] = val else: return p._pulsar_globals.get(name)
[ "def", "process_global", "(", "name", ",", "val", "=", "None", ",", "setval", "=", "False", ")", ":", "p", "=", "current_process", "(", ")", "if", "not", "hasattr", "(", "p", ",", "'_pulsar_globals'", ")", ":", "p", ".", "_pulsar_globals", "=", "{", ...
Access and set global variables for the current process.
[ "Access", "and", "set", "global", "variables", "for", "the", "current", "process", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/log.py#L213-L221
train
quantmind/pulsar
pulsar/utils/httpurl.py
get_environ_proxies
def get_environ_proxies(): """Return a dict of environment proxies. From requests_.""" proxy_keys = [ 'all', 'http', 'https', 'ftp', 'socks', 'ws', 'wss', 'no' ] def get_proxy(k): return os.environ.get(k) or os.environ.get(k.upper()) proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys] return dict([(key, val) for (key, val) in proxies if val])
python
def get_environ_proxies(): """Return a dict of environment proxies. From requests_.""" proxy_keys = [ 'all', 'http', 'https', 'ftp', 'socks', 'ws', 'wss', 'no' ] def get_proxy(k): return os.environ.get(k) or os.environ.get(k.upper()) proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys] return dict([(key, val) for (key, val) in proxies if val])
[ "def", "get_environ_proxies", "(", ")", ":", "proxy_keys", "=", "[", "'all'", ",", "'http'", ",", "'https'", ",", "'ftp'", ",", "'socks'", ",", "'ws'", ",", "'wss'", ",", "'no'", "]", "def", "get_proxy", "(", "k", ")", ":", "return", "os", ".", "envi...
Return a dict of environment proxies. From requests_.
[ "Return", "a", "dict", "of", "environment", "proxies", ".", "From", "requests_", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L310-L328
train
quantmind/pulsar
pulsar/utils/httpurl.py
has_vary_header
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set([header.lower() for header in vary_headers]) return header_query.lower() in existing_headers
python
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set([header.lower() for header in vary_headers]) return header_query.lower() in existing_headers
[ "def", "has_vary_header", "(", "response", ",", "header_query", ")", ":", "if", "not", "response", ".", "has_header", "(", "'Vary'", ")", ":", "return", "False", "vary_headers", "=", "cc_delim_re", ".", "split", "(", "response", "[", "'Vary'", "]", ")", "e...
Checks to see if the response has a given header name in its Vary header.
[ "Checks", "to", "see", "if", "the", "response", "has", "a", "given", "header", "name", "in", "its", "Vary", "header", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L475-L483
train
quantmind/pulsar
pulsar/apps/ds/client.py
PulsarStoreClient.execute
def execute(self, request): '''Execute a new ``request``. ''' handle = None if request: request[0] = command = to_string(request[0]).lower() info = COMMANDS_INFO.get(command) if info: handle = getattr(self.store, info.method_name) # if self.channels or self.patterns: if command not in self.store.SUBSCRIBE_COMMANDS: return self.reply_error(self.store.PUBSUB_ONLY) if self.blocked: return self.reply_error('Blocked client cannot request') if self.transaction is not None and command not in 'exec': self.transaction.append((handle, request)) return self.connection.write(self.store.QUEUED) self.execute_command(handle, request)
python
def execute(self, request): '''Execute a new ``request``. ''' handle = None if request: request[0] = command = to_string(request[0]).lower() info = COMMANDS_INFO.get(command) if info: handle = getattr(self.store, info.method_name) # if self.channels or self.patterns: if command not in self.store.SUBSCRIBE_COMMANDS: return self.reply_error(self.store.PUBSUB_ONLY) if self.blocked: return self.reply_error('Blocked client cannot request') if self.transaction is not None and command not in 'exec': self.transaction.append((handle, request)) return self.connection.write(self.store.QUEUED) self.execute_command(handle, request)
[ "def", "execute", "(", "self", ",", "request", ")", ":", "handle", "=", "None", "if", "request", ":", "request", "[", "0", "]", "=", "command", "=", "to_string", "(", "request", "[", "0", "]", ")", ".", "lower", "(", ")", "info", "=", "COMMANDS_INF...
Execute a new ``request``.
[ "Execute", "a", "new", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ds/client.py#L65-L83
train
quantmind/pulsar
pulsar/apps/http/plugins.py
handle_cookies
def handle_cookies(response, exc=None): '''Handle response cookies. ''' if exc: return headers = response.headers request = response.request client = request.client response._cookies = c = SimpleCookie() if 'set-cookie' in headers or 'set-cookie2' in headers: for cookie in (headers.get('set-cookie2'), headers.get('set-cookie')): if cookie: c.load(cookie) if client.store_cookies: client.cookies.extract_cookies(response, request)
python
def handle_cookies(response, exc=None): '''Handle response cookies. ''' if exc: return headers = response.headers request = response.request client = request.client response._cookies = c = SimpleCookie() if 'set-cookie' in headers or 'set-cookie2' in headers: for cookie in (headers.get('set-cookie2'), headers.get('set-cookie')): if cookie: c.load(cookie) if client.store_cookies: client.cookies.extract_cookies(response, request)
[ "def", "handle_cookies", "(", "response", ",", "exc", "=", "None", ")", ":", "if", "exc", ":", "return", "headers", "=", "response", ".", "headers", "request", "=", "response", ".", "request", "client", "=", "request", ".", "client", "response", ".", "_c...
Handle response cookies.
[ "Handle", "response", "cookies", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/plugins.py#L191-L206
train
quantmind/pulsar
pulsar/apps/http/plugins.py
WebSocket.on_headers
def on_headers(self, response, exc=None): '''Websocket upgrade as ``on_headers`` event.''' if response.status_code == 101: connection = response.connection request = response.request handler = request.websocket_handler if not handler: handler = WS() parser = request.client.frame_parser(kind=1) consumer = partial(WebSocketClient.create, response, handler, parser) connection.upgrade(consumer) response.event('post_request').fire() websocket = connection.current_consumer() response.request_again = lambda r: websocket
python
def on_headers(self, response, exc=None): '''Websocket upgrade as ``on_headers`` event.''' if response.status_code == 101: connection = response.connection request = response.request handler = request.websocket_handler if not handler: handler = WS() parser = request.client.frame_parser(kind=1) consumer = partial(WebSocketClient.create, response, handler, parser) connection.upgrade(consumer) response.event('post_request').fire() websocket = connection.current_consumer() response.request_again = lambda r: websocket
[ "def", "on_headers", "(", "self", ",", "response", ",", "exc", "=", "None", ")", ":", "if", "response", ".", "status_code", "==", "101", ":", "connection", "=", "response", ".", "connection", "request", "=", "response", ".", "request", "handler", "=", "r...
Websocket upgrade as ``on_headers`` event.
[ "Websocket", "upgrade", "as", "on_headers", "event", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/plugins.py#L230-L245
train
quantmind/pulsar
pulsar/utils/path.py
Path.add2python
def add2python(self, module=None, up=0, down=None, front=False, must_exist=True): '''Add a directory to the python path. :parameter module: Optional module name to try to import once we have found the directory :parameter up: number of level to go up the directory three from :attr:`local_path`. :parameter down: Optional tuple of directory names to travel down once we have gone *up* levels. :parameter front: Boolean indicating if we want to insert the new path at the front of ``sys.path`` using ``sys.path.insert(0,path)``. :parameter must_exist: Boolean indicating if the module must exists. ''' if module: try: return import_module(module) except ImportError: pass dir = self.dir().ancestor(up) if down: dir = dir.join(*down) if dir.isdir(): if dir not in sys.path: if front: sys.path.insert(0, dir) else: sys.path.append(dir) elif must_exist: raise ImportError('Directory {0} not available'.format(dir)) else: return None if module: try: return import_module(module) except ImportError: if must_exist: raise
python
def add2python(self, module=None, up=0, down=None, front=False, must_exist=True): '''Add a directory to the python path. :parameter module: Optional module name to try to import once we have found the directory :parameter up: number of level to go up the directory three from :attr:`local_path`. :parameter down: Optional tuple of directory names to travel down once we have gone *up* levels. :parameter front: Boolean indicating if we want to insert the new path at the front of ``sys.path`` using ``sys.path.insert(0,path)``. :parameter must_exist: Boolean indicating if the module must exists. ''' if module: try: return import_module(module) except ImportError: pass dir = self.dir().ancestor(up) if down: dir = dir.join(*down) if dir.isdir(): if dir not in sys.path: if front: sys.path.insert(0, dir) else: sys.path.append(dir) elif must_exist: raise ImportError('Directory {0} not available'.format(dir)) else: return None if module: try: return import_module(module) except ImportError: if must_exist: raise
[ "def", "add2python", "(", "self", ",", "module", "=", "None", ",", "up", "=", "0", ",", "down", "=", "None", ",", "front", "=", "False", ",", "must_exist", "=", "True", ")", ":", "if", "module", ":", "try", ":", "return", "import_module", "(", "mod...
Add a directory to the python path. :parameter module: Optional module name to try to import once we have found the directory :parameter up: number of level to go up the directory three from :attr:`local_path`. :parameter down: Optional tuple of directory names to travel down once we have gone *up* levels. :parameter front: Boolean indicating if we want to insert the new path at the front of ``sys.path`` using ``sys.path.insert(0,path)``. :parameter must_exist: Boolean indicating if the module must exists.
[ "Add", "a", "directory", "to", "the", "python", "path", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/path.py#L79-L117
train
quantmind/pulsar
examples/httpbin/manage.py
HttpBin.get
def get(self, request): '''The home page of this router''' ul = Html('ul') for router in sorted(self.routes, key=lambda r: r.creation_count): a = router.link(escape(router.route.path)) a.addClass(router.name) for method in METHODS: if router.getparam(method): a.addClass(method) li = Html('li', a, ' %s' % router.getparam('title', '')) ul.append(li) title = 'Pulsar' html = request.html_document html.head.title = title html.head.links.append('httpbin.css') html.head.links.append('favicon.ico', rel="icon", type='image/x-icon') html.head.scripts.append('httpbin.js') ul = ul.to_string(request) templ = asset('template.html') body = templ % (title, JAPANESE, CHINESE, version, pyversion, ul) html.body.append(body) return html.http_response(request)
python
def get(self, request): '''The home page of this router''' ul = Html('ul') for router in sorted(self.routes, key=lambda r: r.creation_count): a = router.link(escape(router.route.path)) a.addClass(router.name) for method in METHODS: if router.getparam(method): a.addClass(method) li = Html('li', a, ' %s' % router.getparam('title', '')) ul.append(li) title = 'Pulsar' html = request.html_document html.head.title = title html.head.links.append('httpbin.css') html.head.links.append('favicon.ico', rel="icon", type='image/x-icon') html.head.scripts.append('httpbin.js') ul = ul.to_string(request) templ = asset('template.html') body = templ % (title, JAPANESE, CHINESE, version, pyversion, ul) html.body.append(body) return html.http_response(request)
[ "def", "get", "(", "self", ",", "request", ")", ":", "ul", "=", "Html", "(", "'ul'", ")", "for", "router", "in", "sorted", "(", "self", ".", "routes", ",", "key", "=", "lambda", "r", ":", "r", ".", "creation_count", ")", ":", "a", "=", "router", ...
The home page of this router
[ "The", "home", "page", "of", "this", "router" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/httpbin/manage.py#L106-L127
train
quantmind/pulsar
examples/httpbin/manage.py
HttpBin.stats
def stats(self, request): '''Live stats for the server. Try sending lots of requests ''' # scheme = 'wss' if request.is_secure else 'ws' # host = request.get('HTTP_HOST') # address = '%s://%s/stats' % (scheme, host) doc = HtmlDocument(title='Live server stats', media_path='/assets/') # docs.head.scripts return doc.http_response(request)
python
def stats(self, request): '''Live stats for the server. Try sending lots of requests ''' # scheme = 'wss' if request.is_secure else 'ws' # host = request.get('HTTP_HOST') # address = '%s://%s/stats' % (scheme, host) doc = HtmlDocument(title='Live server stats', media_path='/assets/') # docs.head.scripts return doc.http_response(request)
[ "def", "stats", "(", "self", ",", "request", ")", ":", "doc", "=", "HtmlDocument", "(", "title", "=", "'Live server stats'", ",", "media_path", "=", "'/assets/'", ")", "return", "doc", ".", "http_response", "(", "request", ")" ]
Live stats for the server. Try sending lots of requests
[ "Live", "stats", "for", "the", "server", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/httpbin/manage.py#L273-L283
train
quantmind/pulsar
pulsar/utils/system/winprocess.py
get_preparation_data
def get_preparation_data(name): ''' Return info about parent needed by child to unpickle process object. Monkey-patch from ''' d = dict( name=name, sys_path=sys.path, sys_argv=sys.argv, log_to_stderr=_log_to_stderr, orig_dir=process.ORIGINAL_DIR, authkey=process.current_process().authkey, ) if _logger is not None: d['log_level'] = _logger.getEffectiveLevel() if not WINEXE: main_path = getattr(sys.modules['__main__'], '__file__', None) if not main_path and sys.argv[0] not in ('', '-c'): main_path = sys.argv[0] if main_path is not None: if (not os.path.isabs(main_path) and process.ORIGINAL_DIR is not None): main_path = os.path.join(process.ORIGINAL_DIR, main_path) if not main_path.endswith('.exe'): d['main_path'] = os.path.normpath(main_path) return d
python
def get_preparation_data(name): ''' Return info about parent needed by child to unpickle process object. Monkey-patch from ''' d = dict( name=name, sys_path=sys.path, sys_argv=sys.argv, log_to_stderr=_log_to_stderr, orig_dir=process.ORIGINAL_DIR, authkey=process.current_process().authkey, ) if _logger is not None: d['log_level'] = _logger.getEffectiveLevel() if not WINEXE: main_path = getattr(sys.modules['__main__'], '__file__', None) if not main_path and sys.argv[0] not in ('', '-c'): main_path = sys.argv[0] if main_path is not None: if (not os.path.isabs(main_path) and process.ORIGINAL_DIR is not None): main_path = os.path.join(process.ORIGINAL_DIR, main_path) if not main_path.endswith('.exe'): d['main_path'] = os.path.normpath(main_path) return d
[ "def", "get_preparation_data", "(", "name", ")", ":", "d", "=", "dict", "(", "name", "=", "name", ",", "sys_path", "=", "sys", ".", "path", ",", "sys_argv", "=", "sys", ".", "argv", ",", "log_to_stderr", "=", "_log_to_stderr", ",", "orig_dir", "=", "pr...
Return info about parent needed by child to unpickle process object. Monkey-patch from
[ "Return", "info", "about", "parent", "needed", "by", "child", "to", "unpickle", "process", "object", ".", "Monkey", "-", "patch", "from" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/winprocess.py#L9-L37
train
quantmind/pulsar
examples/snippets/remote.py
remote_call
def remote_call(request, cls, method, args, kw): '''Command for executing remote calls on a remote object ''' actor = request.actor name = 'remote_%s' % cls.__name__ if not hasattr(actor, name): object = cls(actor) setattr(actor, name, object) else: object = getattr(actor, name) method_name = '%s%s' % (PREFIX, method) return getattr(object, method_name)(request, *args, **kw)
python
def remote_call(request, cls, method, args, kw): '''Command for executing remote calls on a remote object ''' actor = request.actor name = 'remote_%s' % cls.__name__ if not hasattr(actor, name): object = cls(actor) setattr(actor, name, object) else: object = getattr(actor, name) method_name = '%s%s' % (PREFIX, method) return getattr(object, method_name)(request, *args, **kw)
[ "def", "remote_call", "(", "request", ",", "cls", ",", "method", ",", "args", ",", "kw", ")", ":", "actor", "=", "request", ".", "actor", "name", "=", "'remote_%s'", "%", "cls", ".", "__name__", "if", "not", "hasattr", "(", "actor", ",", "name", ")",...
Command for executing remote calls on a remote object
[ "Command", "for", "executing", "remote", "calls", "on", "a", "remote", "object" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/snippets/remote.py#L8-L19
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.clear
def clear(self): '''Clear the container from all data.''' self._size = 0 self._level = 1 self._head = Node('HEAD', None, [None]*SKIPLIST_MAXLEVEL, [1]*SKIPLIST_MAXLEVEL)
python
def clear(self): '''Clear the container from all data.''' self._size = 0 self._level = 1 self._head = Node('HEAD', None, [None]*SKIPLIST_MAXLEVEL, [1]*SKIPLIST_MAXLEVEL)
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_size", "=", "0", "self", ".", "_level", "=", "1", "self", ".", "_head", "=", "Node", "(", "'HEAD'", ",", "None", ",", "[", "None", "]", "*", "SKIPLIST_MAXLEVEL", ",", "[", "1", "]", "*", "SK...
Clear the container from all data.
[ "Clear", "the", "container", "from", "all", "data", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L55-L61
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.extend
def extend(self, iterable): '''Extend this skiplist with an iterable over ``score``, ``value`` pairs. ''' i = self.insert for score_values in iterable: i(*score_values)
python
def extend(self, iterable): '''Extend this skiplist with an iterable over ``score``, ``value`` pairs. ''' i = self.insert for score_values in iterable: i(*score_values)
[ "def", "extend", "(", "self", ",", "iterable", ")", ":", "i", "=", "self", ".", "insert", "for", "score_values", "in", "iterable", ":", "i", "(", "*", "score_values", ")" ]
Extend this skiplist with an iterable over ``score``, ``value`` pairs.
[ "Extend", "this", "skiplist", "with", "an", "iterable", "over", "score", "value", "pairs", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L63-L69
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.remove_range
def remove_range(self, start, end, callback=None): '''Remove a range by rank. This is equivalent to perform:: del l[start:end] on a python list. It returns the number of element removed. ''' N = len(self) if start < 0: start = max(N + start, 0) if start >= N: return 0 if end is None: end = N elif end < 0: end = max(N + end, 0) else: end = min(end, N) if start >= end: return 0 node = self._head index = 0 chain = [None] * self._level for i in range(self._level-1, -1, -1): while node.next[i] and (index + node.width[i]) <= start: index += node.width[i] node = node.next[i] chain[i] = node node = node.next[0] initial = self._size while node and index < end: next = node.next[0] self._remove_node(node, chain) index += 1 if callback: callback(node.score, node.value) node = next return initial - self._size
python
def remove_range(self, start, end, callback=None): '''Remove a range by rank. This is equivalent to perform:: del l[start:end] on a python list. It returns the number of element removed. ''' N = len(self) if start < 0: start = max(N + start, 0) if start >= N: return 0 if end is None: end = N elif end < 0: end = max(N + end, 0) else: end = min(end, N) if start >= end: return 0 node = self._head index = 0 chain = [None] * self._level for i in range(self._level-1, -1, -1): while node.next[i] and (index + node.width[i]) <= start: index += node.width[i] node = node.next[i] chain[i] = node node = node.next[0] initial = self._size while node and index < end: next = node.next[0] self._remove_node(node, chain) index += 1 if callback: callback(node.score, node.value) node = next return initial - self._size
[ "def", "remove_range", "(", "self", ",", "start", ",", "end", ",", "callback", "=", "None", ")", ":", "N", "=", "len", "(", "self", ")", "if", "start", "<", "0", ":", "start", "=", "max", "(", "N", "+", "start", ",", "0", ")", "if", "start", ...
Remove a range by rank. This is equivalent to perform:: del l[start:end] on a python list. It returns the number of element removed.
[ "Remove", "a", "range", "by", "rank", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L184-L224
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.remove_range_by_score
def remove_range_by_score(self, minval, maxval, include_min=True, include_max=True, callback=None): '''Remove a range with scores between ``minval`` and ``maxval``. :param minval: the start value of the range to remove :param maxval: the end value of the range to remove :param include_min: whether or not to include ``minval`` in the values to remove :param include_max: whether or not to include ``maxval`` in the scores to to remove :param callback: optional callback function invoked for each score, value pair removed. :return: the number of elements removed. ''' node = self._head chain = [None] * self._level if include_min: for i in range(self._level-1, -1, -1): while node.next[i] and node.next[i].score < minval: node = node.next[i] chain[i] = node else: for i in range(self._level-1, -1, -1): while node.next[i] and node.next[i].score <= minval: node = node.next[i] chain[i] = node node = node.next[0] initial = self._size while node and node.score >= minval: if ((include_max and node.score > maxval) or (not include_max and node.score >= maxval)): break next = node.next[0] self._remove_node(node, chain) if callback: callback(node.score, node.value) node = next return initial - self._size
python
def remove_range_by_score(self, minval, maxval, include_min=True, include_max=True, callback=None): '''Remove a range with scores between ``minval`` and ``maxval``. :param minval: the start value of the range to remove :param maxval: the end value of the range to remove :param include_min: whether or not to include ``minval`` in the values to remove :param include_max: whether or not to include ``maxval`` in the scores to to remove :param callback: optional callback function invoked for each score, value pair removed. :return: the number of elements removed. ''' node = self._head chain = [None] * self._level if include_min: for i in range(self._level-1, -1, -1): while node.next[i] and node.next[i].score < minval: node = node.next[i] chain[i] = node else: for i in range(self._level-1, -1, -1): while node.next[i] and node.next[i].score <= minval: node = node.next[i] chain[i] = node node = node.next[0] initial = self._size while node and node.score >= minval: if ((include_max and node.score > maxval) or (not include_max and node.score >= maxval)): break next = node.next[0] self._remove_node(node, chain) if callback: callback(node.score, node.value) node = next return initial - self._size
[ "def", "remove_range_by_score", "(", "self", ",", "minval", ",", "maxval", ",", "include_min", "=", "True", ",", "include_max", "=", "True", ",", "callback", "=", "None", ")", ":", "node", "=", "self", ".", "_head", "chain", "=", "[", "None", "]", "*",...
Remove a range with scores between ``minval`` and ``maxval``. :param minval: the start value of the range to remove :param maxval: the end value of the range to remove :param include_min: whether or not to include ``minval`` in the values to remove :param include_max: whether or not to include ``maxval`` in the scores to to remove :param callback: optional callback function invoked for each score, value pair removed. :return: the number of elements removed.
[ "Remove", "a", "range", "with", "scores", "between", "minval", "and", "maxval", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L226-L263
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.count
def count(self, minval, maxval, include_min=True, include_max=True): '''Returns the number of elements in the skiplist with a score between min and max. ''' rank1 = self.rank(minval) if rank1 < 0: rank1 = -rank1 - 1 elif not include_min: rank1 += 1 rank2 = self.rank(maxval) if rank2 < 0: rank2 = -rank2 - 1 elif include_max: rank2 += 1 return max(rank2 - rank1, 0)
python
def count(self, minval, maxval, include_min=True, include_max=True): '''Returns the number of elements in the skiplist with a score between min and max. ''' rank1 = self.rank(minval) if rank1 < 0: rank1 = -rank1 - 1 elif not include_min: rank1 += 1 rank2 = self.rank(maxval) if rank2 < 0: rank2 = -rank2 - 1 elif include_max: rank2 += 1 return max(rank2 - rank1, 0)
[ "def", "count", "(", "self", ",", "minval", ",", "maxval", ",", "include_min", "=", "True", ",", "include_max", "=", "True", ")", ":", "rank1", "=", "self", ".", "rank", "(", "minval", ")", "if", "rank1", "<", "0", ":", "rank1", "=", "-", "rank1", ...
Returns the number of elements in the skiplist with a score between min and max.
[ "Returns", "the", "number", "of", "elements", "in", "the", "skiplist", "with", "a", "score", "between", "min", "and", "max", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L265-L279
train
quantmind/pulsar
pulsar/apps/wsgi/structures.py
Accept.quality
def quality(self, key): """Returns the quality of the key. .. versionadded:: 0.6 In previous versions you had to use the item-lookup syntax (eg: ``obj[key]`` instead of ``obj.quality(key)``) """ for item, quality in self: if self._value_matches(key, item): return quality return 0
python
def quality(self, key): """Returns the quality of the key. .. versionadded:: 0.6 In previous versions you had to use the item-lookup syntax (eg: ``obj[key]`` instead of ``obj.quality(key)``) """ for item, quality in self: if self._value_matches(key, item): return quality return 0
[ "def", "quality", "(", "self", ",", "key", ")", ":", "for", "item", ",", "quality", "in", "self", ":", "if", "self", ".", "_value_matches", "(", "key", ",", "item", ")", ":", "return", "quality", "return", "0" ]
Returns the quality of the key. .. versionadded:: 0.6 In previous versions you had to use the item-lookup syntax (eg: ``obj[key]`` instead of ``obj.quality(key)``)
[ "Returns", "the", "quality", "of", "the", "key", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L54-L64
train
quantmind/pulsar
pulsar/apps/wsgi/structures.py
Accept.to_header
def to_header(self): """Convert the header set into an HTTP header string.""" result = [] for value, quality in self: if quality != 1: value = '%s;q=%s' % (value, quality) result.append(value) return ','.join(result)
python
def to_header(self): """Convert the header set into an HTTP header string.""" result = [] for value, quality in self: if quality != 1: value = '%s;q=%s' % (value, quality) result.append(value) return ','.join(result)
[ "def", "to_header", "(", "self", ")", ":", "result", "=", "[", "]", "for", "value", ",", "quality", "in", "self", ":", "if", "quality", "!=", "1", ":", "value", "=", "'%s;q=%s'", "%", "(", "value", ",", "quality", ")", "result", ".", "append", "(",...
Convert the header set into an HTTP header string.
[ "Convert", "the", "header", "set", "into", "an", "HTTP", "header", "string", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L109-L116
train
quantmind/pulsar
pulsar/apps/wsgi/structures.py
Accept.best_match
def best_match(self, matches, default=None): """Returns the best match from a list of possible matches based on the quality of the client. If two items have the same quality, the one is returned that comes first. :param matches: a list of matches to check for :param default: the value that is returned if none match """ if matches: best_quality = -1 result = default for client_item, quality in self: for server_item in matches: if quality <= best_quality: break if self._value_matches(server_item, client_item): best_quality = quality result = server_item return result else: return self.best
python
def best_match(self, matches, default=None): """Returns the best match from a list of possible matches based on the quality of the client. If two items have the same quality, the one is returned that comes first. :param matches: a list of matches to check for :param default: the value that is returned if none match """ if matches: best_quality = -1 result = default for client_item, quality in self: for server_item in matches: if quality <= best_quality: break if self._value_matches(server_item, client_item): best_quality = quality result = server_item return result else: return self.best
[ "def", "best_match", "(", "self", ",", "matches", ",", "default", "=", "None", ")", ":", "if", "matches", ":", "best_quality", "=", "-", "1", "result", "=", "default", "for", "client_item", ",", "quality", "in", "self", ":", "for", "server_item", "in", ...
Returns the best match from a list of possible matches based on the quality of the client. If two items have the same quality, the one is returned that comes first. :param matches: a list of matches to check for :param default: the value that is returned if none match
[ "Returns", "the", "best", "match", "from", "a", "list", "of", "possible", "matches", "based", "on", "the", "quality", "of", "the", "client", ".", "If", "two", "items", "have", "the", "same", "quality", "the", "one", "is", "returned", "that", "comes", "fi...
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L121-L141
train
quantmind/pulsar
pulsar/utils/system/__init__.py
convert_bytes
def convert_bytes(b): '''Convert a number of bytes into a human readable memory usage, bytes, kilo, mega, giga, tera, peta, exa, zetta, yotta''' if b is None: return '#NA' for s in reversed(memory_symbols): if b >= memory_size[s]: value = float(b) / memory_size[s] return '%.1f%sB' % (value, s) return "%sB" % b
python
def convert_bytes(b): '''Convert a number of bytes into a human readable memory usage, bytes, kilo, mega, giga, tera, peta, exa, zetta, yotta''' if b is None: return '#NA' for s in reversed(memory_symbols): if b >= memory_size[s]: value = float(b) / memory_size[s] return '%.1f%sB' % (value, s) return "%sB" % b
[ "def", "convert_bytes", "(", "b", ")", ":", "if", "b", "is", "None", ":", "return", "'#NA'", "for", "s", "in", "reversed", "(", "memory_symbols", ")", ":", "if", "b", ">=", "memory_size", "[", "s", "]", ":", "value", "=", "float", "(", "b", ")", ...
Convert a number of bytes into a human readable memory usage, bytes, kilo, mega, giga, tera, peta, exa, zetta, yotta
[ "Convert", "a", "number", "of", "bytes", "into", "a", "human", "readable", "memory", "usage", "bytes", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/__init__.py#L32-L41
train
quantmind/pulsar
pulsar/utils/system/__init__.py
process_info
def process_info(pid=None): '''Returns a dictionary of system information for the process ``pid``. It uses the psutil_ module for the purpose. If psutil_ is not available it returns an empty dictionary. .. _psutil: http://code.google.com/p/psutil/ ''' if psutil is None: # pragma nocover return {} pid = pid or os.getpid() try: p = psutil.Process(pid) # this fails on platforms which don't allow multiprocessing except psutil.NoSuchProcess: # pragma nocover return {} else: mem = p.memory_info() return {'memory': convert_bytes(mem.rss), 'memory_virtual': convert_bytes(mem.vms), 'cpu_percent': p.cpu_percent(), 'nice': p.nice(), 'num_threads': p.num_threads()}
python
def process_info(pid=None): '''Returns a dictionary of system information for the process ``pid``. It uses the psutil_ module for the purpose. If psutil_ is not available it returns an empty dictionary. .. _psutil: http://code.google.com/p/psutil/ ''' if psutil is None: # pragma nocover return {} pid = pid or os.getpid() try: p = psutil.Process(pid) # this fails on platforms which don't allow multiprocessing except psutil.NoSuchProcess: # pragma nocover return {} else: mem = p.memory_info() return {'memory': convert_bytes(mem.rss), 'memory_virtual': convert_bytes(mem.vms), 'cpu_percent': p.cpu_percent(), 'nice': p.nice(), 'num_threads': p.num_threads()}
[ "def", "process_info", "(", "pid", "=", "None", ")", ":", "if", "psutil", "is", "None", ":", "return", "{", "}", "pid", "=", "pid", "or", "os", ".", "getpid", "(", ")", "try", ":", "p", "=", "psutil", ".", "Process", "(", "pid", ")", "except", ...
Returns a dictionary of system information for the process ``pid``. It uses the psutil_ module for the purpose. If psutil_ is not available it returns an empty dictionary. .. _psutil: http://code.google.com/p/psutil/
[ "Returns", "a", "dictionary", "of", "system", "information", "for", "the", "process", "pid", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/__init__.py#L44-L66
train
quantmind/pulsar
pulsar/async/protocols.py
TcpServer.start_serving
async def start_serving(self, address=None, sockets=None, backlog=100, sslcontext=None): """Start serving. :param address: optional address to bind to :param sockets: optional list of sockets to bind to :param backlog: Number of maximum connections :param sslcontext: optional SSLContext object """ if self._server: raise RuntimeError('Already serving') create_server = self._loop.create_server server = None if sockets: for sock in sockets: srv = await create_server(self.create_protocol, sock=sock, backlog=backlog, ssl=sslcontext) if server: server.sockets.extend(srv.sockets) else: server = srv elif isinstance(address, tuple): server = await create_server(self.create_protocol, host=address[0], port=address[1], backlog=backlog, ssl=sslcontext) else: raise RuntimeError('sockets or address must be supplied') self._set_server(server)
python
async def start_serving(self, address=None, sockets=None, backlog=100, sslcontext=None): """Start serving. :param address: optional address to bind to :param sockets: optional list of sockets to bind to :param backlog: Number of maximum connections :param sslcontext: optional SSLContext object """ if self._server: raise RuntimeError('Already serving') create_server = self._loop.create_server server = None if sockets: for sock in sockets: srv = await create_server(self.create_protocol, sock=sock, backlog=backlog, ssl=sslcontext) if server: server.sockets.extend(srv.sockets) else: server = srv elif isinstance(address, tuple): server = await create_server(self.create_protocol, host=address[0], port=address[1], backlog=backlog, ssl=sslcontext) else: raise RuntimeError('sockets or address must be supplied') self._set_server(server)
[ "async", "def", "start_serving", "(", "self", ",", "address", "=", "None", ",", "sockets", "=", "None", ",", "backlog", "=", "100", ",", "sslcontext", "=", "None", ")", ":", "if", "self", ".", "_server", ":", "raise", "RuntimeError", "(", "'Already servi...
Start serving. :param address: optional address to bind to :param sockets: optional list of sockets to bind to :param backlog: Number of maximum connections :param sslcontext: optional SSLContext object
[ "Start", "serving", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L212-L243
train
quantmind/pulsar
pulsar/async/protocols.py
TcpServer._close_connections
def _close_connections(self, connection=None, timeout=5): """Close ``connection`` if specified, otherwise close all connections. Return a list of :class:`.Future` called back once the connection/s are closed. """ all = [] if connection: waiter = connection.event('connection_lost').waiter() if waiter: all.append(waiter) connection.close() else: connections = list(self._concurrent_connections) self._concurrent_connections = set() for connection in connections: waiter = connection.event('connection_lost').waiter() if waiter: all.append(waiter) connection.close() if all: self.logger.info('%s closing %d connections', self, len(all)) return asyncio.wait(all, timeout=timeout, loop=self._loop)
python
def _close_connections(self, connection=None, timeout=5): """Close ``connection`` if specified, otherwise close all connections. Return a list of :class:`.Future` called back once the connection/s are closed. """ all = [] if connection: waiter = connection.event('connection_lost').waiter() if waiter: all.append(waiter) connection.close() else: connections = list(self._concurrent_connections) self._concurrent_connections = set() for connection in connections: waiter = connection.event('connection_lost').waiter() if waiter: all.append(waiter) connection.close() if all: self.logger.info('%s closing %d connections', self, len(all)) return asyncio.wait(all, timeout=timeout, loop=self._loop)
[ "def", "_close_connections", "(", "self", ",", "connection", "=", "None", ",", "timeout", "=", "5", ")", ":", "all", "=", "[", "]", "if", "connection", ":", "waiter", "=", "connection", ".", "event", "(", "'connection_lost'", ")", ".", "waiter", "(", "...
Close ``connection`` if specified, otherwise close all connections. Return a list of :class:`.Future` called back once the connection/s are closed.
[ "Close", "connection", "if", "specified", "otherwise", "close", "all", "connections", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L282-L304
train
quantmind/pulsar
pulsar/async/protocols.py
DatagramServer.start_serving
async def start_serving(self, address=None, sockets=None, **kw): """create the server endpoint. """ if self._server: raise RuntimeError('Already serving') server = DGServer(self._loop) loop = self._loop if sockets: for sock in sockets: transport, _ = await loop.create_datagram_endpoint( self.create_protocol, sock=sock) server.transports.append(transport) elif isinstance(address, tuple): transport, _ = await loop.create_datagram_endpoint( self.create_protocol, local_addr=address) server.transports.append(transport) else: raise RuntimeError('sockets or address must be supplied') self._set_server(server)
python
async def start_serving(self, address=None, sockets=None, **kw): """create the server endpoint. """ if self._server: raise RuntimeError('Already serving') server = DGServer(self._loop) loop = self._loop if sockets: for sock in sockets: transport, _ = await loop.create_datagram_endpoint( self.create_protocol, sock=sock) server.transports.append(transport) elif isinstance(address, tuple): transport, _ = await loop.create_datagram_endpoint( self.create_protocol, local_addr=address) server.transports.append(transport) else: raise RuntimeError('sockets or address must be supplied') self._set_server(server)
[ "async", "def", "start_serving", "(", "self", ",", "address", "=", "None", ",", "sockets", "=", "None", ",", "**", "kw", ")", ":", "if", "self", ".", "_server", ":", "raise", "RuntimeError", "(", "'Already serving'", ")", "server", "=", "DGServer", "(", ...
create the server endpoint.
[ "create", "the", "server", "endpoint", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L333-L351
train
quantmind/pulsar
pulsar/apps/socket/__init__.py
SocketServer.monitor_start
async def monitor_start(self, monitor): '''Create the socket listening to the ``bind`` address. If the platform does not support multiprocessing sockets set the number of workers to 0. ''' cfg = self.cfg if (not platform.has_multiprocessing_socket or cfg.concurrency == 'thread'): cfg.set('workers', 0) servers = await self.binds(monitor) if not servers: raise ImproperlyConfigured('Could not open a socket. ' 'No address to bind to') addresses = [] for server in servers.values(): addresses.extend(server.addresses) self.cfg.addresses = addresses
python
async def monitor_start(self, monitor): '''Create the socket listening to the ``bind`` address. If the platform does not support multiprocessing sockets set the number of workers to 0. ''' cfg = self.cfg if (not platform.has_multiprocessing_socket or cfg.concurrency == 'thread'): cfg.set('workers', 0) servers = await self.binds(monitor) if not servers: raise ImproperlyConfigured('Could not open a socket. ' 'No address to bind to') addresses = [] for server in servers.values(): addresses.extend(server.addresses) self.cfg.addresses = addresses
[ "async", "def", "monitor_start", "(", "self", ",", "monitor", ")", ":", "cfg", "=", "self", ".", "cfg", "if", "(", "not", "platform", ".", "has_multiprocessing_socket", "or", "cfg", ".", "concurrency", "==", "'thread'", ")", ":", "cfg", ".", "set", "(", ...
Create the socket listening to the ``bind`` address. If the platform does not support multiprocessing sockets set the number of workers to 0.
[ "Create", "the", "socket", "listening", "to", "the", "bind", "address", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/socket/__init__.py#L256-L273
train
quantmind/pulsar
pulsar/apps/socket/__init__.py
SocketServer.create_server
async def create_server(self, worker, protocol_factory, address=None, sockets=None, idx=0): '''Create the Server which will listen for requests. :return: a :class:`.TcpServer`. ''' cfg = self.cfg max_requests = cfg.max_requests if max_requests: max_requests = int(lognormvariate(log(max_requests), 0.2)) server = self.server_factory( protocol_factory, loop=worker._loop, max_requests=max_requests, keep_alive=cfg.keep_alive, name=self.name, logger=self.logger, server_software=cfg.server_software, cfg=cfg, idx=idx ) for event in ('connection_made', 'pre_request', 'post_request', 'connection_lost'): callback = getattr(cfg, event) if callback != pass_through: server.event(event).bind(callback) await server.start_serving( sockets=sockets, address=address, backlog=cfg.backlog, sslcontext=self.sslcontext() ) return server
python
async def create_server(self, worker, protocol_factory, address=None, sockets=None, idx=0): '''Create the Server which will listen for requests. :return: a :class:`.TcpServer`. ''' cfg = self.cfg max_requests = cfg.max_requests if max_requests: max_requests = int(lognormvariate(log(max_requests), 0.2)) server = self.server_factory( protocol_factory, loop=worker._loop, max_requests=max_requests, keep_alive=cfg.keep_alive, name=self.name, logger=self.logger, server_software=cfg.server_software, cfg=cfg, idx=idx ) for event in ('connection_made', 'pre_request', 'post_request', 'connection_lost'): callback = getattr(cfg, event) if callback != pass_through: server.event(event).bind(callback) await server.start_serving( sockets=sockets, address=address, backlog=cfg.backlog, sslcontext=self.sslcontext() ) return server
[ "async", "def", "create_server", "(", "self", ",", "worker", ",", "protocol_factory", ",", "address", "=", "None", ",", "sockets", "=", "None", ",", "idx", "=", "0", ")", ":", "cfg", "=", "self", ".", "cfg", "max_requests", "=", "cfg", ".", "max_reques...
Create the Server which will listen for requests. :return: a :class:`.TcpServer`.
[ "Create", "the", "Server", "which", "will", "listen", "for", "requests", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/socket/__init__.py#L306-L338
train
quantmind/pulsar
pulsar/apps/data/redis/pubsub.py
RedisPubSub.channels
def channels(self, pattern=None): '''Lists the currently active channels matching ``pattern`` ''' if pattern: return self.store.execute('PUBSUB', 'CHANNELS', pattern) else: return self.store.execute('PUBSUB', 'CHANNELS')
python
def channels(self, pattern=None): '''Lists the currently active channels matching ``pattern`` ''' if pattern: return self.store.execute('PUBSUB', 'CHANNELS', pattern) else: return self.store.execute('PUBSUB', 'CHANNELS')
[ "def", "channels", "(", "self", ",", "pattern", "=", "None", ")", ":", "if", "pattern", ":", "return", "self", ".", "store", ".", "execute", "(", "'PUBSUB'", ",", "'CHANNELS'", ",", "pattern", ")", "else", ":", "return", "self", ".", "store", ".", "e...
Lists the currently active channels matching ``pattern``
[ "Lists", "the", "currently", "active", "channels", "matching", "pattern" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L45-L51
train
quantmind/pulsar
pulsar/apps/data/redis/pubsub.py
RedisChannels.lock
def lock(self, name, **kwargs): """Global distributed lock """ return self.pubsub.store.client().lock(self.prefixed(name), **kwargs)
python
def lock(self, name, **kwargs): """Global distributed lock """ return self.pubsub.store.client().lock(self.prefixed(name), **kwargs)
[ "def", "lock", "(", "self", ",", "name", ",", "**", "kwargs", ")", ":", "return", "self", ".", "pubsub", ".", "store", ".", "client", "(", ")", ".", "lock", "(", "self", ".", "prefixed", "(", "name", ")", ",", "**", "kwargs", ")" ]
Global distributed lock
[ "Global", "distributed", "lock" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L104-L107
train
quantmind/pulsar
pulsar/apps/data/redis/pubsub.py
RedisChannels.publish
async def publish(self, channel, event, data=None): """Publish a new ``event`` on a ``channel`` :param channel: channel name :param event: event name :param data: optional payload to include in the event :return: a coroutine and therefore it must be awaited """ msg = {'event': event, 'channel': channel} if data: msg['data'] = data try: await self.pubsub.publish(self.prefixed(channel), msg) except ConnectionRefusedError: self.connection_error = True self.logger.critical( '%s cannot publish on "%s" channel - connection error', self, channel ) else: self.connection_ok()
python
async def publish(self, channel, event, data=None): """Publish a new ``event`` on a ``channel`` :param channel: channel name :param event: event name :param data: optional payload to include in the event :return: a coroutine and therefore it must be awaited """ msg = {'event': event, 'channel': channel} if data: msg['data'] = data try: await self.pubsub.publish(self.prefixed(channel), msg) except ConnectionRefusedError: self.connection_error = True self.logger.critical( '%s cannot publish on "%s" channel - connection error', self, channel ) else: self.connection_ok()
[ "async", "def", "publish", "(", "self", ",", "channel", ",", "event", ",", "data", "=", "None", ")", ":", "msg", "=", "{", "'event'", ":", "event", ",", "'channel'", ":", "channel", "}", "if", "data", ":", "msg", "[", "'data'", "]", "=", "data", ...
Publish a new ``event`` on a ``channel`` :param channel: channel name :param event: event name :param data: optional payload to include in the event :return: a coroutine and therefore it must be awaited
[ "Publish", "a", "new", "event", "on", "a", "channel" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L109-L130
train
quantmind/pulsar
pulsar/apps/data/redis/pubsub.py
RedisChannels.close
async def close(self): """Close channels and underlying pubsub handler :return: a coroutine and therefore it must be awaited """ push_connection = self.pubsub.push_connection self.status = self.statusType.closed if push_connection: push_connection.event('connection_lost').unbind( self._connection_lost ) await self.pubsub.close()
python
async def close(self): """Close channels and underlying pubsub handler :return: a coroutine and therefore it must be awaited """ push_connection = self.pubsub.push_connection self.status = self.statusType.closed if push_connection: push_connection.event('connection_lost').unbind( self._connection_lost ) await self.pubsub.close()
[ "async", "def", "close", "(", "self", ")", ":", "push_connection", "=", "self", ".", "pubsub", ".", "push_connection", "self", ".", "status", "=", "self", ".", "statusType", ".", "closed", "if", "push_connection", ":", "push_connection", ".", "event", "(", ...
Close channels and underlying pubsub handler :return: a coroutine and therefore it must be awaited
[ "Close", "channels", "and", "underlying", "pubsub", "handler" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L140-L151
train
quantmind/pulsar
pulsar/apps/http/client.py
RequestBase.origin_req_host
def origin_req_host(self): """Required by Cookies handlers """ if self.history: return self.history[0].request.origin_req_host else: return scheme_host_port(self.url)[1]
python
def origin_req_host(self): """Required by Cookies handlers """ if self.history: return self.history[0].request.origin_req_host else: return scheme_host_port(self.url)[1]
[ "def", "origin_req_host", "(", "self", ")", ":", "if", "self", ".", "history", ":", "return", "self", ".", "history", "[", "0", "]", ".", "request", ".", "origin_req_host", "else", ":", "return", "scheme_host_port", "(", "self", ".", "url", ")", "[", "...
Required by Cookies handlers
[ "Required", "by", "Cookies", "handlers" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L119-L125
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpRequest.get_header
def get_header(self, header_name, default=None): """Retrieve ``header_name`` from this request headers. """ return self.headers.get( header_name, self.unredirected_headers.get(header_name, default))
python
def get_header(self, header_name, default=None): """Retrieve ``header_name`` from this request headers. """ return self.headers.get( header_name, self.unredirected_headers.get(header_name, default))
[ "def", "get_header", "(", "self", ",", "header_name", ",", "default", "=", "None", ")", ":", "return", "self", ".", "headers", ".", "get", "(", "header_name", ",", "self", ".", "unredirected_headers", ".", "get", "(", "header_name", ",", "default", ")", ...
Retrieve ``header_name`` from this request headers.
[ "Retrieve", "header_name", "from", "this", "request", "headers", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L325-L329
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpRequest.remove_header
def remove_header(self, header_name): """Remove ``header_name`` from this request. """ val1 = self.headers.pop(header_name, None) val2 = self.unredirected_headers.pop(header_name, None) return val1 or val2
python
def remove_header(self, header_name): """Remove ``header_name`` from this request. """ val1 = self.headers.pop(header_name, None) val2 = self.unredirected_headers.pop(header_name, None) return val1 or val2
[ "def", "remove_header", "(", "self", ",", "header_name", ")", ":", "val1", "=", "self", ".", "headers", ".", "pop", "(", "header_name", ",", "None", ")", "val2", "=", "self", ".", "unredirected_headers", ".", "pop", "(", "header_name", ",", "None", ")", ...
Remove ``header_name`` from this request.
[ "Remove", "header_name", "from", "this", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L331-L336
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpResponse.raw
def raw(self): """A raw asynchronous Http response """ if self._raw is None: self._raw = HttpStream(self) return self._raw
python
def raw(self): """A raw asynchronous Http response """ if self._raw is None: self._raw = HttpStream(self) return self._raw
[ "def", "raw", "(", "self", ")", ":", "if", "self", ".", "_raw", "is", "None", ":", "self", ".", "_raw", "=", "HttpStream", "(", "self", ")", "return", "self", ".", "_raw" ]
A raw asynchronous Http response
[ "A", "raw", "asynchronous", "Http", "response" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L539-L544
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpResponse.links
def links(self): """Returns the parsed header links of the response, if any """ headers = self.headers or {} header = headers.get('link') li = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') li[key] = link return li
python
def links(self): """Returns the parsed header links of the response, if any """ headers = self.headers or {} header = headers.get('link') li = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') li[key] = link return li
[ "def", "links", "(", "self", ")", ":", "headers", "=", "self", ".", "headers", "or", "{", "}", "header", "=", "headers", ".", "get", "(", "'link'", ")", "li", "=", "{", "}", "if", "header", ":", "links", "=", "parse_header_links", "(", "header", ")...
Returns the parsed header links of the response, if any
[ "Returns", "the", "parsed", "header", "links", "of", "the", "response", "if", "any" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L547-L558
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpResponse.text
def text(self): """Decode content as a string. """ data = self.content return data.decode(self.encoding or 'utf-8') if data else ''
python
def text(self): """Decode content as a string. """ data = self.content return data.decode(self.encoding or 'utf-8') if data else ''
[ "def", "text", "(", "self", ")", ":", "data", "=", "self", ".", "content", "return", "data", ".", "decode", "(", "self", ".", "encoding", "or", "'utf-8'", ")", "if", "data", "else", "''" ]
Decode content as a string.
[ "Decode", "content", "as", "a", "string", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L565-L569
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpResponse.decode_content
def decode_content(self): """Return the best possible representation of the response body. """ ct = self.headers.get('content-type') if ct: ct, options = parse_options_header(ct) charset = options.get('charset') if ct in JSON_CONTENT_TYPES: return self.json() elif ct.startswith('text/'): return self.text elif ct == FORM_URL_ENCODED: return parse_qsl(self.content.decode(charset), keep_blank_values=True) return self.content
python
def decode_content(self): """Return the best possible representation of the response body. """ ct = self.headers.get('content-type') if ct: ct, options = parse_options_header(ct) charset = options.get('charset') if ct in JSON_CONTENT_TYPES: return self.json() elif ct.startswith('text/'): return self.text elif ct == FORM_URL_ENCODED: return parse_qsl(self.content.decode(charset), keep_blank_values=True) return self.content
[ "def", "decode_content", "(", "self", ")", ":", "ct", "=", "self", ".", "headers", ".", "get", "(", "'content-type'", ")", "if", "ct", ":", "ct", ",", "options", "=", "parse_options_header", "(", "ct", ")", "charset", "=", "options", ".", "get", "(", ...
Return the best possible representation of the response body.
[ "Return", "the", "best", "possible", "representation", "of", "the", "response", "body", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L576-L590
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpClient.request
def request(self, method, url, **params): """Constructs and sends a request to a remote server. It returns a :class:`.Future` which results in a :class:`.HttpResponse` object. :param method: request method for the :class:`HttpRequest`. :param url: URL for the :class:`HttpRequest`. :param params: optional parameters for the :class:`HttpRequest` initialisation. :rtype: a coroutine """ response = self._request(method, url, **params) if not self._loop.is_running(): return self._loop.run_until_complete(response) else: return response
python
def request(self, method, url, **params): """Constructs and sends a request to a remote server. It returns a :class:`.Future` which results in a :class:`.HttpResponse` object. :param method: request method for the :class:`HttpRequest`. :param url: URL for the :class:`HttpRequest`. :param params: optional parameters for the :class:`HttpRequest` initialisation. :rtype: a coroutine """ response = self._request(method, url, **params) if not self._loop.is_running(): return self._loop.run_until_complete(response) else: return response
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "**", "params", ")", ":", "response", "=", "self", ".", "_request", "(", "method", ",", "url", ",", "**", "params", ")", "if", "not", "self", ".", "_loop", ".", "is_running", "(", ")", ...
Constructs and sends a request to a remote server. It returns a :class:`.Future` which results in a :class:`.HttpResponse` object. :param method: request method for the :class:`HttpRequest`. :param url: URL for the :class:`HttpRequest`. :param params: optional parameters for the :class:`HttpRequest` initialisation. :rtype: a coroutine
[ "Constructs", "and", "sends", "a", "request", "to", "a", "remote", "server", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L864-L881
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpClient.ssl_context
def ssl_context(self, verify=True, cert_reqs=None, check_hostname=False, certfile=None, keyfile=None, cafile=None, capath=None, cadata=None, **kw): """Create a SSL context object. This method should not be called by from user code """ assert ssl, 'SSL not supported' cafile = cafile or DEFAULT_CA_BUNDLE_PATH if verify is True: cert_reqs = ssl.CERT_REQUIRED check_hostname = True if isinstance(verify, str): cert_reqs = ssl.CERT_REQUIRED if os.path.isfile(verify): cafile = verify elif os.path.isdir(verify): capath = verify return ssl._create_unverified_context(cert_reqs=cert_reqs, check_hostname=check_hostname, certfile=certfile, keyfile=keyfile, cafile=cafile, capath=capath, cadata=cadata)
python
def ssl_context(self, verify=True, cert_reqs=None, check_hostname=False, certfile=None, keyfile=None, cafile=None, capath=None, cadata=None, **kw): """Create a SSL context object. This method should not be called by from user code """ assert ssl, 'SSL not supported' cafile = cafile or DEFAULT_CA_BUNDLE_PATH if verify is True: cert_reqs = ssl.CERT_REQUIRED check_hostname = True if isinstance(verify, str): cert_reqs = ssl.CERT_REQUIRED if os.path.isfile(verify): cafile = verify elif os.path.isdir(verify): capath = verify return ssl._create_unverified_context(cert_reqs=cert_reqs, check_hostname=check_hostname, certfile=certfile, keyfile=keyfile, cafile=cafile, capath=capath, cadata=cadata)
[ "def", "ssl_context", "(", "self", ",", "verify", "=", "True", ",", "cert_reqs", "=", "None", ",", "check_hostname", "=", "False", ",", "certfile", "=", "None", ",", "keyfile", "=", "None", ",", "cafile", "=", "None", ",", "capath", "=", "None", ",", ...
Create a SSL context object. This method should not be called by from user code
[ "Create", "a", "SSL", "context", "object", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L972-L999
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpClient.create_tunnel_connection
async def create_tunnel_connection(self, req): """Create a tunnel connection """ tunnel_address = req.tunnel_address connection = await self.create_connection(tunnel_address) response = connection.current_consumer() for event in response.events().values(): event.clear() response.start(HttpTunnel(self, req)) await response.event('post_request').waiter() if response.status_code != 200: raise ConnectionRefusedError( 'Cannot connect to tunnel: status code %s' % response.status_code ) raw_sock = connection.transport.get_extra_info('socket') if raw_sock is None: raise RuntimeError('Transport without socket') # duplicate socket so we can close transport raw_sock = raw_sock.dup() connection.transport.close() await connection.event('connection_lost').waiter() self.sessions -= 1 self.requests_processed -= 1 # connection = await self.create_connection( sock=raw_sock, ssl=req.ssl(self), server_hostname=req.netloc ) return connection
python
async def create_tunnel_connection(self, req): """Create a tunnel connection """ tunnel_address = req.tunnel_address connection = await self.create_connection(tunnel_address) response = connection.current_consumer() for event in response.events().values(): event.clear() response.start(HttpTunnel(self, req)) await response.event('post_request').waiter() if response.status_code != 200: raise ConnectionRefusedError( 'Cannot connect to tunnel: status code %s' % response.status_code ) raw_sock = connection.transport.get_extra_info('socket') if raw_sock is None: raise RuntimeError('Transport without socket') # duplicate socket so we can close transport raw_sock = raw_sock.dup() connection.transport.close() await connection.event('connection_lost').waiter() self.sessions -= 1 self.requests_processed -= 1 # connection = await self.create_connection( sock=raw_sock, ssl=req.ssl(self), server_hostname=req.netloc ) return connection
[ "async", "def", "create_tunnel_connection", "(", "self", ",", "req", ")", ":", "tunnel_address", "=", "req", ".", "tunnel_address", "connection", "=", "await", "self", ".", "create_connection", "(", "tunnel_address", ")", "response", "=", "connection", ".", "cur...
Create a tunnel connection
[ "Create", "a", "tunnel", "connection" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L1004-L1032
train
quantmind/pulsar
pulsar/apps/__init__.py
Configurator.python_path
def python_path(self, script): """Called during initialisation to obtain the ``script`` name. If ``script`` does not evaluate to ``True`` it is evaluated from the ``__main__`` import. Returns the real path of the python script which runs the application. """ if not script: try: import __main__ script = getfile(__main__) except Exception: # pragma nocover return script = os.path.realpath(script) if self.cfg.get('python_path', True): path = os.path.dirname(script) if path not in sys.path: sys.path.insert(0, path) return script
python
def python_path(self, script): """Called during initialisation to obtain the ``script`` name. If ``script`` does not evaluate to ``True`` it is evaluated from the ``__main__`` import. Returns the real path of the python script which runs the application. """ if not script: try: import __main__ script = getfile(__main__) except Exception: # pragma nocover return script = os.path.realpath(script) if self.cfg.get('python_path', True): path = os.path.dirname(script) if path not in sys.path: sys.path.insert(0, path) return script
[ "def", "python_path", "(", "self", ",", "script", ")", ":", "if", "not", "script", ":", "try", ":", "import", "__main__", "script", "=", "getfile", "(", "__main__", ")", "except", "Exception", ":", "return", "script", "=", "os", ".", "path", ".", "real...
Called during initialisation to obtain the ``script`` name. If ``script`` does not evaluate to ``True`` it is evaluated from the ``__main__`` import. Returns the real path of the python script which runs the application.
[ "Called", "during", "initialisation", "to", "obtain", "the", "script", "name", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L291-L309
train
quantmind/pulsar
pulsar/apps/__init__.py
Configurator.start
def start(self, exit=True): """Invoked the application callable method and start the ``arbiter`` if it wasn't already started. It returns a :class:`~asyncio.Future` called back once the application/applications are running. It returns ``None`` if called more than once. """ on_start = self() actor = arbiter() if actor and on_start: actor.start(exit=exit) if actor.exit_code is not None: return actor.exit_code return on_start
python
def start(self, exit=True): """Invoked the application callable method and start the ``arbiter`` if it wasn't already started. It returns a :class:`~asyncio.Future` called back once the application/applications are running. It returns ``None`` if called more than once. """ on_start = self() actor = arbiter() if actor and on_start: actor.start(exit=exit) if actor.exit_code is not None: return actor.exit_code return on_start
[ "def", "start", "(", "self", ",", "exit", "=", "True", ")", ":", "on_start", "=", "self", "(", ")", "actor", "=", "arbiter", "(", ")", "if", "actor", "and", "on_start", ":", "actor", ".", "start", "(", "exit", "=", "exit", ")", "if", "actor", "."...
Invoked the application callable method and start the ``arbiter`` if it wasn't already started. It returns a :class:`~asyncio.Future` called back once the application/applications are running. It returns ``None`` if called more than once.
[ "Invoked", "the", "application", "callable", "method", "and", "start", "the", "arbiter", "if", "it", "wasn", "t", "already", "started", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L355-L369
train
quantmind/pulsar
pulsar/apps/__init__.py
Application.stop
def stop(self, actor=None): """Stop the application """ if actor is None: actor = get_actor() if actor and actor.is_arbiter(): monitor = actor.get_actor(self.name) if monitor: return monitor.stop() raise RuntimeError('Cannot stop application')
python
def stop(self, actor=None): """Stop the application """ if actor is None: actor = get_actor() if actor and actor.is_arbiter(): monitor = actor.get_actor(self.name) if monitor: return monitor.stop() raise RuntimeError('Cannot stop application')
[ "def", "stop", "(", "self", ",", "actor", "=", "None", ")", ":", "if", "actor", "is", "None", ":", "actor", "=", "get_actor", "(", ")", "if", "actor", "and", "actor", ".", "is_arbiter", "(", ")", ":", "monitor", "=", "actor", ".", "get_actor", "(",...
Stop the application
[ "Stop", "the", "application" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L493-L502
train
quantmind/pulsar
pulsar/utils/system/posixsystem.py
set_owner_process
def set_owner_process(uid, gid): """ set user and group of workers processes """ if gid: try: os.setgid(gid) except OverflowError: # versions of python < 2.6.2 don't manage unsigned int for # groups like on osx or fedora os.setgid(-ctypes.c_int(-gid).value) if uid: os.setuid(uid)
python
def set_owner_process(uid, gid): """ set user and group of workers processes """ if gid: try: os.setgid(gid) except OverflowError: # versions of python < 2.6.2 don't manage unsigned int for # groups like on osx or fedora os.setgid(-ctypes.c_int(-gid).value) if uid: os.setuid(uid)
[ "def", "set_owner_process", "(", "uid", ",", "gid", ")", ":", "if", "gid", ":", "try", ":", "os", ".", "setgid", "(", "gid", ")", "except", "OverflowError", ":", "os", ".", "setgid", "(", "-", "ctypes", ".", "c_int", "(", "-", "gid", ")", ".", "v...
set user and group of workers processes
[ "set", "user", "and", "group", "of", "workers", "processes" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/posixsystem.py#L77-L87
train
quantmind/pulsar
pulsar/apps/greenio/utils.py
wait
def wait(value, must_be_child=False): '''Wait for a possible asynchronous value to complete. ''' current = getcurrent() parent = current.parent if must_be_child and not parent: raise MustBeInChildGreenlet('Cannot wait on main greenlet') return parent.switch(value) if parent else value
python
def wait(value, must_be_child=False): '''Wait for a possible asynchronous value to complete. ''' current = getcurrent() parent = current.parent if must_be_child and not parent: raise MustBeInChildGreenlet('Cannot wait on main greenlet') return parent.switch(value) if parent else value
[ "def", "wait", "(", "value", ",", "must_be_child", "=", "False", ")", ":", "current", "=", "getcurrent", "(", ")", "parent", "=", "current", ".", "parent", "if", "must_be_child", "and", "not", "parent", ":", "raise", "MustBeInChildGreenlet", "(", "'Cannot wa...
Wait for a possible asynchronous value to complete.
[ "Wait", "for", "a", "possible", "asynchronous", "value", "to", "complete", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/utils.py#L17-L24
train
quantmind/pulsar
pulsar/apps/greenio/utils.py
run_in_greenlet
def run_in_greenlet(callable): """Decorator to run a ``callable`` on a new greenlet. A ``callable`` decorated with this decorator returns a coroutine """ @wraps(callable) async def _(*args, **kwargs): green = greenlet(callable) # switch to the new greenlet result = green.switch(*args, **kwargs) # back to the parent while isawaitable(result): # keep on switching back to the greenlet if we get an awaitable try: result = green.switch((await result)) except Exception: exc_info = sys.exc_info() result = green.throw(*exc_info) return green.switch(result) return _
python
def run_in_greenlet(callable): """Decorator to run a ``callable`` on a new greenlet. A ``callable`` decorated with this decorator returns a coroutine """ @wraps(callable) async def _(*args, **kwargs): green = greenlet(callable) # switch to the new greenlet result = green.switch(*args, **kwargs) # back to the parent while isawaitable(result): # keep on switching back to the greenlet if we get an awaitable try: result = green.switch((await result)) except Exception: exc_info = sys.exc_info() result = green.throw(*exc_info) return green.switch(result) return _
[ "def", "run_in_greenlet", "(", "callable", ")", ":", "@", "wraps", "(", "callable", ")", "async", "def", "_", "(", "*", "args", ",", "**", "kwargs", ")", ":", "green", "=", "greenlet", "(", "callable", ")", "result", "=", "green", ".", "switch", "(",...
Decorator to run a ``callable`` on a new greenlet. A ``callable`` decorated with this decorator returns a coroutine
[ "Decorator", "to", "run", "a", "callable", "on", "a", "new", "greenlet", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/utils.py#L27-L48
train
litaotao/IPython-Dashboard
dashboard/server/utils.py
build_response
def build_response(content, code=200): """Build response, add headers""" response = make_response( jsonify(content), content['code'] ) response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Headers'] = \ 'Origin, X-Requested-With, Content-Type, Accept, Authorization' return response
python
def build_response(content, code=200): """Build response, add headers""" response = make_response( jsonify(content), content['code'] ) response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Headers'] = \ 'Origin, X-Requested-With, Content-Type, Accept, Authorization' return response
[ "def", "build_response", "(", "content", ",", "code", "=", "200", ")", ":", "response", "=", "make_response", "(", "jsonify", "(", "content", ")", ",", "content", "[", "'code'", "]", ")", "response", ".", "headers", "[", "'Access-Control-Allow-Origin'", "]",...
Build response, add headers
[ "Build", "response", "add", "headers" ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/utils.py#L18-L24
train
litaotao/IPython-Dashboard
dashboard/server/resources/sql.py
SqlData.post
def post(self): '''return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result. ''' ## format sql data = request.get_json() options, sql_raw = data.get('options'), data.get('sql_raw') if options == 'format': sql_formmated = sqlparse.format(sql_raw, keyword_case='upper', reindent=True) return build_response(dict(data=sql_formmated, code=200)) elif options in ('all', 'selected'): conn = SQL(config.sql_host, config.sql_port, config.sql_user, config.sql_pwd, config.sql_db) result = conn.run(sql_raw) return build_response(dict(data=result, code=200)) else: pass pass
python
def post(self): '''return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result. ''' ## format sql data = request.get_json() options, sql_raw = data.get('options'), data.get('sql_raw') if options == 'format': sql_formmated = sqlparse.format(sql_raw, keyword_case='upper', reindent=True) return build_response(dict(data=sql_formmated, code=200)) elif options in ('all', 'selected'): conn = SQL(config.sql_host, config.sql_port, config.sql_user, config.sql_pwd, config.sql_db) result = conn.run(sql_raw) return build_response(dict(data=result, code=200)) else: pass pass
[ "def", "post", "(", "self", ")", ":", "data", "=", "request", ".", "get_json", "(", ")", "options", ",", "sql_raw", "=", "data", ".", "get", "(", "'options'", ")", ",", "data", ".", "get", "(", "'sql_raw'", ")", "if", "options", "==", "'format'", "...
return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result.
[ "return", "executed", "sql", "result", "to", "client", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/sql.py#L40-L75
train
litaotao/IPython-Dashboard
dashboard/server/resources/home.py
DashListData.get
def get(self, page=0, size=10): """Get dashboard meta info from in page `page` and page size is `size`. Args: page: page number. size: size number. Returns: list of dict containing the dash_id and accordingly meta info. maybe empty list [] when page * size > total dashes in db. that's reasonable. """ dash_list = r_db.zrevrange(config.DASH_ID_KEY, 0, -1, True) id_list = dash_list[page * size : page * size + size] dash_meta = [] data = [] if id_list: dash_meta = r_db.hmget(config.DASH_META_KEY, [i[0] for i in id_list]) data = [json.loads(i) for i in dash_meta] return build_response(dict(data=data, code=200))
python
def get(self, page=0, size=10): """Get dashboard meta info from in page `page` and page size is `size`. Args: page: page number. size: size number. Returns: list of dict containing the dash_id and accordingly meta info. maybe empty list [] when page * size > total dashes in db. that's reasonable. """ dash_list = r_db.zrevrange(config.DASH_ID_KEY, 0, -1, True) id_list = dash_list[page * size : page * size + size] dash_meta = [] data = [] if id_list: dash_meta = r_db.hmget(config.DASH_META_KEY, [i[0] for i in id_list]) data = [json.loads(i) for i in dash_meta] return build_response(dict(data=data, code=200))
[ "def", "get", "(", "self", ",", "page", "=", "0", ",", "size", "=", "10", ")", ":", "dash_list", "=", "r_db", ".", "zrevrange", "(", "config", ".", "DASH_ID_KEY", ",", "0", ",", "-", "1", ",", "True", ")", "id_list", "=", "dash_list", "[", "page"...
Get dashboard meta info from in page `page` and page size is `size`. Args: page: page number. size: size number. Returns: list of dict containing the dash_id and accordingly meta info. maybe empty list [] when page * size > total dashes in db. that's reasonable.
[ "Get", "dashboard", "meta", "info", "from", "in", "page", "page", "and", "page", "size", "is", "size", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/home.py#L72-L91
train
litaotao/IPython-Dashboard
dashboard/server/resources/storage.py
KeyList.get
def get(self): """Get key list in storage. """ keys = r_kv.keys() keys.sort() return build_response(dict(data=keys, code=200))
python
def get(self): """Get key list in storage. """ keys = r_kv.keys() keys.sort() return build_response(dict(data=keys, code=200))
[ "def", "get", "(", "self", ")", ":", "keys", "=", "r_kv", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "return", "build_response", "(", "dict", "(", "data", "=", "keys", ",", "code", "=", "200", ")", ")" ]
Get key list in storage.
[ "Get", "key", "list", "in", "storage", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/storage.py#L23-L28
train
litaotao/IPython-Dashboard
dashboard/server/resources/storage.py
Key.get
def get(self, key): """Get a key-value from storage according to the key name. """ data = r_kv.get(key) # data = json.dumps(data) if isinstance(data, str) else data # data = json.loads(data) if data else {} return build_response(dict(data=data, code=200))
python
def get(self, key): """Get a key-value from storage according to the key name. """ data = r_kv.get(key) # data = json.dumps(data) if isinstance(data, str) else data # data = json.loads(data) if data else {} return build_response(dict(data=data, code=200))
[ "def", "get", "(", "self", ",", "key", ")", ":", "data", "=", "r_kv", ".", "get", "(", "key", ")", "return", "build_response", "(", "dict", "(", "data", "=", "data", ",", "code", "=", "200", ")", ")" ]
Get a key-value from storage according to the key name.
[ "Get", "a", "key", "-", "value", "from", "storage", "according", "to", "the", "key", "name", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/storage.py#L40-L47
train
litaotao/IPython-Dashboard
dashboard/server/resources/dash.py
Dash.get
def get(self, dash_id): """Just return the dashboard id in the rendering html. JS will do other work [ajax and rendering] according to the dash_id. Args: dash_id: dashboard id. Returns: rendered html. """ return make_response(render_template('dashboard.html', dash_id=dash_id, api_root=config.app_host))
python
def get(self, dash_id): """Just return the dashboard id in the rendering html. JS will do other work [ajax and rendering] according to the dash_id. Args: dash_id: dashboard id. Returns: rendered html. """ return make_response(render_template('dashboard.html', dash_id=dash_id, api_root=config.app_host))
[ "def", "get", "(", "self", ",", "dash_id", ")", ":", "return", "make_response", "(", "render_template", "(", "'dashboard.html'", ",", "dash_id", "=", "dash_id", ",", "api_root", "=", "config", ".", "app_host", ")", ")" ]
Just return the dashboard id in the rendering html. JS will do other work [ajax and rendering] according to the dash_id. Args: dash_id: dashboard id. Returns: rendered html.
[ "Just", "return", "the", "dashboard", "id", "in", "the", "rendering", "html", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/dash.py#L25-L36
train
litaotao/IPython-Dashboard
dashboard/server/resources/dash.py
DashData.get
def get(self, dash_id): """Read dashboard content. Args: dash_id: dashboard id. Returns: A dict containing the content of that dashboard, not include the meta info. """ data = json.loads(r_db.hmget(config.DASH_CONTENT_KEY, dash_id)[0]) return build_response(dict(data=data, code=200))
python
def get(self, dash_id): """Read dashboard content. Args: dash_id: dashboard id. Returns: A dict containing the content of that dashboard, not include the meta info. """ data = json.loads(r_db.hmget(config.DASH_CONTENT_KEY, dash_id)[0]) return build_response(dict(data=data, code=200))
[ "def", "get", "(", "self", ",", "dash_id", ")", ":", "data", "=", "json", ".", "loads", "(", "r_db", ".", "hmget", "(", "config", ".", "DASH_CONTENT_KEY", ",", "dash_id", ")", "[", "0", "]", ")", "return", "build_response", "(", "dict", "(", "data", ...
Read dashboard content. Args: dash_id: dashboard id. Returns: A dict containing the content of that dashboard, not include the meta info.
[ "Read", "dashboard", "content", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/dash.py#L46-L56
train
litaotao/IPython-Dashboard
dashboard/server/resources/dash.py
DashData.put
def put(self, dash_id=0): """Update a dash meta and content, return updated dash content. Args: dash_id: dashboard id. Returns: A dict containing the updated content of that dashboard, not include the meta info. """ data = request.get_json() updated = self._update_dash(dash_id, data) return build_response(dict(data=updated, code=200))
python
def put(self, dash_id=0): """Update a dash meta and content, return updated dash content. Args: dash_id: dashboard id. Returns: A dict containing the updated content of that dashboard, not include the meta info. """ data = request.get_json() updated = self._update_dash(dash_id, data) return build_response(dict(data=updated, code=200))
[ "def", "put", "(", "self", ",", "dash_id", "=", "0", ")", ":", "data", "=", "request", ".", "get_json", "(", ")", "updated", "=", "self", ".", "_update_dash", "(", "dash_id", ",", "data", ")", "return", "build_response", "(", "dict", "(", "data", "="...
Update a dash meta and content, return updated dash content. Args: dash_id: dashboard id. Returns: A dict containing the updated content of that dashboard, not include the meta info.
[ "Update", "a", "dash", "meta", "and", "content", "return", "updated", "dash", "content", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/dash.py#L58-L69
train
litaotao/IPython-Dashboard
dashboard/server/resources/dash.py
DashData.delete
def delete(self, dash_id): """Delete a dash meta and content, return updated dash content. Actually, just remove it to a specfied place in database. Args: dash_id: dashboard id. Returns: Redirect to home page. """ removed_info = dict( time_modified = r_db.zscore(config.DASH_ID_KEY, dash_id), meta = r_db.hget(config.DASH_META_KEY, dash_id), content = r_db.hget(config.DASH_CONTENT_KEY, dash_id)) r_db.zrem(config.DASH_ID_KEY, dash_id) r_db.hdel(config.DASH_META_KEY, dash_id) r_db.hdel(config.DASH_CONTENT_KEY, dash_id) return {'removed_info': removed_info}
python
def delete(self, dash_id): """Delete a dash meta and content, return updated dash content. Actually, just remove it to a specfied place in database. Args: dash_id: dashboard id. Returns: Redirect to home page. """ removed_info = dict( time_modified = r_db.zscore(config.DASH_ID_KEY, dash_id), meta = r_db.hget(config.DASH_META_KEY, dash_id), content = r_db.hget(config.DASH_CONTENT_KEY, dash_id)) r_db.zrem(config.DASH_ID_KEY, dash_id) r_db.hdel(config.DASH_META_KEY, dash_id) r_db.hdel(config.DASH_CONTENT_KEY, dash_id) return {'removed_info': removed_info}
[ "def", "delete", "(", "self", ",", "dash_id", ")", ":", "removed_info", "=", "dict", "(", "time_modified", "=", "r_db", ".", "zscore", "(", "config", ".", "DASH_ID_KEY", ",", "dash_id", ")", ",", "meta", "=", "r_db", ".", "hget", "(", "config", ".", ...
Delete a dash meta and content, return updated dash content. Actually, just remove it to a specfied place in database. Args: dash_id: dashboard id. Returns: Redirect to home page.
[ "Delete", "a", "dash", "meta", "and", "content", "return", "updated", "dash", "content", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/dash.py#L71-L89
train
totalgood/nlpia
src/nlpia/translate.py
main
def main( lang='deu', n=900, epochs=50, batch_size=64, num_neurons=256, encoder_input_data=None, decoder_input_data=None, decoder_target_data=None, checkpoint_dir=os.path.join(BIGDATA_PATH, 'checkpoints'), ): """ Train an LSTM encoder-decoder squence-to-sequence model on Anki flashcards for international translation >>> model = main('spa', n=400, epochs=3, batch_size=128, num_neurons=32) Train on 360 samples, validate on 40 samples Epoch 1/3 ... >>> len(model.get_weights()) 8 # 64 common characters in German, 56 in English >>> model.get_weights()[-1].shape[0] >=50 True >>> model.get_weights()[-2].shape[0] 32 """ mkdir_p(checkpoint_dir) encoder_input_path = os.path.join( checkpoint_dir, 'nlpia-ch10-translate-input-{}.npy'.format(lang)) decoder_input_path = os.path.join( checkpoint_dir, 'nlpia-ch10-translate-decoder-input-{}.npy'.format(lang)) decoder_target_path = os.path.join( checkpoint_dir, 'nlpia-ch10-translate-target-{}.npy'.format('eng')) data_paths = (encoder_input_path, decoder_input_path, decoder_target_path) encoder_input_data = [] if all([os.path.isfile(p) for p in data_paths]): encoder_input_data = np.load(encoder_input_path) decoder_input_data = np.load(decoder_input_path) decoder_target_data = np.load(decoder_target_path) if len(encoder_input_data) < n: encoder_input_data, decoder_input_data, decoder_target_data = onehot_char_training_data( lang=lang, n=n, data_paths=data_paths) encoder_input_data = encoder_input_data[:n] decoder_input_data = decoder_input_data[:n] decoder_target_data = decoder_target_data[:n] model = fit(data_paths=data_paths, epochs=epochs, batch_size=batch_size, num_neurons=num_neurons) return model
python
def main( lang='deu', n=900, epochs=50, batch_size=64, num_neurons=256, encoder_input_data=None, decoder_input_data=None, decoder_target_data=None, checkpoint_dir=os.path.join(BIGDATA_PATH, 'checkpoints'), ): """ Train an LSTM encoder-decoder squence-to-sequence model on Anki flashcards for international translation >>> model = main('spa', n=400, epochs=3, batch_size=128, num_neurons=32) Train on 360 samples, validate on 40 samples Epoch 1/3 ... >>> len(model.get_weights()) 8 # 64 common characters in German, 56 in English >>> model.get_weights()[-1].shape[0] >=50 True >>> model.get_weights()[-2].shape[0] 32 """ mkdir_p(checkpoint_dir) encoder_input_path = os.path.join( checkpoint_dir, 'nlpia-ch10-translate-input-{}.npy'.format(lang)) decoder_input_path = os.path.join( checkpoint_dir, 'nlpia-ch10-translate-decoder-input-{}.npy'.format(lang)) decoder_target_path = os.path.join( checkpoint_dir, 'nlpia-ch10-translate-target-{}.npy'.format('eng')) data_paths = (encoder_input_path, decoder_input_path, decoder_target_path) encoder_input_data = [] if all([os.path.isfile(p) for p in data_paths]): encoder_input_data = np.load(encoder_input_path) decoder_input_data = np.load(decoder_input_path) decoder_target_data = np.load(decoder_target_path) if len(encoder_input_data) < n: encoder_input_data, decoder_input_data, decoder_target_data = onehot_char_training_data( lang=lang, n=n, data_paths=data_paths) encoder_input_data = encoder_input_data[:n] decoder_input_data = decoder_input_data[:n] decoder_target_data = decoder_target_data[:n] model = fit(data_paths=data_paths, epochs=epochs, batch_size=batch_size, num_neurons=num_neurons) return model
[ "def", "main", "(", "lang", "=", "'deu'", ",", "n", "=", "900", ",", "epochs", "=", "50", ",", "batch_size", "=", "64", ",", "num_neurons", "=", "256", ",", "encoder_input_data", "=", "None", ",", "decoder_input_data", "=", "None", ",", "decoder_target_d...
Train an LSTM encoder-decoder squence-to-sequence model on Anki flashcards for international translation >>> model = main('spa', n=400, epochs=3, batch_size=128, num_neurons=32) Train on 360 samples, validate on 40 samples Epoch 1/3 ... >>> len(model.get_weights()) 8 # 64 common characters in German, 56 in English >>> model.get_weights()[-1].shape[0] >=50 True >>> model.get_weights()[-2].shape[0] 32
[ "Train", "an", "LSTM", "encoder", "-", "decoder", "squence", "-", "to", "-", "sequence", "model", "on", "Anki", "flashcards", "for", "international", "translation" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/translate.py#L202-L248
train
totalgood/nlpia
src/nlpia/book/forum/boltz.py
BoltzmanMachine.energy
def energy(self, v, h=None): """Compute the global energy for the current joint state of all nodes >>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]]) >>> q11_4.configurations() >>> v1v2h = product([0, 1], [0, 1], [0, 1]) >>> E = np.array([q11_4.energy(v=x[0:2], h=[x[2]]) for x in v1v2h]) >>> expnegE = np.exp(-E) >>> sumexpnegE = np.sum(expnegE) >>> pvh = np.array([ene / sumexpnegE for ene in expnegE]) >>> pv = [0] * len(df) >>> num_hid_states = 2 ** self.Nh >>> for i in range(len(df)): j = int(i / num_hid_states) pv[i] = sum(pvh[k] for k in range(j * num_hid_states, (j + 1) * num_hid_states)) >>> pd.DataFrame(tablify(v1v2h, -E, expnegE, pvh, pv), columns='v1 v2 h -E exp(-E) p(v,h), p(v)'.split()) """ h = np.zeros(self.Nh) if h is None else h negE = np.dot(v, self.bv) negE += np.dot(h, self.bh) for j in range(self.Nv): for i in range(j): negE += v[i] * v[j] * self.Wvv[i][j] for i in range(self.Nv): for k in range(self.Nh): negE += v[i] * h[k] * self.Wvh[i][k] for l in range(self.Nh): for k in range(l): negE += h[k] * h[l] * self.Whh[k][l] return -negE
python
def energy(self, v, h=None): """Compute the global energy for the current joint state of all nodes >>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]]) >>> q11_4.configurations() >>> v1v2h = product([0, 1], [0, 1], [0, 1]) >>> E = np.array([q11_4.energy(v=x[0:2], h=[x[2]]) for x in v1v2h]) >>> expnegE = np.exp(-E) >>> sumexpnegE = np.sum(expnegE) >>> pvh = np.array([ene / sumexpnegE for ene in expnegE]) >>> pv = [0] * len(df) >>> num_hid_states = 2 ** self.Nh >>> for i in range(len(df)): j = int(i / num_hid_states) pv[i] = sum(pvh[k] for k in range(j * num_hid_states, (j + 1) * num_hid_states)) >>> pd.DataFrame(tablify(v1v2h, -E, expnegE, pvh, pv), columns='v1 v2 h -E exp(-E) p(v,h), p(v)'.split()) """ h = np.zeros(self.Nh) if h is None else h negE = np.dot(v, self.bv) negE += np.dot(h, self.bh) for j in range(self.Nv): for i in range(j): negE += v[i] * v[j] * self.Wvv[i][j] for i in range(self.Nv): for k in range(self.Nh): negE += v[i] * h[k] * self.Wvh[i][k] for l in range(self.Nh): for k in range(l): negE += h[k] * h[l] * self.Whh[k][l] return -negE
[ "def", "energy", "(", "self", ",", "v", ",", "h", "=", "None", ")", ":", "h", "=", "np", ".", "zeros", "(", "self", ".", "Nh", ")", "if", "h", "is", "None", "else", "h", "negE", "=", "np", ".", "dot", "(", "v", ",", "self", ".", "bv", ")"...
Compute the global energy for the current joint state of all nodes >>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]]) >>> q11_4.configurations() >>> v1v2h = product([0, 1], [0, 1], [0, 1]) >>> E = np.array([q11_4.energy(v=x[0:2], h=[x[2]]) for x in v1v2h]) >>> expnegE = np.exp(-E) >>> sumexpnegE = np.sum(expnegE) >>> pvh = np.array([ene / sumexpnegE for ene in expnegE]) >>> pv = [0] * len(df) >>> num_hid_states = 2 ** self.Nh >>> for i in range(len(df)): j = int(i / num_hid_states) pv[i] = sum(pvh[k] for k in range(j * num_hid_states, (j + 1) * num_hid_states)) >>> pd.DataFrame(tablify(v1v2h, -E, expnegE, pvh, pv), columns='v1 v2 h -E exp(-E) p(v,h), p(v)'.split())
[ "Compute", "the", "global", "energy", "for", "the", "current", "joint", "state", "of", "all", "nodes" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/forum/boltz.py#L103-L133
train
totalgood/nlpia
src/nlpia/book/forum/boltz.py
Hopfield.energy
def energy(self): r""" Compute the global energy for the current joint state of all nodes - sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)]) E = − ∑ s i b i − ∑ i i< j s i s j w ij """ s, b, W, N = self.state, self.b, self.W, self.N self.E = - sum(s * b) - sum([s[i] * s[j] * W[i, j] for (i, j) in product(range(N), range(N)) if i < j]) self.low_energies[-1] = self.E self.low_energies.sort() self.high_energies[-1] = self.E self.high_energies.sort() self.high_energies = self.high_energies[::-1] return self.E
python
def energy(self): r""" Compute the global energy for the current joint state of all nodes - sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)]) E = − ∑ s i b i − ∑ i i< j s i s j w ij """ s, b, W, N = self.state, self.b, self.W, self.N self.E = - sum(s * b) - sum([s[i] * s[j] * W[i, j] for (i, j) in product(range(N), range(N)) if i < j]) self.low_energies[-1] = self.E self.low_energies.sort() self.high_energies[-1] = self.E self.high_energies.sort() self.high_energies = self.high_energies[::-1] return self.E
[ "def", "energy", "(", "self", ")", ":", "r", "s", ",", "b", ",", "W", ",", "N", "=", "self", ".", "state", ",", "self", ".", "b", ",", "self", ".", "W", ",", "self", ".", "N", "self", ".", "E", "=", "-", "sum", "(", "s", "*", "b", ")", ...
r""" Compute the global energy for the current joint state of all nodes - sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)]) E = − ∑ s i b i − ∑ i i< j s i s j w ij
[ "r", "Compute", "the", "global", "energy", "for", "the", "current", "joint", "state", "of", "all", "nodes" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/forum/boltz.py#L210-L226
train
totalgood/nlpia
src/nlpia/translators.py
HyperlinkStyleCorrector.translate
def translate(self, text, to_template='{name} ({url})', from_template=None, name_matcher=None, url_matcher=None): """ Translate hyperinks into printable book style for Manning Publishing >>> translator = HyperlinkStyleCorrector() >>> adoc = 'See http://totalgood.com[Total Good] about that.' >>> translator.translate(adoc) 'See Total Good (http://totalgood.com) about that.' """ return self.replace(text, to_template=to_template, from_template=from_template, name_matcher=name_matcher, url_matcher=url_matcher)
python
def translate(self, text, to_template='{name} ({url})', from_template=None, name_matcher=None, url_matcher=None): """ Translate hyperinks into printable book style for Manning Publishing >>> translator = HyperlinkStyleCorrector() >>> adoc = 'See http://totalgood.com[Total Good] about that.' >>> translator.translate(adoc) 'See Total Good (http://totalgood.com) about that.' """ return self.replace(text, to_template=to_template, from_template=from_template, name_matcher=name_matcher, url_matcher=url_matcher)
[ "def", "translate", "(", "self", ",", "text", ",", "to_template", "=", "'{name} ({url})'", ",", "from_template", "=", "None", ",", "name_matcher", "=", "None", ",", "url_matcher", "=", "None", ")", ":", "return", "self", ".", "replace", "(", "text", ",", ...
Translate hyperinks into printable book style for Manning Publishing >>> translator = HyperlinkStyleCorrector() >>> adoc = 'See http://totalgood.com[Total Good] about that.' >>> translator.translate(adoc) 'See Total Good (http://totalgood.com) about that.'
[ "Translate", "hyperinks", "into", "printable", "book", "style", "for", "Manning", "Publishing" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/translators.py#L235-L244
train
totalgood/nlpia
src/nlpia/scripts/cleandialog.py
main
def main(dialogpath=None): """ Parse the state transition graph for a set of dialog-definition tables to find an fix deadends """ if dialogpath is None: args = parse_args() dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath)) else: dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath)) return clean_csvs(dialogpath=dialogpath)
python
def main(dialogpath=None): """ Parse the state transition graph for a set of dialog-definition tables to find an fix deadends """ if dialogpath is None: args = parse_args() dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath)) else: dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath)) return clean_csvs(dialogpath=dialogpath)
[ "def", "main", "(", "dialogpath", "=", "None", ")", ":", "if", "dialogpath", "is", "None", ":", "args", "=", "parse_args", "(", ")", "dialogpath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "args", ".", ...
Parse the state transition graph for a set of dialog-definition tables to find an fix deadends
[ "Parse", "the", "state", "transition", "graph", "for", "a", "set", "of", "dialog", "-", "definition", "tables", "to", "find", "an", "fix", "deadends" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/cleandialog.py#L24-L31
train
totalgood/nlpia
src/nlpia/book/scripts/create_raw_ubuntu_dataset.py
prepare_data_maybe_download
def prepare_data_maybe_download(directory): """ Download and unpack dialogs if necessary. """ filename = 'ubuntu_dialogs.tgz' url = 'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz' dialogs_path = os.path.join(directory, 'dialogs') # test it there are some dialogs in the path if not os.path.exists(os.path.join(directory, "10", "1.tst")): # dialogs are missing archive_path = os.path.join(directory, filename) if not os.path.exists(archive_path): # archive missing, download it print("Downloading %s to %s" % (url, archive_path)) filepath, _ = urllib.request.urlretrieve(url, archive_path) print "Successfully downloaded " + filepath # unpack data if not os.path.exists(dialogs_path): print("Unpacking dialogs ...") with tarfile.open(archive_path) as tar: tar.extractall(path=directory) print("Archive unpacked.") return
python
def prepare_data_maybe_download(directory): """ Download and unpack dialogs if necessary. """ filename = 'ubuntu_dialogs.tgz' url = 'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz' dialogs_path = os.path.join(directory, 'dialogs') # test it there are some dialogs in the path if not os.path.exists(os.path.join(directory, "10", "1.tst")): # dialogs are missing archive_path = os.path.join(directory, filename) if not os.path.exists(archive_path): # archive missing, download it print("Downloading %s to %s" % (url, archive_path)) filepath, _ = urllib.request.urlretrieve(url, archive_path) print "Successfully downloaded " + filepath # unpack data if not os.path.exists(dialogs_path): print("Unpacking dialogs ...") with tarfile.open(archive_path) as tar: tar.extractall(path=directory) print("Archive unpacked.") return
[ "def", "prepare_data_maybe_download", "(", "directory", ")", ":", "filename", "=", "'ubuntu_dialogs.tgz'", "url", "=", "'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz'", "dialogs_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",",...
Download and unpack dialogs if necessary.
[ "Download", "and", "unpack", "dialogs", "if", "necessary", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/scripts/create_raw_ubuntu_dataset.py#L252-L277
train
totalgood/nlpia
src/nlpia/skeleton.py
fib
def fib(n): """Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number """ assert n > 0 a, b = 1, 1 for i in range(n - 1): a, b = b, a + b return a
python
def fib(n): """Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number """ assert n > 0 a, b = 1, 1 for i in range(n - 1): a, b = b, a + b return a
[ "def", "fib", "(", "n", ")", ":", "assert", "n", ">", "0", "a", ",", "b", "=", "1", ",", "1", "for", "i", "in", "range", "(", "n", "-", "1", ")", ":", "a", ",", "b", "=", "b", ",", "a", "+", "b", "return", "a" ]
Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number
[ "Fibonacci", "example", "function" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/skeleton.py#L37-L50
train
totalgood/nlpia
src/nlpia/skeleton.py
main
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.debug("Starting crazy calculations...") print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n))) _logger.info("Script ends here")
python
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.debug("Starting crazy calculations...") print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n))) _logger.info("Script ends here")
[ "def", "main", "(", "args", ")", ":", "args", "=", "parse_args", "(", "args", ")", "setup_logging", "(", "args", ".", "loglevel", ")", "_logger", ".", "debug", "(", "\"Starting crazy calculations...\"", ")", "print", "(", "\"The {}-th Fibonacci number is {}\"", ...
Main entry point allowing external calls Args: args ([str]): command line parameter list
[ "Main", "entry", "point", "allowing", "external", "calls" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/skeleton.py#L101-L111
train
totalgood/nlpia
src/nlpia/features.py
optimize_feature_power
def optimize_feature_power(df, output_column_name=None, exponents=[2., 1., .8, .5, .25, .1, .01]): """ Plot the correlation coefficient for various exponential scalings of input features >>> np.random.seed(314159) >>> df = pd.DataFrame() >>> df['output'] = np.random.randn(1000) >>> df['x10'] = df.output * 10 >>> df['sq'] = df.output ** 2 >>> df['sqrt'] = df.output ** .5 >>> optimize_feature_power(df, output_column_name='output').round(2) x10 sq sqrt power 2.00 -0.08 1.00 0.83 1.00 1.00 -0.08 0.97 0.80 1.00 0.90 0.99 0.50 0.97 0.83 1.00 0.25 0.93 0.76 0.99 0.10 0.89 0.71 0.97 0.01 0.86 0.67 0.95 Returns: DataFrame: columns are the input_columns from the source dataframe (df) rows are correlation with output for each attempted exponent used to scale the input features """ output_column_name = list(df.columns)[-1] if output_column_name is None else output_column_name input_column_names = [colname for colname in df.columns if output_column_name != colname] results = np.zeros((len(exponents), len(input_column_names))) for rownum, exponent in enumerate(exponents): for colnum, column_name in enumerate(input_column_names): results[rownum, colnum] = (df[output_column_name] ** exponent).corr(df[column_name]) results = pd.DataFrame(results, columns=input_column_names, index=pd.Series(exponents, name='power')) # results.plot(logx=True) return results
python
def optimize_feature_power(df, output_column_name=None, exponents=[2., 1., .8, .5, .25, .1, .01]): """ Plot the correlation coefficient for various exponential scalings of input features >>> np.random.seed(314159) >>> df = pd.DataFrame() >>> df['output'] = np.random.randn(1000) >>> df['x10'] = df.output * 10 >>> df['sq'] = df.output ** 2 >>> df['sqrt'] = df.output ** .5 >>> optimize_feature_power(df, output_column_name='output').round(2) x10 sq sqrt power 2.00 -0.08 1.00 0.83 1.00 1.00 -0.08 0.97 0.80 1.00 0.90 0.99 0.50 0.97 0.83 1.00 0.25 0.93 0.76 0.99 0.10 0.89 0.71 0.97 0.01 0.86 0.67 0.95 Returns: DataFrame: columns are the input_columns from the source dataframe (df) rows are correlation with output for each attempted exponent used to scale the input features """ output_column_name = list(df.columns)[-1] if output_column_name is None else output_column_name input_column_names = [colname for colname in df.columns if output_column_name != colname] results = np.zeros((len(exponents), len(input_column_names))) for rownum, exponent in enumerate(exponents): for colnum, column_name in enumerate(input_column_names): results[rownum, colnum] = (df[output_column_name] ** exponent).corr(df[column_name]) results = pd.DataFrame(results, columns=input_column_names, index=pd.Series(exponents, name='power')) # results.plot(logx=True) return results
[ "def", "optimize_feature_power", "(", "df", ",", "output_column_name", "=", "None", ",", "exponents", "=", "[", "2.", ",", "1.", ",", ".8", ",", ".5", ",", ".25", ",", ".1", ",", ".01", "]", ")", ":", "output_column_name", "=", "list", "(", "df", "."...
Plot the correlation coefficient for various exponential scalings of input features >>> np.random.seed(314159) >>> df = pd.DataFrame() >>> df['output'] = np.random.randn(1000) >>> df['x10'] = df.output * 10 >>> df['sq'] = df.output ** 2 >>> df['sqrt'] = df.output ** .5 >>> optimize_feature_power(df, output_column_name='output').round(2) x10 sq sqrt power 2.00 -0.08 1.00 0.83 1.00 1.00 -0.08 0.97 0.80 1.00 0.90 0.99 0.50 0.97 0.83 1.00 0.25 0.93 0.76 0.99 0.10 0.89 0.71 0.97 0.01 0.86 0.67 0.95 Returns: DataFrame: columns are the input_columns from the source dataframe (df) rows are correlation with output for each attempted exponent used to scale the input features
[ "Plot", "the", "correlation", "coefficient", "for", "various", "exponential", "scalings", "of", "input", "features" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/features.py#L5-L38
train
totalgood/nlpia
src/nlpia/highd.py
representative_sample
def representative_sample(X, num_samples, save=False): """Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set """ X = X.values if hasattr(X, 'values') else np.array(X) N, M = X.shape rownums = np.arange(N) np.random.shuffle(rownums) idx = AnnoyIndex(M) for i, row in enumerate(X): idx.add_item(i, row) idx.build(int(np.log2(N)) + 1) if save: if isinstance(save, basestring): idxfilename = save else: idxfile = tempfile.NamedTemporaryFile(delete=False) idxfile.close() idxfilename = idxfile.name idx.save(idxfilename) idx = AnnoyIndex(M) idx.load(idxfile.name) samples = -1 * np.ones(shape=(num_samples,), dtype=int) samples[0] = rownums[0] # FIXME: some integer determined by N and num_samples and distribution j, num_nns = 0, min(1000, int(num_samples / 2. + 1)) for i in rownums: if i in samples: continue nns = idx.get_nns_by_item(i, num_nns) # FIXME: pick vector furthest from past K (K > 1) points or outside of a hypercube # (sized to uniformly fill the space) around the last sample samples[j + 1] = np.setdiff1d(nns, samples)[-1] if len(num_nns) < num_samples / 3.: num_nns = min(N, 1.3 * num_nns) j += 1 return samples
python
def representative_sample(X, num_samples, save=False): """Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set """ X = X.values if hasattr(X, 'values') else np.array(X) N, M = X.shape rownums = np.arange(N) np.random.shuffle(rownums) idx = AnnoyIndex(M) for i, row in enumerate(X): idx.add_item(i, row) idx.build(int(np.log2(N)) + 1) if save: if isinstance(save, basestring): idxfilename = save else: idxfile = tempfile.NamedTemporaryFile(delete=False) idxfile.close() idxfilename = idxfile.name idx.save(idxfilename) idx = AnnoyIndex(M) idx.load(idxfile.name) samples = -1 * np.ones(shape=(num_samples,), dtype=int) samples[0] = rownums[0] # FIXME: some integer determined by N and num_samples and distribution j, num_nns = 0, min(1000, int(num_samples / 2. + 1)) for i in rownums: if i in samples: continue nns = idx.get_nns_by_item(i, num_nns) # FIXME: pick vector furthest from past K (K > 1) points or outside of a hypercube # (sized to uniformly fill the space) around the last sample samples[j + 1] = np.setdiff1d(nns, samples)[-1] if len(num_nns) < num_samples / 3.: num_nns = min(N, 1.3 * num_nns) j += 1 return samples
[ "def", "representative_sample", "(", "X", ",", "num_samples", ",", "save", "=", "False", ")", ":", "X", "=", "X", ".", "values", "if", "hasattr", "(", "X", ",", "'values'", ")", "else", "np", ".", "array", "(", "X", ")", "N", ",", "M", "=", "X", ...
Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set
[ "Sample", "vectors", "in", "X", "preferring", "edge", "cases", "and", "vectors", "farthest", "from", "other", "vectors", "in", "sample", "set" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/highd.py#L28-L68
train
totalgood/nlpia
src/nlpia/book/examples/ch03-2.py
cosine_sim
def cosine_sim(vec1, vec2): """ Since our vectors are dictionaries, lets convert them to lists for easier mathing. """ vec1 = [val for val in vec1.values()] vec2 = [val for val in vec2.values()] dot_prod = 0 for i, v in enumerate(vec1): dot_prod += v * vec2[i] mag_1 = math.sqrt(sum([x**2 for x in vec1])) mag_2 = math.sqrt(sum([x**2 for x in vec2])) return dot_prod / (mag_1 * mag_2)
python
def cosine_sim(vec1, vec2): """ Since our vectors are dictionaries, lets convert them to lists for easier mathing. """ vec1 = [val for val in vec1.values()] vec2 = [val for val in vec2.values()] dot_prod = 0 for i, v in enumerate(vec1): dot_prod += v * vec2[i] mag_1 = math.sqrt(sum([x**2 for x in vec1])) mag_2 = math.sqrt(sum([x**2 for x in vec2])) return dot_prod / (mag_1 * mag_2)
[ "def", "cosine_sim", "(", "vec1", ",", "vec2", ")", ":", "vec1", "=", "[", "val", "for", "val", "in", "vec1", ".", "values", "(", ")", "]", "vec2", "=", "[", "val", "for", "val", "in", "vec2", ".", "values", "(", ")", "]", "dot_prod", "=", "0",...
Since our vectors are dictionaries, lets convert them to lists for easier mathing.
[ "Since", "our", "vectors", "are", "dictionaries", "lets", "convert", "them", "to", "lists", "for", "easier", "mathing", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch03-2.py#L141-L155
train
totalgood/nlpia
src/nlpia/models.py
LinearRegressor.fit
def fit(self, X, y): """ Compute average slope and intercept for all X, y pairs Arguments: X (np.array): model input (independent variable) y (np.array): model output (dependent variable) Returns: Linear Regression instance with `slope` and `intercept` attributes References: Based on: https://github.com/justmarkham/DAT4/blob/master/notebooks/08_linear_regression.ipynb >>> n_samples = 100 >>> X = np.arange(100).reshape((n_samples, 1)) >>> slope, intercept = 3.14159, -4.242 >>> y = 3.14 * X + np.random.randn(*X.shape) + intercept >>> line = LinearRegressor() >>> line.fit(X, y) <nlpia.models.LinearRegressor object ... >>> abs(line.slope - slope) < abs(0.02 * (slope + 1)) True >>> abs(line.intercept - intercept) < 0.2 * (abs(intercept) + 1) True """ # initial sums n = float(len(X)) sum_x = X.sum() sum_y = y.sum() sum_xy = (X * y).sum() sum_xx = (X**2).sum() # formula for w0 self.slope = (sum_xy - (sum_x * sum_y) / n) / (sum_xx - (sum_x * sum_x) / n) # formula for w1 self.intercept = sum_y / n - self.slope * (sum_x / n) return self
python
def fit(self, X, y): """ Compute average slope and intercept for all X, y pairs Arguments: X (np.array): model input (independent variable) y (np.array): model output (dependent variable) Returns: Linear Regression instance with `slope` and `intercept` attributes References: Based on: https://github.com/justmarkham/DAT4/blob/master/notebooks/08_linear_regression.ipynb >>> n_samples = 100 >>> X = np.arange(100).reshape((n_samples, 1)) >>> slope, intercept = 3.14159, -4.242 >>> y = 3.14 * X + np.random.randn(*X.shape) + intercept >>> line = LinearRegressor() >>> line.fit(X, y) <nlpia.models.LinearRegressor object ... >>> abs(line.slope - slope) < abs(0.02 * (slope + 1)) True >>> abs(line.intercept - intercept) < 0.2 * (abs(intercept) + 1) True """ # initial sums n = float(len(X)) sum_x = X.sum() sum_y = y.sum() sum_xy = (X * y).sum() sum_xx = (X**2).sum() # formula for w0 self.slope = (sum_xy - (sum_x * sum_y) / n) / (sum_xx - (sum_x * sum_x) / n) # formula for w1 self.intercept = sum_y / n - self.slope * (sum_x / n) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "n", "=", "float", "(", "len", "(", "X", ")", ")", "sum_x", "=", "X", ".", "sum", "(", ")", "sum_y", "=", "y", ".", "sum", "(", ")", "sum_xy", "=", "(", "X", "*", "y", ")", ".", ...
Compute average slope and intercept for all X, y pairs Arguments: X (np.array): model input (independent variable) y (np.array): model output (dependent variable) Returns: Linear Regression instance with `slope` and `intercept` attributes References: Based on: https://github.com/justmarkham/DAT4/blob/master/notebooks/08_linear_regression.ipynb >>> n_samples = 100 >>> X = np.arange(100).reshape((n_samples, 1)) >>> slope, intercept = 3.14159, -4.242 >>> y = 3.14 * X + np.random.randn(*X.shape) + intercept >>> line = LinearRegressor() >>> line.fit(X, y) <nlpia.models.LinearRegressor object ... >>> abs(line.slope - slope) < abs(0.02 * (slope + 1)) True >>> abs(line.intercept - intercept) < 0.2 * (abs(intercept) + 1) True
[ "Compute", "average", "slope", "and", "intercept", "for", "all", "X", "y", "pairs" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/models.py#L15-L54
train
totalgood/nlpia
src/nlpia/web.py
looks_like_url
def looks_like_url(url): """ Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True """ if not isinstance(url, basestring): return False if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url): return False return True
python
def looks_like_url(url): """ Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True """ if not isinstance(url, basestring): return False if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url): return False return True
[ "def", "looks_like_url", "(", "url", ")", ":", "if", "not", "isinstance", "(", "url", ",", "basestring", ")", ":", "return", "False", "if", "not", "isinstance", "(", "url", ",", "basestring", ")", "or", "len", "(", "url", ")", ">=", "1024", "or", "no...
Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True
[ "Simplified", "check", "to", "see", "if", "the", "text", "appears", "to", "be", "a", "URL", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L68-L85
train
totalgood/nlpia
src/nlpia/web.py
try_parse_url
def try_parse_url(url): """ User urlparse to try to parse URL returning None on exception """ if len(url.strip()) < 4: logger.info('URL too short: {}'.format(url)) return None try: parsed_url = urlparse(url) except ValueError: logger.info('Parse URL ValueError: {}'.format(url)) return None if parsed_url.scheme: return parsed_url try: parsed_url = urlparse('http://' + parsed_url.geturl()) except ValueError: logger.info('Invalid URL for assumed http scheme: urlparse("{}") from "{}" '.format('http://' + parsed_url.geturl(), url)) return None if not parsed_url.scheme: logger.info('Unable to guess a scheme for URL: {}'.format(url)) return None return parsed_url
python
def try_parse_url(url): """ User urlparse to try to parse URL returning None on exception """ if len(url.strip()) < 4: logger.info('URL too short: {}'.format(url)) return None try: parsed_url = urlparse(url) except ValueError: logger.info('Parse URL ValueError: {}'.format(url)) return None if parsed_url.scheme: return parsed_url try: parsed_url = urlparse('http://' + parsed_url.geturl()) except ValueError: logger.info('Invalid URL for assumed http scheme: urlparse("{}") from "{}" '.format('http://' + parsed_url.geturl(), url)) return None if not parsed_url.scheme: logger.info('Unable to guess a scheme for URL: {}'.format(url)) return None return parsed_url
[ "def", "try_parse_url", "(", "url", ")", ":", "if", "len", "(", "url", ".", "strip", "(", ")", ")", "<", "4", ":", "logger", ".", "info", "(", "'URL too short: {}'", ".", "format", "(", "url", ")", ")", "return", "None", "try", ":", "parsed_url", "...
User urlparse to try to parse URL returning None on exception
[ "User", "urlparse", "to", "try", "to", "parse", "URL", "returning", "None", "on", "exception" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L88-L108
train
totalgood/nlpia
src/nlpia/web.py
get_url_filemeta
def get_url_filemeta(url): """ Request HTML for the page at the URL indicated and return the url, filename, and remote size TODO: just add remote_size and basename and filename attributes to the urlparse object instead of returning a dict >>> sorted(get_url_filemeta('mozilla.com').items()) [('filename', ''), ('hostname', 'mozilla.com'), ('path', ''), ('remote_size', -1), ('url', 'http://mozilla.com'), ('username', None)] >>> sorted(get_url_filemeta('https://duckduckgo.com/about?q=nlp').items()) [('filename', 'about'), ('hostname', 'duckduckgo.com'), ('path', '/about'), ('remote_size', -1), ('url', 'https://duckduckgo.com/about?q=nlp'), ('username', None)] >>> 1000 <= int(get_url_filemeta('en.wikipedia.org')['remote_size']) <= 200000 True """ parsed_url = try_parse_url(url) if parsed_url is None: return None if parsed_url.scheme.startswith('ftp'): return get_ftp_filemeta(parsed_url) url = parsed_url.geturl() try: r = requests.get(url, stream=True, allow_redirects=True, timeout=5) remote_size = r.headers.get('Content-Length', -1) return dict(url=url, hostname=parsed_url.hostname, path=parsed_url.path, username=parsed_url.username, remote_size=remote_size, filename=os.path.basename(parsed_url.path)) except ConnectionError: return None except (InvalidURL, InvalidSchema, InvalidHeader, MissingSchema): return None return None
python
def get_url_filemeta(url): """ Request HTML for the page at the URL indicated and return the url, filename, and remote size TODO: just add remote_size and basename and filename attributes to the urlparse object instead of returning a dict >>> sorted(get_url_filemeta('mozilla.com').items()) [('filename', ''), ('hostname', 'mozilla.com'), ('path', ''), ('remote_size', -1), ('url', 'http://mozilla.com'), ('username', None)] >>> sorted(get_url_filemeta('https://duckduckgo.com/about?q=nlp').items()) [('filename', 'about'), ('hostname', 'duckduckgo.com'), ('path', '/about'), ('remote_size', -1), ('url', 'https://duckduckgo.com/about?q=nlp'), ('username', None)] >>> 1000 <= int(get_url_filemeta('en.wikipedia.org')['remote_size']) <= 200000 True """ parsed_url = try_parse_url(url) if parsed_url is None: return None if parsed_url.scheme.startswith('ftp'): return get_ftp_filemeta(parsed_url) url = parsed_url.geturl() try: r = requests.get(url, stream=True, allow_redirects=True, timeout=5) remote_size = r.headers.get('Content-Length', -1) return dict(url=url, hostname=parsed_url.hostname, path=parsed_url.path, username=parsed_url.username, remote_size=remote_size, filename=os.path.basename(parsed_url.path)) except ConnectionError: return None except (InvalidURL, InvalidSchema, InvalidHeader, MissingSchema): return None return None
[ "def", "get_url_filemeta", "(", "url", ")", ":", "parsed_url", "=", "try_parse_url", "(", "url", ")", "if", "parsed_url", "is", "None", ":", "return", "None", "if", "parsed_url", ".", "scheme", ".", "startswith", "(", "'ftp'", ")", ":", "return", "get_ftp_...
Request HTML for the page at the URL indicated and return the url, filename, and remote size TODO: just add remote_size and basename and filename attributes to the urlparse object instead of returning a dict >>> sorted(get_url_filemeta('mozilla.com').items()) [('filename', ''), ('hostname', 'mozilla.com'), ('path', ''), ('remote_size', -1), ('url', 'http://mozilla.com'), ('username', None)] >>> sorted(get_url_filemeta('https://duckduckgo.com/about?q=nlp').items()) [('filename', 'about'), ('hostname', 'duckduckgo.com'), ('path', '/about'), ('remote_size', -1), ('url', 'https://duckduckgo.com/about?q=nlp'), ('username', None)] >>> 1000 <= int(get_url_filemeta('en.wikipedia.org')['remote_size']) <= 200000 True
[ "Request", "HTML", "for", "the", "page", "at", "the", "URL", "indicated", "and", "return", "the", "url", "filename", "and", "remote", "size" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L111-L152
train
totalgood/nlpia
src/nlpia/web.py
save_response_content
def save_response_content(response, filename='data.csv', destination=os.path.curdir, chunksize=32768): """ For streaming response from requests, download the content one CHUNK at a time """ chunksize = chunksize or 32768 if os.path.sep in filename: full_destination_path = filename else: full_destination_path = os.path.join(destination, filename) full_destination_path = expand_filepath(full_destination_path) with open(full_destination_path, "wb") as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out keep-alive new chunks f.write(chunk) return full_destination_path
python
def save_response_content(response, filename='data.csv', destination=os.path.curdir, chunksize=32768): """ For streaming response from requests, download the content one CHUNK at a time """ chunksize = chunksize or 32768 if os.path.sep in filename: full_destination_path = filename else: full_destination_path = os.path.join(destination, filename) full_destination_path = expand_filepath(full_destination_path) with open(full_destination_path, "wb") as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out keep-alive new chunks f.write(chunk) return full_destination_path
[ "def", "save_response_content", "(", "response", ",", "filename", "=", "'data.csv'", ",", "destination", "=", "os", ".", "path", ".", "curdir", ",", "chunksize", "=", "32768", ")", ":", "chunksize", "=", "chunksize", "or", "32768", "if", "os", ".", "path",...
For streaming response from requests, download the content one CHUNK at a time
[ "For", "streaming", "response", "from", "requests", "download", "the", "content", "one", "CHUNK", "at", "a", "time" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L209-L221
train
totalgood/nlpia
src/nlpia/web.py
download_file_from_google_drive
def download_file_from_google_drive(driveid, filename=None, destination=os.path.curdir): """ Download script for google drive shared links Thank you @turdus-merula and Andrew Hundt! https://stackoverflow.com/a/39225039/623735 """ if '&id=' in driveid: # https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfM1BxdkxVaTY2bWs # dailymail_stories.tgz driveid = driveid.split('&id=')[-1] if '?id=' in driveid: # 'https://drive.google.com/open?id=14mELuzm0OvXnwjb0mzAiG-Ake9_NP_LQ' # SSD pretrainined keras model driveid = driveid.split('?id=')[-1] URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params={'id': driveid}, stream=True) token = get_response_confirmation_token(response) if token: params = {'id': driveid, 'confirm': token} response = session.get(URL, params=params, stream=True) filename = filename or get_url_filename(driveid=driveid) full_destination_path = save_response_content(response, filename=fileanme, destination=destination) return os.path.abspath(destination)
python
def download_file_from_google_drive(driveid, filename=None, destination=os.path.curdir): """ Download script for google drive shared links Thank you @turdus-merula and Andrew Hundt! https://stackoverflow.com/a/39225039/623735 """ if '&id=' in driveid: # https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfM1BxdkxVaTY2bWs # dailymail_stories.tgz driveid = driveid.split('&id=')[-1] if '?id=' in driveid: # 'https://drive.google.com/open?id=14mELuzm0OvXnwjb0mzAiG-Ake9_NP_LQ' # SSD pretrainined keras model driveid = driveid.split('?id=')[-1] URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params={'id': driveid}, stream=True) token = get_response_confirmation_token(response) if token: params = {'id': driveid, 'confirm': token} response = session.get(URL, params=params, stream=True) filename = filename or get_url_filename(driveid=driveid) full_destination_path = save_response_content(response, filename=fileanme, destination=destination) return os.path.abspath(destination)
[ "def", "download_file_from_google_drive", "(", "driveid", ",", "filename", "=", "None", ",", "destination", "=", "os", ".", "path", ".", "curdir", ")", ":", "if", "'&id='", "in", "driveid", ":", "driveid", "=", "driveid", ".", "split", "(", "'&id='", ")", ...
Download script for google drive shared links Thank you @turdus-merula and Andrew Hundt! https://stackoverflow.com/a/39225039/623735
[ "Download", "script", "for", "google", "drive", "shared", "links" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L224-L252
train
totalgood/nlpia
src/nlpia/book/examples/ch11_greetings.py
find_greeting
def find_greeting(s): """ Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string >>> find_greeting('Hi Mr. Turing!') 'Hi' >>> find_greeting('Hello, Rosa.') 'Hello' >>> find_greeting("Yo, what's up?") 'Yo' >>> find_greeting("Hello") 'Hello' >>> print(find_greeting("hello")) None >>> print(find_greeting("HelloWorld")) None """ if s[0] == 'H': if s[:3] in ['Hi', 'Hi ', 'Hi,', 'Hi!']: return s[:2] elif s[:6] in ['Hello', 'Hello ', 'Hello,', 'Hello!']: return s[:5] elif s[0] == 'Y': if s[1] == 'o' and s[:3] in ['Yo', 'Yo,', 'Yo ', 'Yo!']: return s[:2] return None
python
def find_greeting(s): """ Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string >>> find_greeting('Hi Mr. Turing!') 'Hi' >>> find_greeting('Hello, Rosa.') 'Hello' >>> find_greeting("Yo, what's up?") 'Yo' >>> find_greeting("Hello") 'Hello' >>> print(find_greeting("hello")) None >>> print(find_greeting("HelloWorld")) None """ if s[0] == 'H': if s[:3] in ['Hi', 'Hi ', 'Hi,', 'Hi!']: return s[:2] elif s[:6] in ['Hello', 'Hello ', 'Hello,', 'Hello!']: return s[:5] elif s[0] == 'Y': if s[1] == 'o' and s[:3] in ['Yo', 'Yo,', 'Yo ', 'Yo!']: return s[:2] return None
[ "def", "find_greeting", "(", "s", ")", ":", "if", "s", "[", "0", "]", "==", "'H'", ":", "if", "s", "[", ":", "3", "]", "in", "[", "'Hi'", ",", "'Hi '", ",", "'Hi,'", ",", "'Hi!'", "]", ":", "return", "s", "[", ":", "2", "]", "elif", "s", ...
Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string >>> find_greeting('Hi Mr. Turing!') 'Hi' >>> find_greeting('Hello, Rosa.') 'Hello' >>> find_greeting("Yo, what's up?") 'Yo' >>> find_greeting("Hello") 'Hello' >>> print(find_greeting("hello")) None >>> print(find_greeting("HelloWorld")) None
[ "Return", "the", "the", "greeting", "string", "Hi", "Hello", "or", "Yo", "if", "it", "occurs", "at", "the", "beginning", "of", "a", "string" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch11_greetings.py#L4-L28
train
totalgood/nlpia
src/nlpia/scripts/hunspell_to_json.py
file_to_list
def file_to_list(in_file): ''' Reads file into list ''' lines = [] for line in in_file: # Strip new line line = line.strip('\n') # Ignore empty lines if line != '': # Ignore comments if line[0] != '#': lines.append(line) return lines
python
def file_to_list(in_file): ''' Reads file into list ''' lines = [] for line in in_file: # Strip new line line = line.strip('\n') # Ignore empty lines if line != '': # Ignore comments if line[0] != '#': lines.append(line) return lines
[ "def", "file_to_list", "(", "in_file", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "in_file", ":", "line", "=", "line", ".", "strip", "(", "'\\n'", ")", "if", "line", "!=", "''", ":", "if", "line", "[", "0", "]", "!=", "'#'", ":", "l...
Reads file into list
[ "Reads", "file", "into", "list" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L39-L52
train
totalgood/nlpia
src/nlpia/scripts/hunspell_to_json.py
CompoundRule.add_flag_values
def add_flag_values(self, entry, flag): ''' Adds flag value to applicable compounds ''' if flag in self.flags: self.flags[flag].append(entry)
python
def add_flag_values(self, entry, flag): ''' Adds flag value to applicable compounds ''' if flag in self.flags: self.flags[flag].append(entry)
[ "def", "add_flag_values", "(", "self", ",", "entry", ",", "flag", ")", ":", "if", "flag", "in", "self", ".", "flags", ":", "self", ".", "flags", "[", "flag", "]", ".", "append", "(", "entry", ")" ]
Adds flag value to applicable compounds
[ "Adds", "flag", "value", "to", "applicable", "compounds" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L110-L113
train
totalgood/nlpia
src/nlpia/scripts/hunspell_to_json.py
CompoundRule.get_regex
def get_regex(self): ''' Generates and returns compound regular expression ''' regex = '' for flag in self.compound: if flag == '?' or flag == '*': regex += flag else: regex += '(' + '|'.join(self.flags[flag]) + ')' return regex
python
def get_regex(self): ''' Generates and returns compound regular expression ''' regex = '' for flag in self.compound: if flag == '?' or flag == '*': regex += flag else: regex += '(' + '|'.join(self.flags[flag]) + ')' return regex
[ "def", "get_regex", "(", "self", ")", ":", "regex", "=", "''", "for", "flag", "in", "self", ".", "compound", ":", "if", "flag", "==", "'?'", "or", "flag", "==", "'*'", ":", "regex", "+=", "flag", "else", ":", "regex", "+=", "'('", "+", "'|'", "."...
Generates and returns compound regular expression
[ "Generates", "and", "returns", "compound", "regular", "expression" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L115-L124
train
totalgood/nlpia
src/nlpia/scripts/hunspell_to_json.py
DICT.__parse_dict
def __parse_dict(self): ''' Parses dictionary with according rules ''' i = 0 lines = self.lines for line in lines: line = line.split('/') word = line[0] flags = line[1] if len(line) > 1 else None # Base Word self.num_words += 1 if flags != None: # Derivatives possible for flag in flags: # Compound? if flag in self.aff.compound_flags or flag == self.aff.only_in_compound_flag: for rule in self.aff.compound_rules: rule.add_flag_values(word, flag) else: # No Suggest flags if self.aff.no_suggest_flag == flag: pass else: affix_rule_entries = self.aff.affix_rules[flag] # Get flag that meets condition for i in range(len(affix_rule_entries)): rule = affix_rule_entries[i] if rule.meets_condition(word): # Add word to list if does not already exist if word not in self.words: self.words[word] = [] # Derivatives self.num_words += 1 if self.format == "addsub": add_sub = rule.generate_add_sub() # Add to list of keys if add_sub not in self.keys: self.keys.append(add_sub) # Check if key is to be generated if self.key: self.words[word].append(str(self.keys.index(add_sub))) else: # Generate addsub next to base word self.words[word].append(rule.generate_add_sub()) else: # Default, insert complete derivative word self.words[word].append(rule.create_derivative(word)) else: # No derivatives. self.words[word] = [] # Create regular expression from compounds for rule in self.aff.compound_rules: # Add to list self.regex_compounds.append(rule.get_regex())
python
def __parse_dict(self): ''' Parses dictionary with according rules ''' i = 0 lines = self.lines for line in lines: line = line.split('/') word = line[0] flags = line[1] if len(line) > 1 else None # Base Word self.num_words += 1 if flags != None: # Derivatives possible for flag in flags: # Compound? if flag in self.aff.compound_flags or flag == self.aff.only_in_compound_flag: for rule in self.aff.compound_rules: rule.add_flag_values(word, flag) else: # No Suggest flags if self.aff.no_suggest_flag == flag: pass else: affix_rule_entries = self.aff.affix_rules[flag] # Get flag that meets condition for i in range(len(affix_rule_entries)): rule = affix_rule_entries[i] if rule.meets_condition(word): # Add word to list if does not already exist if word not in self.words: self.words[word] = [] # Derivatives self.num_words += 1 if self.format == "addsub": add_sub = rule.generate_add_sub() # Add to list of keys if add_sub not in self.keys: self.keys.append(add_sub) # Check if key is to be generated if self.key: self.words[word].append(str(self.keys.index(add_sub))) else: # Generate addsub next to base word self.words[word].append(rule.generate_add_sub()) else: # Default, insert complete derivative word self.words[word].append(rule.create_derivative(word)) else: # No derivatives. self.words[word] = [] # Create regular expression from compounds for rule in self.aff.compound_rules: # Add to list self.regex_compounds.append(rule.get_regex())
[ "def", "__parse_dict", "(", "self", ")", ":", "i", "=", "0", "lines", "=", "self", ".", "lines", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "split", "(", "'/'", ")", "word", "=", "line", "[", "0", "]", "flags", "=", "line", "[...
Parses dictionary with according rules
[ "Parses", "dictionary", "with", "according", "rules" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L282-L343
train
totalgood/nlpia
src/nlpia/loaders.py
load_imdb_df
def load_imdb_df(dirpath=os.path.join(BIGDATA_PATH, 'aclImdb'), subdirectories=(('train', 'test'), ('pos', 'neg', 'unsup'))): """ Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], index=MultiIndex(['train_test', 'pos_neg_unsup', 'id']) TODO: Make this more robust/general by allowing the subdirectories to be None and find all the subdirs containing txt files >> imdb_df().head() url rating text index0 index1 index2 train pos 0 http://www.imdb.com/title/tt0453418 9 Bromwell High is a cartoon comedy. It ran at t... 1 http://www.imdb.com/title/tt0210075 7 If you like adult comedy cartoons, like South ... 2 http://www.imdb.com/title/tt0085688 9 Bromwell High is nothing short of brilliant. E... 3 http://www.imdb.com/title/tt0033022 10 "All the world's a stage and its people actors... 4 http://www.imdb.com/title/tt0043137 8 FUTZ is the only show preserved from the exper... """ dfs = {} for subdirs in tqdm(list(product(*subdirectories))): urlspath = os.path.join(dirpath, subdirs[0], 'urls_{}.txt'.format(subdirs[1])) if not os.path.isfile(urlspath): if subdirs != ('test', 'unsup'): # test/ dir doesn't usually have an unsup subdirectory logger.warning('Unable to find expected IMDB review list of URLs: {}'.format(urlspath)) continue df = pd.read_csv(urlspath, header=None, names=['url']) # df.index.name = 'id' df['url'] = series_strip(df.url, endswith='/usercomments') textsdir = os.path.join(dirpath, subdirs[0], subdirs[1]) if not os.path.isdir(textsdir): logger.warning('Unable to find expected IMDB review text subdirectory: {}'.format(textsdir)) continue filenames = [fn for fn in os.listdir(textsdir) if fn.lower().endswith('.txt')] df['index0'] = subdirs[0] # TODO: column names more generic so will work on other datasets df['index1'] = subdirs[1] df['index2'] = np.array([int(fn[:-4].split('_')[0]) for fn in filenames]) df['rating'] = np.array([int(fn[:-4].split('_')[1]) for fn in filenames]) texts = [] for fn in filenames: with ensure_open(os.path.join(textsdir, fn)) as f: texts.append(f.read()) df['text'] = np.array(texts) del texts df.set_index('index0 index1 index2'.split(), inplace=True) df.sort_index(inplace=True) dfs[subdirs] = df return pd.concat(dfs.values())
python
def load_imdb_df(dirpath=os.path.join(BIGDATA_PATH, 'aclImdb'), subdirectories=(('train', 'test'), ('pos', 'neg', 'unsup'))): """ Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], index=MultiIndex(['train_test', 'pos_neg_unsup', 'id']) TODO: Make this more robust/general by allowing the subdirectories to be None and find all the subdirs containing txt files >> imdb_df().head() url rating text index0 index1 index2 train pos 0 http://www.imdb.com/title/tt0453418 9 Bromwell High is a cartoon comedy. It ran at t... 1 http://www.imdb.com/title/tt0210075 7 If you like adult comedy cartoons, like South ... 2 http://www.imdb.com/title/tt0085688 9 Bromwell High is nothing short of brilliant. E... 3 http://www.imdb.com/title/tt0033022 10 "All the world's a stage and its people actors... 4 http://www.imdb.com/title/tt0043137 8 FUTZ is the only show preserved from the exper... """ dfs = {} for subdirs in tqdm(list(product(*subdirectories))): urlspath = os.path.join(dirpath, subdirs[0], 'urls_{}.txt'.format(subdirs[1])) if not os.path.isfile(urlspath): if subdirs != ('test', 'unsup'): # test/ dir doesn't usually have an unsup subdirectory logger.warning('Unable to find expected IMDB review list of URLs: {}'.format(urlspath)) continue df = pd.read_csv(urlspath, header=None, names=['url']) # df.index.name = 'id' df['url'] = series_strip(df.url, endswith='/usercomments') textsdir = os.path.join(dirpath, subdirs[0], subdirs[1]) if not os.path.isdir(textsdir): logger.warning('Unable to find expected IMDB review text subdirectory: {}'.format(textsdir)) continue filenames = [fn for fn in os.listdir(textsdir) if fn.lower().endswith('.txt')] df['index0'] = subdirs[0] # TODO: column names more generic so will work on other datasets df['index1'] = subdirs[1] df['index2'] = np.array([int(fn[:-4].split('_')[0]) for fn in filenames]) df['rating'] = np.array([int(fn[:-4].split('_')[1]) for fn in filenames]) texts = [] for fn in filenames: with ensure_open(os.path.join(textsdir, fn)) as f: texts.append(f.read()) df['text'] = np.array(texts) del texts df.set_index('index0 index1 index2'.split(), inplace=True) df.sort_index(inplace=True) dfs[subdirs] = df return pd.concat(dfs.values())
[ "def", "load_imdb_df", "(", "dirpath", "=", "os", ".", "path", ".", "join", "(", "BIGDATA_PATH", ",", "'aclImdb'", ")", ",", "subdirectories", "=", "(", "(", "'train'", ",", "'test'", ")", ",", "(", "'pos'", ",", "'neg'", ",", "'unsup'", ")", ")", ")...
Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], index=MultiIndex(['train_test', 'pos_neg_unsup', 'id']) TODO: Make this more robust/general by allowing the subdirectories to be None and find all the subdirs containing txt files >> imdb_df().head() url rating text index0 index1 index2 train pos 0 http://www.imdb.com/title/tt0453418 9 Bromwell High is a cartoon comedy. It ran at t... 1 http://www.imdb.com/title/tt0210075 7 If you like adult comedy cartoons, like South ... 2 http://www.imdb.com/title/tt0085688 9 Bromwell High is nothing short of brilliant. E... 3 http://www.imdb.com/title/tt0033022 10 "All the world's a stage and its people actors... 4 http://www.imdb.com/title/tt0043137 8 FUTZ is the only show preserved from the exper...
[ "Walk", "directory", "tree", "starting", "at", "path", "to", "compile", "a", "DataFrame", "of", "movie", "review", "text", "labeled", "with", "their", "1", "-", "10", "star", "ratings" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L108-L155
train
totalgood/nlpia
src/nlpia/loaders.py
load_glove
def load_glove(filepath, batch_size=1000, limit=None, verbose=True): r""" Load a pretrained GloVE word vector model First header line of GloVE text file should look like: 400000 50\n First vector of GloVE text file should look like: the .12 .22 .32 .42 ... .42 >>> wv = load_glove(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> wv.most_similar('and')[:3] [(',', 0.92...), ('.', 0.91...), ('of', 0.86...)] """ num_dim = isglove(filepath) tqdm_prog = tqdm if verbose else no_tqdm wv = KeyedVectors(num_dim) if limit: vocab_size = int(limit) else: with ensure_open(filepath) as fin: for i, line in enumerate(fin): pass vocab_size = i + 1 wv.vectors = np.zeros((vocab_size, num_dim), REAL) with ensure_open(filepath) as fin: batch, words = [], [] for i, line in enumerate(tqdm_prog(fin, total=vocab_size)): line = line.split() word = line[0] vector = np.array(line[1:]).astype(float) # words.append(word) # batch.append(vector) wv.index2word.append(word) wv.vocab[word] = Vocab(index=i, count=vocab_size - i) wv.vectors[i] = vector if len(words) >= batch_size: # wv[words] = np.array(batch) batch, words = [], [] if i >= vocab_size - 1: break if words: wv[words] = np.array(batch) return wv
python
def load_glove(filepath, batch_size=1000, limit=None, verbose=True): r""" Load a pretrained GloVE word vector model First header line of GloVE text file should look like: 400000 50\n First vector of GloVE text file should look like: the .12 .22 .32 .42 ... .42 >>> wv = load_glove(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> wv.most_similar('and')[:3] [(',', 0.92...), ('.', 0.91...), ('of', 0.86...)] """ num_dim = isglove(filepath) tqdm_prog = tqdm if verbose else no_tqdm wv = KeyedVectors(num_dim) if limit: vocab_size = int(limit) else: with ensure_open(filepath) as fin: for i, line in enumerate(fin): pass vocab_size = i + 1 wv.vectors = np.zeros((vocab_size, num_dim), REAL) with ensure_open(filepath) as fin: batch, words = [], [] for i, line in enumerate(tqdm_prog(fin, total=vocab_size)): line = line.split() word = line[0] vector = np.array(line[1:]).astype(float) # words.append(word) # batch.append(vector) wv.index2word.append(word) wv.vocab[word] = Vocab(index=i, count=vocab_size - i) wv.vectors[i] = vector if len(words) >= batch_size: # wv[words] = np.array(batch) batch, words = [], [] if i >= vocab_size - 1: break if words: wv[words] = np.array(batch) return wv
[ "def", "load_glove", "(", "filepath", ",", "batch_size", "=", "1000", ",", "limit", "=", "None", ",", "verbose", "=", "True", ")", ":", "r", "num_dim", "=", "isglove", "(", "filepath", ")", "tqdm_prog", "=", "tqdm", "if", "verbose", "else", "no_tqdm", ...
r""" Load a pretrained GloVE word vector model First header line of GloVE text file should look like: 400000 50\n First vector of GloVE text file should look like: the .12 .22 .32 .42 ... .42 >>> wv = load_glove(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> wv.most_similar('and')[:3] [(',', 0.92...), ('.', 0.91...), ('of', 0.86...)]
[ "r", "Load", "a", "pretrained", "GloVE", "word", "vector", "model" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L158-L204
train
totalgood/nlpia
src/nlpia/loaders.py
load_glove_df
def load_glove_df(filepath, **kwargs): """ Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 Name: the, dtype: float64 """ pdkwargs = dict(index_col=0, header=None, sep=r'\s', skiprows=[0], verbose=False, engine='python') pdkwargs.update(kwargs) return pd.read_csv(filepath, **pdkwargs)
python
def load_glove_df(filepath, **kwargs): """ Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 Name: the, dtype: float64 """ pdkwargs = dict(index_col=0, header=None, sep=r'\s', skiprows=[0], verbose=False, engine='python') pdkwargs.update(kwargs) return pd.read_csv(filepath, **pdkwargs)
[ "def", "load_glove_df", "(", "filepath", ",", "**", "kwargs", ")", ":", "pdkwargs", "=", "dict", "(", "index_col", "=", "0", ",", "header", "=", "None", ",", "sep", "=", "r'\\s'", ",", "skiprows", "=", "[", "0", "]", ",", "verbose", "=", "False", "...
Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 Name: the, dtype: float64
[ "Load", "a", "GloVE", "-", "format", "text", "file", "into", "a", "dataframe" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L207-L221
train
totalgood/nlpia
src/nlpia/loaders.py
get_en2fr
def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'): """ Download and parse English->French translation dataset used in Keras seq2seq example """ download_unzip(url) return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\t', skiprows=0, names='en fr'.split())
python
def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'): """ Download and parse English->French translation dataset used in Keras seq2seq example """ download_unzip(url) return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\t', skiprows=0, names='en fr'.split())
[ "def", "get_en2fr", "(", "url", "=", "'http://www.manythings.org/anki/fra-eng.zip'", ")", ":", "download_unzip", "(", "url", ")", "return", "pd", ".", "read_table", "(", "url", ",", "compression", "=", "'zip'", ",", "header", "=", "None", ",", "skip_blank_lines"...
Download and parse English->French translation dataset used in Keras seq2seq example
[ "Download", "and", "parse", "English", "-", ">", "French", "translation", "dataset", "used", "in", "Keras", "seq2seq", "example" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L233-L236
train
totalgood/nlpia
src/nlpia/loaders.py
load_anki_df
def load_anki_df(language='deu'): """ Load into a DataFrame statements in one language along with their translation into English >>> get_data('zsm').head(1) eng zsm 0 Are you new? Awak baru? """ if os.path.isfile(language): filepath = language lang = re.search('[a-z]{3}-eng/', filepath).group()[:3].lower() else: lang = (language or 'deu').lower()[:3] filepath = os.path.join(BIGDATA_PATH, '{}-eng'.format(lang), '{}.txt'.format(lang)) df = pd.read_table(filepath, skiprows=1, header=None) df.columns = ['eng', lang] return df
python
def load_anki_df(language='deu'): """ Load into a DataFrame statements in one language along with their translation into English >>> get_data('zsm').head(1) eng zsm 0 Are you new? Awak baru? """ if os.path.isfile(language): filepath = language lang = re.search('[a-z]{3}-eng/', filepath).group()[:3].lower() else: lang = (language or 'deu').lower()[:3] filepath = os.path.join(BIGDATA_PATH, '{}-eng'.format(lang), '{}.txt'.format(lang)) df = pd.read_table(filepath, skiprows=1, header=None) df.columns = ['eng', lang] return df
[ "def", "load_anki_df", "(", "language", "=", "'deu'", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "language", ")", ":", "filepath", "=", "language", "lang", "=", "re", ".", "search", "(", "'[a-z]{3}-eng/'", ",", "filepath", ")", ".", "group"...
Load into a DataFrame statements in one language along with their translation into English >>> get_data('zsm').head(1) eng zsm 0 Are you new? Awak baru?
[ "Load", "into", "a", "DataFrame", "statements", "in", "one", "language", "along", "with", "their", "translation", "into", "English" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L239-L254
train
totalgood/nlpia
src/nlpia/loaders.py
generate_big_urls_glove
def generate_big_urls_glove(bigurls=None): """ Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality """ bigurls = bigurls or {} for num_dim in (50, 100, 200, 300): # not all of these dimensionality, and training set size combinations were trained by Stanford for suffixes, num_words in zip( ('sm -sm _sm -small _small'.split(), 'med -med _med -medium _medium'.split(), 'lg -lg _lg -large _large'.split()), (6, 42, 840) ): for suf in suffixes[:-1]: name = 'glove' + suf + str(num_dim) dirname = 'glove.{num_words}B'.format(num_words=num_words) # glove.42B.300d.w2v.txt filename = dirname + '.{num_dim}d.w2v.txt'.format(num_dim=num_dim) # seed the alias named URL with the URL for that training set size's canonical name bigurl_tuple = BIG_URLS['glove' + suffixes[-1]] bigurls[name] = list(bigurl_tuple[:2]) bigurls[name].append(os.path.join(dirname, filename)) bigurls[name].append(load_glove) bigurls[name] = tuple(bigurls[name]) return bigurls
python
def generate_big_urls_glove(bigurls=None): """ Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality """ bigurls = bigurls or {} for num_dim in (50, 100, 200, 300): # not all of these dimensionality, and training set size combinations were trained by Stanford for suffixes, num_words in zip( ('sm -sm _sm -small _small'.split(), 'med -med _med -medium _medium'.split(), 'lg -lg _lg -large _large'.split()), (6, 42, 840) ): for suf in suffixes[:-1]: name = 'glove' + suf + str(num_dim) dirname = 'glove.{num_words}B'.format(num_words=num_words) # glove.42B.300d.w2v.txt filename = dirname + '.{num_dim}d.w2v.txt'.format(num_dim=num_dim) # seed the alias named URL with the URL for that training set size's canonical name bigurl_tuple = BIG_URLS['glove' + suffixes[-1]] bigurls[name] = list(bigurl_tuple[:2]) bigurls[name].append(os.path.join(dirname, filename)) bigurls[name].append(load_glove) bigurls[name] = tuple(bigurls[name]) return bigurls
[ "def", "generate_big_urls_glove", "(", "bigurls", "=", "None", ")", ":", "bigurls", "=", "bigurls", "or", "{", "}", "for", "num_dim", "in", "(", "50", ",", "100", ",", "200", ",", "300", ")", ":", "for", "suffixes", ",", "num_words", "in", "zip", "("...
Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality
[ "Generate", "a", "dictionary", "of", "URLs", "for", "various", "combinations", "of", "GloVe", "training", "set", "sizes", "and", "dimensionality" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L381-L403
train
totalgood/nlpia
src/nlpia/loaders.py
normalize_ext_rename
def normalize_ext_rename(filepath): """ normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file >>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt') >>> pth == normalize_ext_rename(pth) True """ logger.debug('normalize_ext.filepath=' + str(filepath)) new_file_path = normalize_ext(filepath) logger.debug('download_unzip.new_filepaths=' + str(new_file_path)) # FIXME: fails when name is a url filename filepath = rename_file(filepath, new_file_path) logger.debug('download_unzip.filepath=' + str(filepath)) return filepath
python
def normalize_ext_rename(filepath): """ normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file >>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt') >>> pth == normalize_ext_rename(pth) True """ logger.debug('normalize_ext.filepath=' + str(filepath)) new_file_path = normalize_ext(filepath) logger.debug('download_unzip.new_filepaths=' + str(new_file_path)) # FIXME: fails when name is a url filename filepath = rename_file(filepath, new_file_path) logger.debug('download_unzip.filepath=' + str(filepath)) return filepath
[ "def", "normalize_ext_rename", "(", "filepath", ")", ":", "logger", ".", "debug", "(", "'normalize_ext.filepath='", "+", "str", "(", "filepath", ")", ")", "new_file_path", "=", "normalize_ext", "(", "filepath", ")", "logger", ".", "debug", "(", "'download_unzip....
normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file >>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt') >>> pth == normalize_ext_rename(pth) True
[ "normalize", "file", "ext", "like", ".", "tgz", "-", ">", ".", "tar", ".", "gz", "and", "300d", ".", "txt", "-", ">", "300d", ".", "glove", ".", "txt", "and", "rename", "the", "file" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L506-L519
train
totalgood/nlpia
src/nlpia/loaders.py
untar
def untar(fname, verbose=True): """ Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory """ if fname.lower().endswith(".tar.gz"): dirpath = os.path.join(BIGDATA_PATH, os.path.basename(fname)[:-7]) if os.path.isdir(dirpath): return dirpath with tarfile.open(fname) as tf: members = tf.getmembers() for member in tqdm(members, total=len(members)): tf.extract(member, path=BIGDATA_PATH) dirpath = os.path.join(BIGDATA_PATH, members[0].name) if os.path.isdir(dirpath): return dirpath else: logger.warning("Not a tar.gz file: {}".format(fname))
python
def untar(fname, verbose=True): """ Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory """ if fname.lower().endswith(".tar.gz"): dirpath = os.path.join(BIGDATA_PATH, os.path.basename(fname)[:-7]) if os.path.isdir(dirpath): return dirpath with tarfile.open(fname) as tf: members = tf.getmembers() for member in tqdm(members, total=len(members)): tf.extract(member, path=BIGDATA_PATH) dirpath = os.path.join(BIGDATA_PATH, members[0].name) if os.path.isdir(dirpath): return dirpath else: logger.warning("Not a tar.gz file: {}".format(fname))
[ "def", "untar", "(", "fname", ",", "verbose", "=", "True", ")", ":", "if", "fname", ".", "lower", "(", ")", ".", "endswith", "(", "\".tar.gz\"", ")", ":", "dirpath", "=", "os", ".", "path", ".", "join", "(", "BIGDATA_PATH", ",", "os", ".", "path", ...
Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory
[ "Uunzip", "and", "untar", "a", "tar", ".", "gz", "file", "into", "a", "subdir", "of", "the", "BIGDATA_PATH", "directory" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L522-L536
train
totalgood/nlpia
src/nlpia/loaders.py
endswith_strip
def endswith_strip(s, endswith='.txt', ignorecase=True): """ Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com' """ if ignorecase: if s.lower().endswith(endswith.lower()): return s[:-len(endswith)] else: if s.endswith(endswith): return s[:-len(endswith)] return s
python
def endswith_strip(s, endswith='.txt', ignorecase=True): """ Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com' """ if ignorecase: if s.lower().endswith(endswith.lower()): return s[:-len(endswith)] else: if s.endswith(endswith): return s[:-len(endswith)] return s
[ "def", "endswith_strip", "(", "s", ",", "endswith", "=", "'.txt'", ",", "ignorecase", "=", "True", ")", ":", "if", "ignorecase", ":", "if", "s", ".", "lower", "(", ")", ".", "endswith", "(", "endswith", ".", "lower", "(", ")", ")", ":", "return", "...
Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com'
[ "Strip", "a", "suffix", "from", "the", "end", "of", "a", "string" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L570-L584
train
totalgood/nlpia
src/nlpia/loaders.py
startswith_strip
def startswith_strip(s, startswith='http://', ignorecase=True): """ Strip a prefix from the beginning of a string >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://') 'TotalGood.com' >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False) 'HTtp://TotalGood.com' """ if ignorecase: if s.lower().startswith(startswith.lower()): return s[len(startswith):] else: if s.endswith(startswith): return s[len(startswith):] return s
python
def startswith_strip(s, startswith='http://', ignorecase=True): """ Strip a prefix from the beginning of a string >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://') 'TotalGood.com' >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False) 'HTtp://TotalGood.com' """ if ignorecase: if s.lower().startswith(startswith.lower()): return s[len(startswith):] else: if s.endswith(startswith): return s[len(startswith):] return s
[ "def", "startswith_strip", "(", "s", ",", "startswith", "=", "'http://'", ",", "ignorecase", "=", "True", ")", ":", "if", "ignorecase", ":", "if", "s", ".", "lower", "(", ")", ".", "startswith", "(", "startswith", ".", "lower", "(", ")", ")", ":", "r...
Strip a prefix from the beginning of a string >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://') 'TotalGood.com' >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False) 'HTtp://TotalGood.com'
[ "Strip", "a", "prefix", "from", "the", "beginning", "of", "a", "string" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L587-L601
train
totalgood/nlpia
src/nlpia/loaders.py
get_longest_table
def get_longest_table(url='https://www.openoffice.org/dev_docs/source/file_extensions.html', header=0): """ Retrieve the HTML tables from a URL and return the longest DataFrame found >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns Index(['Common and formal names', 'Membership within the UN System[a]', 'Sovereignty dispute[b]', 'Further information on status and recognition of sovereignty[d]'], dtype='object') """ dfs = pd.read_html(url, header=header) return longest_table(dfs)
python
def get_longest_table(url='https://www.openoffice.org/dev_docs/source/file_extensions.html', header=0): """ Retrieve the HTML tables from a URL and return the longest DataFrame found >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns Index(['Common and formal names', 'Membership within the UN System[a]', 'Sovereignty dispute[b]', 'Further information on status and recognition of sovereignty[d]'], dtype='object') """ dfs = pd.read_html(url, header=header) return longest_table(dfs)
[ "def", "get_longest_table", "(", "url", "=", "'https://www.openoffice.org/dev_docs/source/file_extensions.html'", ",", "header", "=", "0", ")", ":", "dfs", "=", "pd", ".", "read_html", "(", "url", ",", "header", "=", "header", ")", "return", "longest_table", "(", ...
Retrieve the HTML tables from a URL and return the longest DataFrame found >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns Index(['Common and formal names', 'Membership within the UN System[a]', 'Sovereignty dispute[b]', 'Further information on status and recognition of sovereignty[d]'], dtype='object')
[ "Retrieve", "the", "HTML", "tables", "from", "a", "URL", "and", "return", "the", "longest", "DataFrame", "found" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L609-L619
train
totalgood/nlpia
src/nlpia/loaders.py
get_filename_extensions
def get_filename_extensions(url='https://www.webopedia.com/quick_ref/fileextensionsfull.asp'): """ Load a DataFrame of filename extensions from the indicated url >>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html') >>> df.head(2) ext description 0 .a UNIX static library file. 1 .asm Non-UNIX assembler source file. """ df = get_longest_table(url) columns = list(df.columns) columns[0] = 'ext' columns[1] = 'description' if len(columns) > 2: columns[2] = 'details' df.columns = columns return df
python
def get_filename_extensions(url='https://www.webopedia.com/quick_ref/fileextensionsfull.asp'): """ Load a DataFrame of filename extensions from the indicated url >>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html') >>> df.head(2) ext description 0 .a UNIX static library file. 1 .asm Non-UNIX assembler source file. """ df = get_longest_table(url) columns = list(df.columns) columns[0] = 'ext' columns[1] = 'description' if len(columns) > 2: columns[2] = 'details' df.columns = columns return df
[ "def", "get_filename_extensions", "(", "url", "=", "'https://www.webopedia.com/quick_ref/fileextensionsfull.asp'", ")", ":", "df", "=", "get_longest_table", "(", "url", ")", "columns", "=", "list", "(", "df", ".", "columns", ")", "columns", "[", "0", "]", "=", "...
Load a DataFrame of filename extensions from the indicated url >>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html') >>> df.head(2) ext description 0 .a UNIX static library file. 1 .asm Non-UNIX assembler source file.
[ "Load", "a", "DataFrame", "of", "filename", "extensions", "from", "the", "indicated", "url" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L663-L679
train
totalgood/nlpia
src/nlpia/loaders.py
create_big_url
def create_big_url(name): """ If name looks like a url, with an http, add an entry for it in BIG_URLS """ # BIG side effect global BIG_URLS filemeta = get_url_filemeta(name) if not filemeta: return None filename = filemeta['filename'] remote_size = filemeta['remote_size'] url = filemeta['url'] name = filename.split('.') name = (name[0] if name[0] not in ('', '.') else name[1]).replace(' ', '-') name = name.lower().strip() BIG_URLS[name] = (url, int(remote_size or -1), filename) return name
python
def create_big_url(name): """ If name looks like a url, with an http, add an entry for it in BIG_URLS """ # BIG side effect global BIG_URLS filemeta = get_url_filemeta(name) if not filemeta: return None filename = filemeta['filename'] remote_size = filemeta['remote_size'] url = filemeta['url'] name = filename.split('.') name = (name[0] if name[0] not in ('', '.') else name[1]).replace(' ', '-') name = name.lower().strip() BIG_URLS[name] = (url, int(remote_size or -1), filename) return name
[ "def", "create_big_url", "(", "name", ")", ":", "global", "BIG_URLS", "filemeta", "=", "get_url_filemeta", "(", "name", ")", "if", "not", "filemeta", ":", "return", "None", "filename", "=", "filemeta", "[", "'filename'", "]", "remote_size", "=", "filemeta", ...
If name looks like a url, with an http, add an entry for it in BIG_URLS
[ "If", "name", "looks", "like", "a", "url", "with", "an", "http", "add", "an", "entry", "for", "it", "in", "BIG_URLS" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L787-L801
train
totalgood/nlpia
src/nlpia/loaders.py
get_data
def get_data(name='sms-spam', nrows=None, limit=None): """ Load data from a json, csv, or txt file if it exists in the data dir. References: [cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp) [cities](http://download.geonames.org/export/dump/cities.zip) [cities_us](http://download.geonames.org/export/dump/cities_us.zip) >>> from nlpia.data.loaders import get_data >>> words = get_data('words_ubuntu_us') >>> len(words) 99171 >>> list(words[:8]) ['A', "A's", "AA's", "AB's", "ABM's", "AC's", "ACTH's", "AI's"] >>> get_data('ubuntu_dialog_test').iloc[0] Context i think we could import the old comments via r... Utterance basically each xfree86 upload will NOT force u... Name: 0, dtype: object >>> get_data('imdb_test').info() <class 'pandas.core.frame.DataFrame'> MultiIndex: 20 entries, (train, pos, 0) to (train, neg, 9) Data columns (total 3 columns): url 20 non-null object rating 20 non-null int64 text 20 non-null object dtypes: int64(1), object(2) memory usage: 809.0+ bytes """ nrows = nrows or limit if name in BIG_URLS: logger.info('Downloading {}'.format(name)) filepaths = download_unzip(name, normalize_filenames=True) logger.debug('nlpia.loaders.get_data.filepaths=' + str(filepaths)) filepath = filepaths[name][0] if isinstance(filepaths[name], (list, tuple)) else filepaths[name] logger.debug('nlpia.loaders.get_data.filepath=' + str(filepath)) filepathlow = filepath.lower() if len(BIG_URLS[name]) >= 4: kwargs = BIG_URLS[name][4] if len(BIG_URLS[name]) >= 5 else {} return BIG_URLS[name][3](filepath, **kwargs) if filepathlow.endswith('.w2v.txt'): try: return KeyedVectors.load_word2vec_format(filepath, binary=False, limit=nrows) except (TypeError, UnicodeError): pass if filepathlow.endswith('.w2v.bin') or filepathlow.endswith('.bin.gz') or filepathlow.endswith('.w2v.bin.gz'): try: return KeyedVectors.load_word2vec_format(filepath, binary=True, limit=nrows) except (TypeError, UnicodeError): pass if filepathlow.endswith('.gz'): try: filepath = ensure_open(filepath) except: # noqa pass if re.match(r'.json([.][a-z]{0,3}){0,2}', filepathlow): return read_json(filepath) if filepathlow.endswith('.tsv.gz') or filepathlow.endswith('.tsv'): try: return pd.read_table(filepath) except: # noqa pass if filepathlow.endswith('.csv.gz') or filepathlow.endswith('.csv'): try: return read_csv(filepath) except: # noqa pass if filepathlow.endswith('.txt'): try: return read_txt(filepath) except (TypeError, UnicodeError): pass return filepaths[name] elif name in DATASET_NAME2FILENAME: return read_named_csv(name, nrows=nrows) elif name in DATA_NAMES: return read_named_csv(DATA_NAMES[name], nrows=nrows) elif os.path.isfile(name): return read_named_csv(name, nrows=nrows) elif os.path.isfile(os.path.join(DATA_PATH, name)): return read_named_csv(os.path.join(DATA_PATH, name), nrows=nrows) msg = 'Unable to find dataset "{}"" in {} or {} (*.csv.gz, *.csv, *.json, *.zip, or *.txt)\n'.format( name, DATA_PATH, BIGDATA_PATH) msg += 'Available dataset names include:\n{}'.format('\n'.join(DATASET_NAMES)) logger.error(msg) raise IOError(msg)
python
def get_data(name='sms-spam', nrows=None, limit=None): """ Load data from a json, csv, or txt file if it exists in the data dir. References: [cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp) [cities](http://download.geonames.org/export/dump/cities.zip) [cities_us](http://download.geonames.org/export/dump/cities_us.zip) >>> from nlpia.data.loaders import get_data >>> words = get_data('words_ubuntu_us') >>> len(words) 99171 >>> list(words[:8]) ['A', "A's", "AA's", "AB's", "ABM's", "AC's", "ACTH's", "AI's"] >>> get_data('ubuntu_dialog_test').iloc[0] Context i think we could import the old comments via r... Utterance basically each xfree86 upload will NOT force u... Name: 0, dtype: object >>> get_data('imdb_test').info() <class 'pandas.core.frame.DataFrame'> MultiIndex: 20 entries, (train, pos, 0) to (train, neg, 9) Data columns (total 3 columns): url 20 non-null object rating 20 non-null int64 text 20 non-null object dtypes: int64(1), object(2) memory usage: 809.0+ bytes """ nrows = nrows or limit if name in BIG_URLS: logger.info('Downloading {}'.format(name)) filepaths = download_unzip(name, normalize_filenames=True) logger.debug('nlpia.loaders.get_data.filepaths=' + str(filepaths)) filepath = filepaths[name][0] if isinstance(filepaths[name], (list, tuple)) else filepaths[name] logger.debug('nlpia.loaders.get_data.filepath=' + str(filepath)) filepathlow = filepath.lower() if len(BIG_URLS[name]) >= 4: kwargs = BIG_URLS[name][4] if len(BIG_URLS[name]) >= 5 else {} return BIG_URLS[name][3](filepath, **kwargs) if filepathlow.endswith('.w2v.txt'): try: return KeyedVectors.load_word2vec_format(filepath, binary=False, limit=nrows) except (TypeError, UnicodeError): pass if filepathlow.endswith('.w2v.bin') or filepathlow.endswith('.bin.gz') or filepathlow.endswith('.w2v.bin.gz'): try: return KeyedVectors.load_word2vec_format(filepath, binary=True, limit=nrows) except (TypeError, UnicodeError): pass if filepathlow.endswith('.gz'): try: filepath = ensure_open(filepath) except: # noqa pass if re.match(r'.json([.][a-z]{0,3}){0,2}', filepathlow): return read_json(filepath) if filepathlow.endswith('.tsv.gz') or filepathlow.endswith('.tsv'): try: return pd.read_table(filepath) except: # noqa pass if filepathlow.endswith('.csv.gz') or filepathlow.endswith('.csv'): try: return read_csv(filepath) except: # noqa pass if filepathlow.endswith('.txt'): try: return read_txt(filepath) except (TypeError, UnicodeError): pass return filepaths[name] elif name in DATASET_NAME2FILENAME: return read_named_csv(name, nrows=nrows) elif name in DATA_NAMES: return read_named_csv(DATA_NAMES[name], nrows=nrows) elif os.path.isfile(name): return read_named_csv(name, nrows=nrows) elif os.path.isfile(os.path.join(DATA_PATH, name)): return read_named_csv(os.path.join(DATA_PATH, name), nrows=nrows) msg = 'Unable to find dataset "{}"" in {} or {} (*.csv.gz, *.csv, *.json, *.zip, or *.txt)\n'.format( name, DATA_PATH, BIGDATA_PATH) msg += 'Available dataset names include:\n{}'.format('\n'.join(DATASET_NAMES)) logger.error(msg) raise IOError(msg)
[ "def", "get_data", "(", "name", "=", "'sms-spam'", ",", "nrows", "=", "None", ",", "limit", "=", "None", ")", ":", "nrows", "=", "nrows", "or", "limit", "if", "name", "in", "BIG_URLS", ":", "logger", ".", "info", "(", "'Downloading {}'", ".", "format",...
Load data from a json, csv, or txt file if it exists in the data dir. References: [cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp) [cities](http://download.geonames.org/export/dump/cities.zip) [cities_us](http://download.geonames.org/export/dump/cities_us.zip) >>> from nlpia.data.loaders import get_data >>> words = get_data('words_ubuntu_us') >>> len(words) 99171 >>> list(words[:8]) ['A', "A's", "AA's", "AB's", "ABM's", "AC's", "ACTH's", "AI's"] >>> get_data('ubuntu_dialog_test').iloc[0] Context i think we could import the old comments via r... Utterance basically each xfree86 upload will NOT force u... Name: 0, dtype: object >>> get_data('imdb_test').info() <class 'pandas.core.frame.DataFrame'> MultiIndex: 20 entries, (train, pos, 0) to (train, neg, 9) Data columns (total 3 columns): url 20 non-null object rating 20 non-null int64 text 20 non-null object dtypes: int64(1), object(2) memory usage: 809.0+ bytes
[ "Load", "data", "from", "a", "json", "csv", "or", "txt", "file", "if", "it", "exists", "in", "the", "data", "dir", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1027-L1113
train
totalgood/nlpia
src/nlpia/loaders.py
get_wikidata_qnum
def get_wikidata_qnum(wikiarticle, wikisite): """Retrieve the Query number for a wikidata database of metadata about a particular article >>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki")) Q2469 """ resp = requests.get('https://www.wikidata.org/w/api.php', timeout=5, params={ 'action': 'wbgetentities', 'titles': wikiarticle, 'sites': wikisite, 'props': '', 'format': 'json' }).json() return list(resp['entities'])[0]
python
def get_wikidata_qnum(wikiarticle, wikisite): """Retrieve the Query number for a wikidata database of metadata about a particular article >>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki")) Q2469 """ resp = requests.get('https://www.wikidata.org/w/api.php', timeout=5, params={ 'action': 'wbgetentities', 'titles': wikiarticle, 'sites': wikisite, 'props': '', 'format': 'json' }).json() return list(resp['entities'])[0]
[ "def", "get_wikidata_qnum", "(", "wikiarticle", ",", "wikisite", ")", ":", "resp", "=", "requests", ".", "get", "(", "'https://www.wikidata.org/w/api.php'", ",", "timeout", "=", "5", ",", "params", "=", "{", "'action'", ":", "'wbgetentities'", ",", "'titles'", ...
Retrieve the Query number for a wikidata database of metadata about a particular article >>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki")) Q2469
[ "Retrieve", "the", "Query", "number", "for", "a", "wikidata", "database", "of", "metadata", "about", "a", "particular", "article" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1126-L1139
train