repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
discolabs/django-shopify-auth
shopify_auth/apps.py
initialise_shopify_session
def initialise_shopify_session(): """ Initialise the Shopify session with the Shopify App's API credentials. """ if not settings.SHOPIFY_APP_API_KEY or not settings.SHOPIFY_APP_API_SECRET: raise ImproperlyConfigured("SHOPIFY_APP_API_KEY and SHOPIFY_APP_API_SECRET must be set in settings") sh...
python
def initialise_shopify_session(): """ Initialise the Shopify session with the Shopify App's API credentials. """ if not settings.SHOPIFY_APP_API_KEY or not settings.SHOPIFY_APP_API_SECRET: raise ImproperlyConfigured("SHOPIFY_APP_API_KEY and SHOPIFY_APP_API_SECRET must be set in settings") sh...
[ "def", "initialise_shopify_session", "(", ")", ":", "if", "not", "settings", ".", "SHOPIFY_APP_API_KEY", "or", "not", "settings", ".", "SHOPIFY_APP_API_SECRET", ":", "raise", "ImproperlyConfigured", "(", "\"SHOPIFY_APP_API_KEY and SHOPIFY_APP_API_SECRET must be set in settings\...
Initialise the Shopify session with the Shopify App's API credentials.
[ "Initialise", "the", "Shopify", "session", "with", "the", "Shopify", "App", "s", "API", "credentials", "." ]
76523867bc630c7ade963d787afea1a94017874a
https://github.com/discolabs/django-shopify-auth/blob/76523867bc630c7ade963d787afea1a94017874a/shopify_auth/apps.py#L23-L29
train
discolabs/django-shopify-auth
shopify_auth/decorators.py
anonymous_required
def anonymous_required(function=None, redirect_url=None): """ Decorator requiring the current user to be anonymous (not logged in). """ if not redirect_url: redirect_url = settings.LOGIN_REDIRECT_URL actual_decorator = user_passes_test( is_anonymous, login_url=redirect_url, ...
python
def anonymous_required(function=None, redirect_url=None): """ Decorator requiring the current user to be anonymous (not logged in). """ if not redirect_url: redirect_url = settings.LOGIN_REDIRECT_URL actual_decorator = user_passes_test( is_anonymous, login_url=redirect_url, ...
[ "def", "anonymous_required", "(", "function", "=", "None", ",", "redirect_url", "=", "None", ")", ":", "if", "not", "redirect_url", ":", "redirect_url", "=", "settings", ".", "LOGIN_REDIRECT_URL", "actual_decorator", "=", "user_passes_test", "(", "is_anonymous", "...
Decorator requiring the current user to be anonymous (not logged in).
[ "Decorator", "requiring", "the", "current", "user", "to", "be", "anonymous", "(", "not", "logged", "in", ")", "." ]
76523867bc630c7ade963d787afea1a94017874a
https://github.com/discolabs/django-shopify-auth/blob/76523867bc630c7ade963d787afea1a94017874a/shopify_auth/decorators.py#L26-L41
train
discolabs/django-shopify-auth
shopify_auth/decorators.py
login_required
def login_required(f, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator that wraps django.contrib.auth.decorators.login_required, but supports extracting Shopify's authentication query parameters (`shop`, `timestamp`, `signature` and `hmac`) and passing them on to the login URL (instea...
python
def login_required(f, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator that wraps django.contrib.auth.decorators.login_required, but supports extracting Shopify's authentication query parameters (`shop`, `timestamp`, `signature` and `hmac`) and passing them on to the login URL (instea...
[ "def", "login_required", "(", "f", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "login_url", "=", "None", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if"...
Decorator that wraps django.contrib.auth.decorators.login_required, but supports extracting Shopify's authentication query parameters (`shop`, `timestamp`, `signature` and `hmac`) and passing them on to the login URL (instead of just wrapping them up and encoding them in to the `next` parameter). This is u...
[ "Decorator", "that", "wraps", "django", ".", "contrib", ".", "auth", ".", "decorators", ".", "login_required", "but", "supports", "extracting", "Shopify", "s", "authentication", "query", "parameters", "(", "shop", "timestamp", "signature", "and", "hmac", ")", "a...
76523867bc630c7ade963d787afea1a94017874a
https://github.com/discolabs/django-shopify-auth/blob/76523867bc630c7ade963d787afea1a94017874a/shopify_auth/decorators.py#L44-L76
train
discolabs/django-shopify-auth
shopify_auth/models.py
ShopUserManager.create_user
def create_user(self, myshopify_domain, password=None): """ Creates and saves a ShopUser with the given domain and password. """ if not myshopify_domain: raise ValueError('ShopUsers must have a myshopify domain') user = self.model(myshopify_domain=myshopify_domain) ...
python
def create_user(self, myshopify_domain, password=None): """ Creates and saves a ShopUser with the given domain and password. """ if not myshopify_domain: raise ValueError('ShopUsers must have a myshopify domain') user = self.model(myshopify_domain=myshopify_domain) ...
[ "def", "create_user", "(", "self", ",", "myshopify_domain", ",", "password", "=", "None", ")", ":", "if", "not", "myshopify_domain", ":", "raise", "ValueError", "(", "'ShopUsers must have a myshopify domain'", ")", "user", "=", "self", ".", "model", "(", "myshop...
Creates and saves a ShopUser with the given domain and password.
[ "Creates", "and", "saves", "a", "ShopUser", "with", "the", "given", "domain", "and", "password", "." ]
76523867bc630c7ade963d787afea1a94017874a
https://github.com/discolabs/django-shopify-auth/blob/76523867bc630c7ade963d787afea1a94017874a/shopify_auth/models.py#L10-L23
train
discolabs/django-shopify-auth
shopify_auth/helpers.py
add_query_parameters_to_url
def add_query_parameters_to_url(url, query_parameters): """ Merge a dictionary of query parameters into the given URL. Ensures all parameters are sorted in dictionary order when returning the URL. """ # Parse the given URL into parts. url_parts = urllib.parse.urlparse(url) # Parse existing ...
python
def add_query_parameters_to_url(url, query_parameters): """ Merge a dictionary of query parameters into the given URL. Ensures all parameters are sorted in dictionary order when returning the URL. """ # Parse the given URL into parts. url_parts = urllib.parse.urlparse(url) # Parse existing ...
[ "def", "add_query_parameters_to_url", "(", "url", ",", "query_parameters", ")", ":", "# Parse the given URL into parts.", "url_parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "# Parse existing parameters and add new parameters.", "qs_args", "=", "ur...
Merge a dictionary of query parameters into the given URL. Ensures all parameters are sorted in dictionary order when returning the URL.
[ "Merge", "a", "dictionary", "of", "query", "parameters", "into", "the", "given", "URL", ".", "Ensures", "all", "parameters", "are", "sorted", "in", "dictionary", "order", "when", "returning", "the", "URL", "." ]
76523867bc630c7ade963d787afea1a94017874a
https://github.com/discolabs/django-shopify-auth/blob/76523867bc630c7ade963d787afea1a94017874a/shopify_auth/helpers.py#L5-L24
train
nlsdfnbch/Pysher
pysher/connection.py
Connection.bind
def bind(self, event_name, callback, *args, **kwargs): """Bind an event to a callback :param event_name: The name of the event to bind to. :type event_name: str :param callback: The callback to notify of this event. """ self.event_callbacks[event_name].append((callback,...
python
def bind(self, event_name, callback, *args, **kwargs): """Bind an event to a callback :param event_name: The name of the event to bind to. :type event_name: str :param callback: The callback to notify of this event. """ self.event_callbacks[event_name].append((callback,...
[ "def", "bind", "(", "self", ",", "event_name", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "event_callbacks", "[", "event_name", "]", ".", "append", "(", "(", "callback", ",", "args", ",", "kwargs", ")", ")" ]
Bind an event to a callback :param event_name: The name of the event to bind to. :type event_name: str :param callback: The callback to notify of this event.
[ "Bind", "an", "event", "to", "a", "callback" ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/connection.py#L73-L81
train
nlsdfnbch/Pysher
pysher/connection.py
Connection.send_event
def send_event(self, event_name, data, channel_name=None): """Send an event to the Pusher server. :param str event_name: :param Any data: :param str channel_name: """ event = {'event': event_name, 'data': data} if channel_name: event['channel'] = chan...
python
def send_event(self, event_name, data, channel_name=None): """Send an event to the Pusher server. :param str event_name: :param Any data: :param str channel_name: """ event = {'event': event_name, 'data': data} if channel_name: event['channel'] = chan...
[ "def", "send_event", "(", "self", ",", "event_name", ",", "data", ",", "channel_name", "=", "None", ")", ":", "event", "=", "{", "'event'", ":", "event_name", ",", "'data'", ":", "data", "}", "if", "channel_name", ":", "event", "[", "'channel'", "]", "...
Send an event to the Pusher server. :param str event_name: :param Any data: :param str channel_name:
[ "Send", "an", "event", "to", "the", "Pusher", "server", "." ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/connection.py#L206-L221
train
nlsdfnbch/Pysher
pysher/channel.py
Channel.trigger
def trigger(self, event_name, data): """Trigger an event on this channel. Only available for private or presence channels :param event_name: The name of the event. Must begin with 'client-'' :type event_name: str :param data: The data to send with the event. """ ...
python
def trigger(self, event_name, data): """Trigger an event on this channel. Only available for private or presence channels :param event_name: The name of the event. Must begin with 'client-'' :type event_name: str :param data: The data to send with the event. """ ...
[ "def", "trigger", "(", "self", ",", "event_name", ",", "data", ")", ":", "if", "self", ".", "connection", ":", "if", "event_name", ".", "startswith", "(", "\"client-\"", ")", ":", "if", "self", ".", "name", ".", "startswith", "(", "\"private-\"", ")", ...
Trigger an event on this channel. Only available for private or presence channels :param event_name: The name of the event. Must begin with 'client-'' :type event_name: str :param data: The data to send with the event.
[ "Trigger", "an", "event", "on", "this", "channel", ".", "Only", "available", "for", "private", "or", "presence", "channels" ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/channel.py#L24-L36
train
nlsdfnbch/Pysher
pysher/pusher.py
Pusher.subscribe
def subscribe(self, channel_name, auth=None): """Subscribe to a channel. :param str channel_name: The name of the channel to subscribe to. :param str auth: The token to use if authenticated externally. :rtype: pysher.Channel """ data = {'channel': channel_name} i...
python
def subscribe(self, channel_name, auth=None): """Subscribe to a channel. :param str channel_name: The name of the channel to subscribe to. :param str auth: The token to use if authenticated externally. :rtype: pysher.Channel """ data = {'channel': channel_name} i...
[ "def", "subscribe", "(", "self", ",", "channel_name", ",", "auth", "=", "None", ")", ":", "data", "=", "{", "'channel'", ":", "channel_name", "}", "if", "auth", "is", "None", ":", "if", "channel_name", ".", "startswith", "(", "'presence-'", ")", ":", "...
Subscribe to a channel. :param str channel_name: The name of the channel to subscribe to. :param str auth: The token to use if authenticated externally. :rtype: pysher.Channel
[ "Subscribe", "to", "a", "channel", "." ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/pusher.py#L87-L108
train
nlsdfnbch/Pysher
pysher/pusher.py
Pusher.unsubscribe
def unsubscribe(self, channel_name): """Unsubscribe from a channel :param str channel_name: The name of the channel to unsubscribe from. """ if channel_name in self.channels: self.connection.send_event( 'pusher:unsubscribe', { 'channel': c...
python
def unsubscribe(self, channel_name): """Unsubscribe from a channel :param str channel_name: The name of the channel to unsubscribe from. """ if channel_name in self.channels: self.connection.send_event( 'pusher:unsubscribe', { 'channel': c...
[ "def", "unsubscribe", "(", "self", ",", "channel_name", ")", ":", "if", "channel_name", "in", "self", ".", "channels", ":", "self", ".", "connection", ".", "send_event", "(", "'pusher:unsubscribe'", ",", "{", "'channel'", ":", "channel_name", ",", "}", ")", ...
Unsubscribe from a channel :param str channel_name: The name of the channel to unsubscribe from.
[ "Unsubscribe", "from", "a", "channel" ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/pusher.py#L110-L121
train
nlsdfnbch/Pysher
pysher/pusher.py
Pusher._connection_handler
def _connection_handler(self, event_name, data, channel_name): """Handle incoming data. :param str event_name: Name of the event. :param Any data: Data received. :param str channel_name: Name of the channel this event and data belongs to. """ if channel_name in self.chan...
python
def _connection_handler(self, event_name, data, channel_name): """Handle incoming data. :param str event_name: Name of the event. :param Any data: Data received. :param str channel_name: Name of the channel this event and data belongs to. """ if channel_name in self.chan...
[ "def", "_connection_handler", "(", "self", ",", "event_name", ",", "data", ",", "channel_name", ")", ":", "if", "channel_name", "in", "self", ".", "channels", ":", "self", ".", "channels", "[", "channel_name", "]", ".", "_handle_event", "(", "event_name", ",...
Handle incoming data. :param str event_name: Name of the event. :param Any data: Data received. :param str channel_name: Name of the channel this event and data belongs to.
[ "Handle", "incoming", "data", "." ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/pusher.py#L131-L139
train
nlsdfnbch/Pysher
pysher/pusher.py
Pusher._reconnect_handler
def _reconnect_handler(self): """Handle a reconnect.""" for channel_name, channel in self.channels.items(): data = {'channel': channel_name} if channel.auth: data['auth'] = channel.auth self.connection.send_event('pusher:subscribe', data)
python
def _reconnect_handler(self): """Handle a reconnect.""" for channel_name, channel in self.channels.items(): data = {'channel': channel_name} if channel.auth: data['auth'] = channel.auth self.connection.send_event('pusher:subscribe', data)
[ "def", "_reconnect_handler", "(", "self", ")", ":", "for", "channel_name", ",", "channel", "in", "self", ".", "channels", ".", "items", "(", ")", ":", "data", "=", "{", "'channel'", ":", "channel_name", "}", "if", "channel", ".", "auth", ":", "data", "...
Handle a reconnect.
[ "Handle", "a", "reconnect", "." ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/pusher.py#L141-L149
train
nlsdfnbch/Pysher
pysher/pusher.py
Pusher._generate_auth_token
def _generate_auth_token(self, channel_name): """Generate a token for authentication with the given channel. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """ subject = "{}:{}".format(self.connection.socket_id, channel_name) h = hm...
python
def _generate_auth_token(self, channel_name): """Generate a token for authentication with the given channel. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """ subject = "{}:{}".format(self.connection.socket_id, channel_name) h = hm...
[ "def", "_generate_auth_token", "(", "self", ",", "channel_name", ")", ":", "subject", "=", "\"{}:{}\"", ".", "format", "(", "self", ".", "connection", ".", "socket_id", ",", "channel_name", ")", "h", "=", "hmac", ".", "new", "(", "self", ".", "secret_as_by...
Generate a token for authentication with the given channel. :param str channel_name: Name of the channel to generate a signature for. :rtype: str
[ "Generate", "a", "token", "for", "authentication", "with", "the", "given", "channel", "." ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/pusher.py#L151-L161
train
nlsdfnbch/Pysher
pysher/pusher.py
Pusher._generate_presence_token
def _generate_presence_token(self, channel_name): """Generate a presence token. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """ subject = "{}:{}:{}".format(self.connection.socket_id, channel_name, json.dumps(self.user_data)) h = ...
python
def _generate_presence_token(self, channel_name): """Generate a presence token. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """ subject = "{}:{}:{}".format(self.connection.socket_id, channel_name, json.dumps(self.user_data)) h = ...
[ "def", "_generate_presence_token", "(", "self", ",", "channel_name", ")", ":", "subject", "=", "\"{}:{}:{}\"", ".", "format", "(", "self", ".", "connection", ".", "socket_id", ",", "channel_name", ",", "json", ".", "dumps", "(", "self", ".", "user_data", ")"...
Generate a presence token. :param str channel_name: Name of the channel to generate a signature for. :rtype: str
[ "Generate", "a", "presence", "token", "." ]
8bec81616be2b6c9a9c0e2774b42890426a73745
https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/pusher.py#L163-L173
train
lltk/lltk
lltk/nl/scrapers/uitmuntend.py
UitmuntendNl.pos
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if element.startswith(('de ', 'het ', 'het/de', 'de/het')) and not re.search('\[[\w|\s][\w|\s]+\]', element.split('\r\n')[0], re.U): tags.append('NN') if re.search('[\w|\s|/]+ \| [\w|\s|/]+ - [\w|\s|/...
python
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if element.startswith(('de ', 'het ', 'het/de', 'de/het')) and not re.search('\[[\w|\s][\w|\s]+\]', element.split('\r\n')[0], re.U): tags.append('NN') if re.search('[\w|\s|/]+ \| [\w|\s|/]+ - [\w|\s|/...
[ "def", "pos", "(", "self", ",", "element", "=", "None", ")", ":", "tags", "=", "[", "]", "if", "element", ":", "if", "element", ".", "startswith", "(", "(", "'de '", ",", "'het '", ",", "'het/de'", ",", "'de/het'", ")", ")", "and", "not", "re", "...
Tries to decide about the part of speech.
[ "Tries", "to", "decide", "about", "the", "part", "of", "speech", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/nl/scrapers/uitmuntend.py#L40-L57
train
lltk/lltk
lltk/nl/scrapers/uitmuntend.py
UitmuntendNl.articles
def articles(self): ''' Tries to scrape the correct articles for singular and plural from uitmuntend.nl. ''' result = [None, None] element = self._first('NN') if element: element = element.split('\r\n')[0] if ' | ' in element: # This means there is a plural singular, plural = element.split(' | ')...
python
def articles(self): ''' Tries to scrape the correct articles for singular and plural from uitmuntend.nl. ''' result = [None, None] element = self._first('NN') if element: element = element.split('\r\n')[0] if ' | ' in element: # This means there is a plural singular, plural = element.split(' | ')...
[ "def", "articles", "(", "self", ")", ":", "result", "=", "[", "None", ",", "None", "]", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "element", "=", "element", ".", "split", "(", "'\\r\\n'", ")", "[", "0", "]", "...
Tries to scrape the correct articles for singular and plural from uitmuntend.nl.
[ "Tries", "to", "scrape", "the", "correct", "articles", "for", "singular", "and", "plural", "from", "uitmuntend", ".", "nl", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/nl/scrapers/uitmuntend.py#L60-L79
train
lltk/lltk
lltk/nl/scrapers/uitmuntend.py
UitmuntendNl.plural
def plural(self): ''' Tries to scrape the plural version from uitmuntend.nl. ''' element = self._first('NN') if element: element = element.split('\r\n')[0] if ' | ' in element: # This means there is a plural singular, plural = element.split(' | ') return [plural.split(' ')[1]] else: # Th...
python
def plural(self): ''' Tries to scrape the plural version from uitmuntend.nl. ''' element = self._first('NN') if element: element = element.split('\r\n')[0] if ' | ' in element: # This means there is a plural singular, plural = element.split(' | ') return [plural.split(' ')[1]] else: # Th...
[ "def", "plural", "(", "self", ")", ":", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "element", "=", "element", ".", "split", "(", "'\\r\\n'", ")", "[", "0", "]", "if", "' | '", "in", "element", ":", "# This means th...
Tries to scrape the plural version from uitmuntend.nl.
[ "Tries", "to", "scrape", "the", "plural", "version", "from", "uitmuntend", ".", "nl", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/nl/scrapers/uitmuntend.py#L82-L95
train
lltk/lltk
lltk/helpers.py
download
def download(url, filename, overwrite = False): ''' Downloads a file via HTTP. ''' from requests import get from os.path import exists debug('Downloading ' + unicode(url) + '...') data = get(url) if data.status_code == 200: if not exists(filename) or overwrite: f = open(filename, 'wb') f.write(data.cont...
python
def download(url, filename, overwrite = False): ''' Downloads a file via HTTP. ''' from requests import get from os.path import exists debug('Downloading ' + unicode(url) + '...') data = get(url) if data.status_code == 200: if not exists(filename) or overwrite: f = open(filename, 'wb') f.write(data.cont...
[ "def", "download", "(", "url", ",", "filename", ",", "overwrite", "=", "False", ")", ":", "from", "requests", "import", "get", "from", "os", ".", "path", "import", "exists", "debug", "(", "'Downloading '", "+", "unicode", "(", "url", ")", "+", "'...'", ...
Downloads a file via HTTP.
[ "Downloads", "a", "file", "via", "HTTP", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/helpers.py#L6-L20
train
lltk/lltk
lltk/helpers.py
warning
def warning(message): ''' Prints a message if warning mode is enabled. ''' import lltk.config as config if config['warnings']: try: from termcolor import colored except ImportError: def colored(message, color): return message print colored('@LLTK-WARNING: ' + message, 'red')
python
def warning(message): ''' Prints a message if warning mode is enabled. ''' import lltk.config as config if config['warnings']: try: from termcolor import colored except ImportError: def colored(message, color): return message print colored('@LLTK-WARNING: ' + message, 'red')
[ "def", "warning", "(", "message", ")", ":", "import", "lltk", ".", "config", "as", "config", "if", "config", "[", "'warnings'", "]", ":", "try", ":", "from", "termcolor", "import", "colored", "except", "ImportError", ":", "def", "colored", "(", "message", ...
Prints a message if warning mode is enabled.
[ "Prints", "a", "message", "if", "warning", "mode", "is", "enabled", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/helpers.py#L42-L54
train
lltk/lltk
lltk/helpers.py
trace
def trace(f, *args, **kwargs): ''' Decorator used to trace function calls for debugging purposes. ''' print 'Calling %s() with args %s, %s ' % (f.__name__, args, kwargs) return f(*args,**kwargs)
python
def trace(f, *args, **kwargs): ''' Decorator used to trace function calls for debugging purposes. ''' print 'Calling %s() with args %s, %s ' % (f.__name__, args, kwargs) return f(*args,**kwargs)
[ "def", "trace", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "'Calling %s() with args %s, %s '", "%", "(", "f", ".", "__name__", ",", "args", ",", "kwargs", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", "...
Decorator used to trace function calls for debugging purposes.
[ "Decorator", "used", "to", "trace", "function", "calls", "for", "debugging", "purposes", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/helpers.py#L68-L72
train
lltk/lltk
lltk/nl/scrapers/vandale.py
VandaleNl.articles
def articles(self): ''' Tries to scrape the correct articles for singular and plural from vandale.nl. ''' result = [None, None] element = self._first('NN') if element: if re.search('(de|het/?de|het);', element, re.U): result[0] = re.findall('(de|het/?de|het);', element, re.U)[0].split('/') if re.sear...
python
def articles(self): ''' Tries to scrape the correct articles for singular and plural from vandale.nl. ''' result = [None, None] element = self._first('NN') if element: if re.search('(de|het/?de|het);', element, re.U): result[0] = re.findall('(de|het/?de|het);', element, re.U)[0].split('/') if re.sear...
[ "def", "articles", "(", "self", ")", ":", "result", "=", "[", "None", ",", "None", "]", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "if", "re", ".", "search", "(", "'(de|het/?de|het);'", ",", "element", ",", "re", ...
Tries to scrape the correct articles for singular and plural from vandale.nl.
[ "Tries", "to", "scrape", "the", "correct", "articles", "for", "singular", "and", "plural", "from", "vandale", ".", "nl", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/nl/scrapers/vandale.py#L56-L70
train
lltk/lltk
lltk/nl/scrapers/vandale.py
VandaleNl.plural
def plural(self): ''' Tries to scrape the plural version from vandale.nl. ''' element = self._first('NN') if element: if re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U): results = re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U).groups()[0].split(', ') results = [x.replace('ook ', '')...
python
def plural(self): ''' Tries to scrape the plural version from vandale.nl. ''' element = self._first('NN') if element: if re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U): results = re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U).groups()[0].split(', ') results = [x.replace('ook ', '')...
[ "def", "plural", "(", "self", ")", ":", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "if", "re", ".", "search", "(", "'meervoud: ([\\w|\\s|\\'|\\-|,]+)'", ",", "element", ",", "re", ".", "U", ")", ":", "results", "=", ...
Tries to scrape the plural version from vandale.nl.
[ "Tries", "to", "scrape", "the", "plural", "version", "from", "vandale", ".", "nl", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/nl/scrapers/vandale.py#L73-L85
train
lltk/lltk
lltk/nl/scrapers/vandale.py
VandaleNl.miniaturize
def miniaturize(self): ''' Tries to scrape the miniaturized version from vandale.nl. ''' element = self._first('NN') if element: if re.search('verkleinwoord: (\w+)', element, re.U): return re.findall('verkleinwoord: (\w+)', element, re.U) else: return [''] return [None]
python
def miniaturize(self): ''' Tries to scrape the miniaturized version from vandale.nl. ''' element = self._first('NN') if element: if re.search('verkleinwoord: (\w+)', element, re.U): return re.findall('verkleinwoord: (\w+)', element, re.U) else: return [''] return [None]
[ "def", "miniaturize", "(", "self", ")", ":", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "if", "re", ".", "search", "(", "'verkleinwoord: (\\w+)'", ",", "element", ",", "re", ".", "U", ")", ":", "return", "re", ".",...
Tries to scrape the miniaturized version from vandale.nl.
[ "Tries", "to", "scrape", "the", "miniaturized", "version", "from", "vandale", ".", "nl", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/nl/scrapers/vandale.py#L88-L97
train
lltk/lltk
lltk/de/scrapers/verbix.py
VerbixDe._normalize
def _normalize(self, string): ''' Returns a sanitized string. ''' string = super(VerbixDe, self)._normalize(string) string = string.replace('sie; Sie', 'sie') string = string.strip() return string
python
def _normalize(self, string): ''' Returns a sanitized string. ''' string = super(VerbixDe, self)._normalize(string) string = string.replace('sie; Sie', 'sie') string = string.strip() return string
[ "def", "_normalize", "(", "self", ",", "string", ")", ":", "string", "=", "super", "(", "VerbixDe", ",", "self", ")", ".", "_normalize", "(", "string", ")", "string", "=", "string", ".", "replace", "(", "'sie; Sie'", ",", "'sie'", ")", "string", "=", ...
Returns a sanitized string.
[ "Returns", "a", "sanitized", "string", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/de/scrapers/verbix.py#L19-L25
train
lltk/lltk
lltk/nl/scrapers/mijnwoordenboek.py
MijnWoordenBoekNl.pos
def pos(self): ''' Tries to decide about the part of speech. ''' tags = [] if self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]//text()'): info = self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]')[0].text_content() info = info.strip('I ') if info.startswith(('de', 'het')): ...
python
def pos(self): ''' Tries to decide about the part of speech. ''' tags = [] if self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]//text()'): info = self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]')[0].text_content() info = info.strip('I ') if info.startswith(('de', 'het')): ...
[ "def", "pos", "(", "self", ")", ":", "tags", "=", "[", "]", "if", "self", ".", "tree", ".", "xpath", "(", "'//div[@class=\"grad733100\"]/h2[@class=\"inline\"]//text()'", ")", ":", "info", "=", "self", ".", "tree", ".", "xpath", "(", "'//div[@class=\"grad733100...
Tries to decide about the part of speech.
[ "Tries", "to", "decide", "about", "the", "part", "of", "speech", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/nl/scrapers/mijnwoordenboek.py#L26-L39
train
lltk/lltk
lltk/fr/scrapers/verbix.py
VerbixFr._normalize
def _normalize(self, string): ''' Returns a sanitized string. ''' string = super(VerbixFr, self)._normalize(string) string = string.replace('il; elle', 'il/elle') string = string.replace('ils; elles', 'ils/elles') string = string.strip() return string
python
def _normalize(self, string): ''' Returns a sanitized string. ''' string = super(VerbixFr, self)._normalize(string) string = string.replace('il; elle', 'il/elle') string = string.replace('ils; elles', 'ils/elles') string = string.strip() return string
[ "def", "_normalize", "(", "self", ",", "string", ")", ":", "string", "=", "super", "(", "VerbixFr", ",", "self", ")", ".", "_normalize", "(", "string", ")", "string", "=", "string", ".", "replace", "(", "'il; elle'", ",", "'il/elle'", ")", "string", "=...
Returns a sanitized string.
[ "Returns", "a", "sanitized", "string", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/fr/scrapers/verbix.py#L23-L30
train
lltk/lltk
lltk/it/scrapers/leo.py
LeoIt.pos
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if re.search('[\w|\s]+ [m|f]\.', element, re.U): tags.append('NN') if '[VERB]' in element: tags.append('VB') if 'adj.' in element and re.search('([\w|\s]+, [\w|\s]+)', element, re.U): tags....
python
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if re.search('[\w|\s]+ [m|f]\.', element, re.U): tags.append('NN') if '[VERB]' in element: tags.append('VB') if 'adj.' in element and re.search('([\w|\s]+, [\w|\s]+)', element, re.U): tags....
[ "def", "pos", "(", "self", ",", "element", "=", "None", ")", ":", "tags", "=", "[", "]", "if", "element", ":", "if", "re", ".", "search", "(", "'[\\w|\\s]+ [m|f]\\.'", ",", "element", ",", "re", ".", "U", ")", ":", "tags", ".", "append", "(", "'N...
Tries to decide about the part of speech.
[ "Tries", "to", "decide", "about", "the", "part", "of", "speech", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/it/scrapers/leo.py#L45-L60
train
lltk/lltk
lltk/it/scrapers/leo.py
LeoIt.gender
def gender(self): ''' Tries to scrape the gender for a given noun from leo.org. ''' element = self._first('NN') if element: if re.search('([m|f|n)])\.', element, re.U): genus = re.findall('([m|f|n)])\.', element, re.U)[0] return genus
python
def gender(self): ''' Tries to scrape the gender for a given noun from leo.org. ''' element = self._first('NN') if element: if re.search('([m|f|n)])\.', element, re.U): genus = re.findall('([m|f|n)])\.', element, re.U)[0] return genus
[ "def", "gender", "(", "self", ")", ":", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "if", "re", ".", "search", "(", "'([m|f|n)])\\.'", ",", "element", ",", "re", ".", "U", ")", ":", "genus", "=", "re", ".", "fin...
Tries to scrape the gender for a given noun from leo.org.
[ "Tries", "to", "scrape", "the", "gender", "for", "a", "given", "noun", "from", "leo", ".", "org", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/it/scrapers/leo.py#L63-L70
train
lltk/lltk
lltk/utils.py
isempty
def isempty(result): ''' Finds out if a scraping result should be considered empty. ''' if isinstance(result, list): for element in result: if isinstance(element, list): if not isempty(element): return False else: if element is not None: return False else: if result is not None: retur...
python
def isempty(result): ''' Finds out if a scraping result should be considered empty. ''' if isinstance(result, list): for element in result: if isinstance(element, list): if not isempty(element): return False else: if element is not None: return False else: if result is not None: retur...
[ "def", "isempty", "(", "result", ")", ":", "if", "isinstance", "(", "result", ",", "list", ")", ":", "for", "element", "in", "result", ":", "if", "isinstance", "(", "element", ",", "list", ")", ":", "if", "not", "isempty", "(", "element", ")", ":", ...
Finds out if a scraping result should be considered empty.
[ "Finds", "out", "if", "a", "scraping", "result", "should", "be", "considered", "empty", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/utils.py#L6-L20
train
lltk/lltk
lltk/utils.py
method2pos
def method2pos(method): ''' Returns a list of valid POS-tags for a given method. ''' if method in ('articles', 'plural', 'miniaturize', 'gender'): pos = ['NN'] elif method in ('conjugate',): pos = ['VB'] elif method in ('comparative, superlative'): pos = ['JJ'] else: pos = ['*'] return pos
python
def method2pos(method): ''' Returns a list of valid POS-tags for a given method. ''' if method in ('articles', 'plural', 'miniaturize', 'gender'): pos = ['NN'] elif method in ('conjugate',): pos = ['VB'] elif method in ('comparative, superlative'): pos = ['JJ'] else: pos = ['*'] return pos
[ "def", "method2pos", "(", "method", ")", ":", "if", "method", "in", "(", "'articles'", ",", "'plural'", ",", "'miniaturize'", ",", "'gender'", ")", ":", "pos", "=", "[", "'NN'", "]", "elif", "method", "in", "(", "'conjugate'", ",", ")", ":", "pos", "...
Returns a list of valid POS-tags for a given method.
[ "Returns", "a", "list", "of", "valid", "POS", "-", "tags", "for", "a", "given", "method", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/utils.py#L22-L33
train
lltk/lltk
lltk/scraping.py
register
def register(scraper): ''' Registers a scraper to make it available for the generic scraping interface. ''' global scrapers language = scraper('').language if not language: raise Exception('No language specified for your scraper.') if scrapers.has_key(language): scrapers[language].append(scraper) else: scr...
python
def register(scraper): ''' Registers a scraper to make it available for the generic scraping interface. ''' global scrapers language = scraper('').language if not language: raise Exception('No language specified for your scraper.') if scrapers.has_key(language): scrapers[language].append(scraper) else: scr...
[ "def", "register", "(", "scraper", ")", ":", "global", "scrapers", "language", "=", "scraper", "(", "''", ")", ".", "language", "if", "not", "language", ":", "raise", "Exception", "(", "'No language specified for your scraper.'", ")", "if", "scrapers", ".", "h...
Registers a scraper to make it available for the generic scraping interface.
[ "Registers", "a", "scraper", "to", "make", "it", "available", "for", "the", "generic", "scraping", "interface", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L19-L29
train
lltk/lltk
lltk/scraping.py
discover
def discover(language): ''' Discovers all registered scrapers to be used for the generic scraping interface. ''' debug('Discovering scrapers for \'%s\'...' % (language,)) global scrapers, discovered for language in scrapers.iterkeys(): discovered[language] = {} for scraper in scrapers[language]: blacklist =...
python
def discover(language): ''' Discovers all registered scrapers to be used for the generic scraping interface. ''' debug('Discovering scrapers for \'%s\'...' % (language,)) global scrapers, discovered for language in scrapers.iterkeys(): discovered[language] = {} for scraper in scrapers[language]: blacklist =...
[ "def", "discover", "(", "language", ")", ":", "debug", "(", "'Discovering scrapers for \\'%s\\'...'", "%", "(", "language", ",", ")", ")", "global", "scrapers", ",", "discovered", "for", "language", "in", "scrapers", ".", "iterkeys", "(", ")", ":", "discovered...
Discovers all registered scrapers to be used for the generic scraping interface.
[ "Discovers", "all", "registered", "scrapers", "to", "be", "used", "for", "the", "generic", "scraping", "interface", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L31-L46
train
lltk/lltk
lltk/scraping.py
scrape
def scrape(language, method, word, *args, **kwargs): ''' Uses custom scrapers and calls provided method. ''' scraper = Scrape(language, word) if hasattr(scraper, method): function = getattr(scraper, method) if callable(function): return function(*args, **kwargs) else: raise NotImplementedError('The method...
python
def scrape(language, method, word, *args, **kwargs): ''' Uses custom scrapers and calls provided method. ''' scraper = Scrape(language, word) if hasattr(scraper, method): function = getattr(scraper, method) if callable(function): return function(*args, **kwargs) else: raise NotImplementedError('The method...
[ "def", "scrape", "(", "language", ",", "method", ",", "word", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "scraper", "=", "Scrape", "(", "language", ",", "word", ")", "if", "hasattr", "(", "scraper", ",", "method", ")", ":", "function", "=...
Uses custom scrapers and calls provided method.
[ "Uses", "custom", "scrapers", "and", "calls", "provided", "method", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L48-L57
train
lltk/lltk
lltk/scraping.py
Scrape.iterscrapers
def iterscrapers(self, method, mode = None): ''' Iterates over all available scrapers. ''' global discovered if discovered.has_key(self.language) and discovered[self.language].has_key(method): for Scraper in discovered[self.language][method]: yield Scraper
python
def iterscrapers(self, method, mode = None): ''' Iterates over all available scrapers. ''' global discovered if discovered.has_key(self.language) and discovered[self.language].has_key(method): for Scraper in discovered[self.language][method]: yield Scraper
[ "def", "iterscrapers", "(", "self", ",", "method", ",", "mode", "=", "None", ")", ":", "global", "discovered", "if", "discovered", ".", "has_key", "(", "self", ".", "language", ")", "and", "discovered", "[", "self", ".", "language", "]", ".", "has_key", ...
Iterates over all available scrapers.
[ "Iterates", "over", "all", "available", "scrapers", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L99-L105
train
lltk/lltk
lltk/scraping.py
Scrape.merge
def merge(self, elements): ''' Merges all scraping results to a list sorted by frequency of occurrence. ''' from collections import Counter from lltk.utils import list2tuple, tuple2list # The list2tuple conversion is necessary because mutable objects (e.g. lists) are not hashable merged = tuple2list([value f...
python
def merge(self, elements): ''' Merges all scraping results to a list sorted by frequency of occurrence. ''' from collections import Counter from lltk.utils import list2tuple, tuple2list # The list2tuple conversion is necessary because mutable objects (e.g. lists) are not hashable merged = tuple2list([value f...
[ "def", "merge", "(", "self", ",", "elements", ")", ":", "from", "collections", "import", "Counter", "from", "lltk", ".", "utils", "import", "list2tuple", ",", "tuple2list", "# The list2tuple conversion is necessary because mutable objects (e.g. lists) are not hashable", "me...
Merges all scraping results to a list sorted by frequency of occurrence.
[ "Merges", "all", "scraping", "results", "to", "a", "list", "sorted", "by", "frequency", "of", "occurrence", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L147-L154
train
lltk/lltk
lltk/scraping.py
Scrape.clean
def clean(self, elements): ''' Removes empty or incomplete answers. ''' cleanelements = [] for i in xrange(len(elements)): if isempty(elements[i]): return [] next = elements[i] if isinstance(elements[i], (list, tuple)): next = self.clean(elements[i]) if next: cleanelements.append(elements...
python
def clean(self, elements): ''' Removes empty or incomplete answers. ''' cleanelements = [] for i in xrange(len(elements)): if isempty(elements[i]): return [] next = elements[i] if isinstance(elements[i], (list, tuple)): next = self.clean(elements[i]) if next: cleanelements.append(elements...
[ "def", "clean", "(", "self", ",", "elements", ")", ":", "cleanelements", "=", "[", "]", "for", "i", "in", "xrange", "(", "len", "(", "elements", ")", ")", ":", "if", "isempty", "(", "elements", "[", "i", "]", ")", ":", "return", "[", "]", "next",...
Removes empty or incomplete answers.
[ "Removes", "empty", "or", "incomplete", "answers", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L156-L168
train
lltk/lltk
lltk/scraping.py
GenericScraper._needs_download
def _needs_download(self, f): ''' Decorator used to make sure that the downloading happens prior to running the task. ''' @wraps(f) def wrapper(self, *args, **kwargs): if not self.isdownloaded(): self.download() return f(self, *args, **kwargs) return wrapper
python
def _needs_download(self, f): ''' Decorator used to make sure that the downloading happens prior to running the task. ''' @wraps(f) def wrapper(self, *args, **kwargs): if not self.isdownloaded(): self.download() return f(self, *args, **kwargs) return wrapper
[ "def", "_needs_download", "(", "self", ",", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "isdownloaded", "(", ")", ":", "self", ".", "d...
Decorator used to make sure that the downloading happens prior to running the task.
[ "Decorator", "used", "to", "make", "sure", "that", "the", "downloading", "happens", "prior", "to", "running", "the", "task", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L188-L196
train
lltk/lltk
lltk/scraping.py
GenericScraper.download
def download(self): ''' Downloads HTML from url. ''' self.page = requests.get(self.url) self.tree = html.fromstring(self.page.text)
python
def download(self): ''' Downloads HTML from url. ''' self.page = requests.get(self.url) self.tree = html.fromstring(self.page.text)
[ "def", "download", "(", "self", ")", ":", "self", ".", "page", "=", "requests", ".", "get", "(", "self", ".", "url", ")", "self", ".", "tree", "=", "html", ".", "fromstring", "(", "self", ".", "page", ".", "text", ")" ]
Downloads HTML from url.
[ "Downloads", "HTML", "from", "url", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L198-L202
train
lltk/lltk
lltk/scraping.py
DictScraper._needs_elements
def _needs_elements(self, f): ''' Decorator used to make sure that there are elements prior to running the task. ''' @wraps(f) def wrapper(self, *args, **kwargs): if self.elements == None: self.getelements() return f(self, *args, **kwargs) return wrapper
python
def _needs_elements(self, f): ''' Decorator used to make sure that there are elements prior to running the task. ''' @wraps(f) def wrapper(self, *args, **kwargs): if self.elements == None: self.getelements() return f(self, *args, **kwargs) return wrapper
[ "def", "_needs_elements", "(", "self", ",", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "elements", "==", "None", ":", "self", ".", "getelement...
Decorator used to make sure that there are elements prior to running the task.
[ "Decorator", "used", "to", "make", "sure", "that", "there", "are", "elements", "prior", "to", "running", "the", "task", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L252-L260
train
lltk/lltk
lltk/scraping.py
DictScraper._first
def _first(self, tag): ''' Returns the first element with required POS-tag. ''' self.getelements() for element in self.elements: if tag in self.pos(element): return element return None
python
def _first(self, tag): ''' Returns the first element with required POS-tag. ''' self.getelements() for element in self.elements: if tag in self.pos(element): return element return None
[ "def", "_first", "(", "self", ",", "tag", ")", ":", "self", ".", "getelements", "(", ")", "for", "element", "in", "self", ".", "elements", ":", "if", "tag", "in", "self", ".", "pos", "(", "element", ")", ":", "return", "element", "return", "None" ]
Returns the first element with required POS-tag.
[ "Returns", "the", "first", "element", "with", "required", "POS", "-", "tag", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L262-L269
train
lltk/lltk
lltk/de/scrapers/pons.py
PonsDe._normalize
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xb7', '') string = string.replace(u'\u0331', '') string = string.replace(u'\u0323', '') string = string.strip(' \n\rI.') return string
python
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xb7', '') string = string.replace(u'\u0331', '') string = string.replace(u'\u0323', '') string = string.strip(' \n\rI.') return string
[ "def", "_normalize", "(", "self", ",", "string", ")", ":", "string", "=", "string", ".", "replace", "(", "u'\\xb7'", ",", "''", ")", "string", "=", "string", ".", "replace", "(", "u'\\u0331'", ",", "''", ")", "string", "=", "string", ".", "replace", ...
Returns a sanitized string.
[ "Returns", "a", "sanitized", "string", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/de/scrapers/pons.py#L20-L27
train
lltk/lltk
lltk/de/scrapers/pons.py
PonsDe.pos
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if element.startswith(('der', 'die', 'das')): tags.append('NN') if ' VERB' in element: tags.append('VB') if ' ADJ' in element: tags.append('JJ') else: for element in self.elements: ...
python
def pos(self, element = None): ''' Tries to decide about the part of speech. ''' tags = [] if element: if element.startswith(('der', 'die', 'das')): tags.append('NN') if ' VERB' in element: tags.append('VB') if ' ADJ' in element: tags.append('JJ') else: for element in self.elements: ...
[ "def", "pos", "(", "self", ",", "element", "=", "None", ")", ":", "tags", "=", "[", "]", "if", "element", ":", "if", "element", ".", "startswith", "(", "(", "'der'", ",", "'die'", ",", "'das'", ")", ")", ":", "tags", ".", "append", "(", "'NN'", ...
Tries to decide about the part of speech.
[ "Tries", "to", "decide", "about", "the", "part", "of", "speech", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/de/scrapers/pons.py#L46-L61
train
lltk/lltk
lltk/de/scrapers/pons.py
PonsDe.articles
def articles(self): ''' Tries to scrape the correct articles for singular and plural from de.pons.eu. ''' result = [None, None] element = self._first('NN') if element: result[0] = [element.split(' ')[0].replace('(die)', '').strip()] if 'kein Plur' in element: # There is no plural result[1] = ['']...
python
def articles(self): ''' Tries to scrape the correct articles for singular and plural from de.pons.eu. ''' result = [None, None] element = self._first('NN') if element: result[0] = [element.split(' ')[0].replace('(die)', '').strip()] if 'kein Plur' in element: # There is no plural result[1] = ['']...
[ "def", "articles", "(", "self", ")", ":", "result", "=", "[", "None", ",", "None", "]", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "result", "[", "0", "]", "=", "[", "element", ".", "split", "(", "' '", ")", ...
Tries to scrape the correct articles for singular and plural from de.pons.eu.
[ "Tries", "to", "scrape", "the", "correct", "articles", "for", "singular", "and", "plural", "from", "de", ".", "pons", ".", "eu", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/de/scrapers/pons.py#L64-L77
train
lltk/lltk
lltk/de/scrapers/pons.py
PonsDe.plural
def plural(self): ''' Tries to scrape the plural version from pons.eu. ''' element = self._first('NN') if element: if 'kein Plur' in element: # There is no plural return [''] if re.search(', ([\w|\s|/]+)>', element, re.U): # Plural form is provided return re.findall(', ([\w|\s|/]+)>', eleme...
python
def plural(self): ''' Tries to scrape the plural version from pons.eu. ''' element = self._first('NN') if element: if 'kein Plur' in element: # There is no plural return [''] if re.search(', ([\w|\s|/]+)>', element, re.U): # Plural form is provided return re.findall(', ([\w|\s|/]+)>', eleme...
[ "def", "plural", "(", "self", ")", ":", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "if", "'kein Plur'", "in", "element", ":", "# There is no plural", "return", "[", "''", "]", "if", "re", ".", "search", "(", "', ([\\...
Tries to scrape the plural version from pons.eu.
[ "Tries", "to", "scrape", "the", "plural", "version", "from", "pons", ".", "eu", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/de/scrapers/pons.py#L80-L98
train
lltk/lltk
lltk/generic.py
reference
def reference(language, word): ''' Returns the articles (singular and plural) combined with singular and plural for a given noun. ''' sg, pl, art = word, '/'.join(plural(language, word) or ['-']), [[''], ['']] art[0], art[1] = articles(language, word) or (['-'], ['-']) result = ['%s %s' % ('/'.join(art[0]), sg), ...
python
def reference(language, word): ''' Returns the articles (singular and plural) combined with singular and plural for a given noun. ''' sg, pl, art = word, '/'.join(plural(language, word) or ['-']), [[''], ['']] art[0], art[1] = articles(language, word) or (['-'], ['-']) result = ['%s %s' % ('/'.join(art[0]), sg), ...
[ "def", "reference", "(", "language", ",", "word", ")", ":", "sg", ",", "pl", ",", "art", "=", "word", ",", "'/'", ".", "join", "(", "plural", "(", "language", ",", "word", ")", "or", "[", "'-'", "]", ")", ",", "[", "[", "''", "]", ",", "[", ...
Returns the articles (singular and plural) combined with singular and plural for a given noun.
[ "Returns", "the", "articles", "(", "singular", "and", "plural", ")", "combined", "with", "singular", "and", "plural", "for", "a", "given", "noun", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/generic.py#L54-L61
train
lltk/lltk
lltk/generic.py
translate
def translate(src, dest, word): ''' Translates a word using Google Translate. ''' results = [] try: from textblob import TextBlob results.append(TextBlob(word).translate(from_lang = src, to = dest).string) except ImportError: pass if not results: return [None] return results
python
def translate(src, dest, word): ''' Translates a word using Google Translate. ''' results = [] try: from textblob import TextBlob results.append(TextBlob(word).translate(from_lang = src, to = dest).string) except ImportError: pass if not results: return [None] return results
[ "def", "translate", "(", "src", ",", "dest", ",", "word", ")", ":", "results", "=", "[", "]", "try", ":", "from", "textblob", "import", "TextBlob", "results", ".", "append", "(", "TextBlob", "(", "word", ")", ".", "translate", "(", "from_lang", "=", ...
Translates a word using Google Translate.
[ "Translates", "a", "word", "using", "Google", "Translate", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/generic.py#L64-L77
train
lltk/lltk
lltk/generic.py
audiosamples
def audiosamples(language, word, key = ''): ''' Returns a list of URLs to suitable audiosamples for a given word. ''' from lltk.audiosamples import forvo, google urls = [] urls += forvo(language, word, key) urls += google(language, word) return urls
python
def audiosamples(language, word, key = ''): ''' Returns a list of URLs to suitable audiosamples for a given word. ''' from lltk.audiosamples import forvo, google urls = [] urls += forvo(language, word, key) urls += google(language, word) return urls
[ "def", "audiosamples", "(", "language", ",", "word", ",", "key", "=", "''", ")", ":", "from", "lltk", ".", "audiosamples", "import", "forvo", ",", "google", "urls", "=", "[", "]", "urls", "+=", "forvo", "(", "language", ",", "word", ",", "key", ")", ...
Returns a list of URLs to suitable audiosamples for a given word.
[ "Returns", "a", "list", "of", "URLs", "to", "suitable", "audiosamples", "for", "a", "given", "word", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/generic.py#L81-L89
train
lltk/lltk
lltk/generic.py
images
def images(language, word, n = 20, *args, **kwargs): ''' Returns a list of URLs to suitable images for a given word.''' from lltk.images import google return google(language, word, n, *args, **kwargs)
python
def images(language, word, n = 20, *args, **kwargs): ''' Returns a list of URLs to suitable images for a given word.''' from lltk.images import google return google(language, word, n, *args, **kwargs)
[ "def", "images", "(", "language", ",", "word", ",", "n", "=", "20", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "lltk", ".", "images", "import", "google", "return", "google", "(", "language", ",", "word", ",", "n", ",", "*", "arg...
Returns a list of URLs to suitable images for a given word.
[ "Returns", "a", "list", "of", "URLs", "to", "suitable", "images", "for", "a", "given", "word", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/generic.py#L99-L103
train
lltk/lltk
lltk/it/it.py
articles
def articles(word): ''' Returns the articles (singular and plural) for a given noun. ''' from pattern.it import article result = [[None], [None]] genus = gender(word) or 'f' result[0] = [article(word, function = 'definite', gender = genus)] result[1] = [article(plural(word)[0], function = 'definite', gender = (...
python
def articles(word): ''' Returns the articles (singular and plural) for a given noun. ''' from pattern.it import article result = [[None], [None]] genus = gender(word) or 'f' result[0] = [article(word, function = 'definite', gender = genus)] result[1] = [article(plural(word)[0], function = 'definite', gender = (...
[ "def", "articles", "(", "word", ")", ":", "from", "pattern", ".", "it", "import", "article", "result", "=", "[", "[", "None", "]", ",", "[", "None", "]", "]", "genus", "=", "gender", "(", "word", ")", "or", "'f'", "result", "[", "0", "]", "=", ...
Returns the articles (singular and plural) for a given noun.
[ "Returns", "the", "articles", "(", "singular", "and", "plural", ")", "for", "a", "given", "noun", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/it/it.py#L17-L26
train
lltk/lltk
lltk/images/google.py
google
def google(language, word, n = 8, *args, **kwargs): ''' Downloads suitable images for a given word from Google Images. ''' if not kwargs.has_key('start'): kwargs['start'] = 0 if not kwargs.has_key('itype'): kwargs['itype'] = 'photo|clipart|lineart' if not kwargs.has_key('isize'): kwargs['isize'] = 'small|med...
python
def google(language, word, n = 8, *args, **kwargs): ''' Downloads suitable images for a given word from Google Images. ''' if not kwargs.has_key('start'): kwargs['start'] = 0 if not kwargs.has_key('itype'): kwargs['itype'] = 'photo|clipart|lineart' if not kwargs.has_key('isize'): kwargs['isize'] = 'small|med...
[ "def", "google", "(", "language", ",", "word", ",", "n", "=", "8", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "has_key", "(", "'start'", ")", ":", "kwargs", "[", "'start'", "]", "=", "0", "if", "not", "kwar...
Downloads suitable images for a given word from Google Images.
[ "Downloads", "suitable", "images", "for", "a", "given", "word", "from", "Google", "Images", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/images/google.py#L9-L37
train
lltk/lltk
lltk/scrapers/verbix.py
Verbix._normalize
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xa0', '') string = string.strip() return string
python
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xa0', '') string = string.strip() return string
[ "def", "_normalize", "(", "self", ",", "string", ")", ":", "string", "=", "string", ".", "replace", "(", "u'\\xa0'", ",", "''", ")", "string", "=", "string", ".", "strip", "(", ")", "return", "string" ]
Returns a sanitized string.
[ "Returns", "a", "sanitized", "string", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scrapers/verbix.py#L22-L27
train
lltk/lltk
lltk/scrapers/verbix.py
Verbix._extract
def _extract(self, identifier): ''' Extracts data from conjugation table. ''' conjugation = [] if self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]'): p = self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]')[0].getparent() for font in...
python
def _extract(self, identifier): ''' Extracts data from conjugation table. ''' conjugation = [] if self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]'): p = self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]')[0].getparent() for font in...
[ "def", "_extract", "(", "self", ",", "identifier", ")", ":", "conjugation", "=", "[", "]", "if", "self", ".", "tree", ".", "xpath", "(", "'//p/b[normalize-space(text()) = \"'", "+", "identifier", ".", "decode", "(", "'utf-8'", ")", "+", "'\"]'", ")", ":", ...
Extracts data from conjugation table.
[ "Extracts", "data", "from", "conjugation", "table", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scrapers/verbix.py#L30-L46
train
lltk/lltk
lltk/scrapers/verbix.py
Verbix.conjugate
def conjugate(self, tense = 'present'): ''' Tries to conjugate a given verb using verbix.com.''' if self.tenses.has_key(tense): return self._extract(self.tenses[tense]) elif self.tenses.has_key(tense.title()): return self._extract(self.tenses[tense.title()]) return [None]
python
def conjugate(self, tense = 'present'): ''' Tries to conjugate a given verb using verbix.com.''' if self.tenses.has_key(tense): return self._extract(self.tenses[tense]) elif self.tenses.has_key(tense.title()): return self._extract(self.tenses[tense.title()]) return [None]
[ "def", "conjugate", "(", "self", ",", "tense", "=", "'present'", ")", ":", "if", "self", ".", "tenses", ".", "has_key", "(", "tense", ")", ":", "return", "self", ".", "_extract", "(", "self", ".", "tenses", "[", "tense", "]", ")", "elif", "self", "...
Tries to conjugate a given verb using verbix.com.
[ "Tries", "to", "conjugate", "a", "given", "verb", "using", "verbix", ".", "com", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scrapers/verbix.py#L48-L55
train
lltk/lltk
lltk/config/__init__.py
Config.load
def load(self, filename, replace = False): ''' Loads a configuration file (JSON). ''' import os, json, re if os.path.exists(filename): f = open(filename, 'r') content = f.read() content = re.sub('[\t ]*?[#].*?\n', '', content) try: settings = json.loads(content) except ValueError: # This m...
python
def load(self, filename, replace = False): ''' Loads a configuration file (JSON). ''' import os, json, re if os.path.exists(filename): f = open(filename, 'r') content = f.read() content = re.sub('[\t ]*?[#].*?\n', '', content) try: settings = json.loads(content) except ValueError: # This m...
[ "def", "load", "(", "self", ",", "filename", ",", "replace", "=", "False", ")", ":", "import", "os", ",", "json", ",", "re", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "'r'", ")", ...
Loads a configuration file (JSON).
[ "Loads", "a", "configuration", "file", "(", "JSON", ")", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/config/__init__.py#L39-L64
train
lltk/lltk
lltk/config/__init__.py
Config.save
def save(self, filename): ''' Saves the current configuration to file 'filename' (JSON). ''' import json f = open(filename, 'w') json.dump(self.settings, f, indent = 4) f.close()
python
def save(self, filename): ''' Saves the current configuration to file 'filename' (JSON). ''' import json f = open(filename, 'w') json.dump(self.settings, f, indent = 4) f.close()
[ "def", "save", "(", "self", ",", "filename", ")", ":", "import", "json", "f", "=", "open", "(", "filename", ",", "'w'", ")", "json", ".", "dump", "(", "self", ".", "settings", ",", "f", ",", "indent", "=", "4", ")", "f", ".", "close", "(", ")" ...
Saves the current configuration to file 'filename' (JSON).
[ "Saves", "the", "current", "configuration", "to", "file", "filename", "(", "JSON", ")", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/config/__init__.py#L66-L72
train
lltk/lltk
lltk/audiosamples/forvo.py
forvo
def forvo(language, word, key): ''' Returns a list of suitable audiosamples for a given word from Forvo.com. ''' from requests import get url = 'http://apifree.forvo.com/action/word-pronunciations/format/json/word/%s/language/%s/key/%s/' % (word, language, key) urls = [] page = get(url) if page.status_code == ...
python
def forvo(language, word, key): ''' Returns a list of suitable audiosamples for a given word from Forvo.com. ''' from requests import get url = 'http://apifree.forvo.com/action/word-pronunciations/format/json/word/%s/language/%s/key/%s/' % (word, language, key) urls = [] page = get(url) if page.status_code == ...
[ "def", "forvo", "(", "language", ",", "word", ",", "key", ")", ":", "from", "requests", "import", "get", "url", "=", "'http://apifree.forvo.com/action/word-pronunciations/format/json/word/%s/language/%s/key/%s/'", "%", "(", "word", ",", "language", ",", "key", ")", ...
Returns a list of suitable audiosamples for a given word from Forvo.com.
[ "Returns", "a", "list", "of", "suitable", "audiosamples", "for", "a", "given", "word", "from", "Forvo", ".", "com", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/audiosamples/forvo.py#L4-L25
train
lltk/lltk
lltk/de/scrapers/wiktionary.py
WiktionaryDe._normalize
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xb7', '') string = string.replace(u'\xa0', ' ') string = string.replace('selten: ', '') string = string.replace('Alte Rechtschreibung', '') string = string.strip() return string
python
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xb7', '') string = string.replace(u'\xa0', ' ') string = string.replace('selten: ', '') string = string.replace('Alte Rechtschreibung', '') string = string.strip() return string
[ "def", "_normalize", "(", "self", ",", "string", ")", ":", "string", "=", "string", ".", "replace", "(", "u'\\xb7'", ",", "''", ")", "string", "=", "string", ".", "replace", "(", "u'\\xa0'", ",", "' '", ")", "string", "=", "string", ".", "replace", "...
Returns a sanitized string.
[ "Returns", "a", "sanitized", "string", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/de/scrapers/wiktionary.py#L20-L28
train
lltk/lltk
lltk/de/scrapers/wiktionary.py
WiktionaryDe.pos
def pos(self): ''' Tries to decide about the part of speech. ''' tags = [] if self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()'): info = self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()')[0] if info == 'Substantiv': tags.append('NN') if i...
python
def pos(self): ''' Tries to decide about the part of speech. ''' tags = [] if self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()'): info = self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()')[0] if info == 'Substantiv': tags.append('NN') if i...
[ "def", "pos", "(", "self", ")", ":", "tags", "=", "[", "]", "if", "self", ".", "tree", ".", "xpath", "(", "'//div[@id=\"mw-content-text\"]//a[@title=\"Hilfe:Wortart\"]/text()'", ")", ":", "info", "=", "self", ".", "tree", ".", "xpath", "(", "'//div[@id=\"mw-co...
Tries to decide about the part of speech.
[ "Tries", "to", "decide", "about", "the", "part", "of", "speech", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/de/scrapers/wiktionary.py#L31-L43
train
lltk/lltk
lltk/caching.py
register
def register(cache): ''' Registers a cache. ''' global caches name = cache().name if not caches.has_key(name): caches[name] = cache
python
def register(cache): ''' Registers a cache. ''' global caches name = cache().name if not caches.has_key(name): caches[name] = cache
[ "def", "register", "(", "cache", ")", ":", "global", "caches", "name", "=", "cache", "(", ")", ".", "name", "if", "not", "caches", ".", "has_key", "(", "name", ")", ":", "caches", "[", "name", "]", "=", "cache" ]
Registers a cache.
[ "Registers", "a", "cache", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/caching.py#L15-L21
train
lltk/lltk
lltk/caching.py
enable
def enable(identifier = None, *args, **kwargs): ''' Enables a specific cache for the current session. Remember that is has to be registered. ''' global cache if not identifier: for item in (config['default-caches'] + ['NoCache']): if caches.has_key(item): debug('Enabling default cache %s...' % (item,)) ...
python
def enable(identifier = None, *args, **kwargs): ''' Enables a specific cache for the current session. Remember that is has to be registered. ''' global cache if not identifier: for item in (config['default-caches'] + ['NoCache']): if caches.has_key(item): debug('Enabling default cache %s...' % (item,)) ...
[ "def", "enable", "(", "identifier", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "cache", "if", "not", "identifier", ":", "for", "item", "in", "(", "config", "[", "'default-caches'", "]", "+", "[", "'NoCache'", "]", ")"...
Enables a specific cache for the current session. Remember that is has to be registered.
[ "Enables", "a", "specific", "cache", "for", "the", "current", "session", ".", "Remember", "that", "is", "has", "to", "be", "registered", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/caching.py#L23-L47
train
lltk/lltk
lltk/caching.py
cached
def cached(key = None, extradata = {}): ''' Decorator used for caching. ''' def decorator(f): @wraps(f) def wrapper(*args, **kwargs): uid = key if not uid: from hashlib import md5 arguments = list(args) + [(a, kwargs[a]) for a in sorted(kwargs.keys())] uid = md5(str(arguments)).hexdigest() ...
python
def cached(key = None, extradata = {}): ''' Decorator used for caching. ''' def decorator(f): @wraps(f) def wrapper(*args, **kwargs): uid = key if not uid: from hashlib import md5 arguments = list(args) + [(a, kwargs[a]) for a in sorted(kwargs.keys())] uid = md5(str(arguments)).hexdigest() ...
[ "def", "cached", "(", "key", "=", "None", ",", "extradata", "=", "{", "}", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "uid", "=", "key"...
Decorator used for caching.
[ "Decorator", "used", "for", "caching", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/caching.py#L85-L109
train
lltk/lltk
lltk/caching.py
GenericCache.needsconnection
def needsconnection(self, f): ''' Decorator used to make sure that the connection has been established. ''' @wraps(f) def wrapper(self, *args, **kwargs): if not self.connection: self.connect() return f(self, *args, **kwargs) return wrapper
python
def needsconnection(self, f): ''' Decorator used to make sure that the connection has been established. ''' @wraps(f) def wrapper(self, *args, **kwargs): if not self.connection: self.connect() return f(self, *args, **kwargs) return wrapper
[ "def", "needsconnection", "(", "self", ",", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "connection", ":", "self", ".", "connect", "(", ...
Decorator used to make sure that the connection has been established.
[ "Decorator", "used", "to", "make", "sure", "that", "the", "connection", "has", "been", "established", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/caching.py#L142-L150
train
lltk/lltk
lltk/decorators.py
language
def language(l): ''' Use this as a decorator (implicitly or explicitly). ''' # Usage: @language('en') or function = language('en')(function) def decorator(f): ''' Decorator used to prepend the language as an argument. ''' @wraps(f) def wrapper(*args, **kwargs): return f(l, *args, **kwargs) return wrapp...
python
def language(l): ''' Use this as a decorator (implicitly or explicitly). ''' # Usage: @language('en') or function = language('en')(function) def decorator(f): ''' Decorator used to prepend the language as an argument. ''' @wraps(f) def wrapper(*args, **kwargs): return f(l, *args, **kwargs) return wrapp...
[ "def", "language", "(", "l", ")", ":", "# Usage: @language('en') or function = language('en')(function)", "def", "decorator", "(", "f", ")", ":", "''' Decorator used to prepend the language as an argument. '''", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "...
Use this as a decorator (implicitly or explicitly).
[ "Use", "this", "as", "a", "decorator", "(", "implicitly", "or", "explicitly", ")", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/decorators.py#L6-L19
train
lltk/lltk
lltk/decorators.py
_load_language_or_die
def _load_language_or_die(f): ''' Decorator used to load a custom method for a given language. ''' # This decorator checks if there's a custom method for a given language. # If so, prefer the custom method, otherwise raise exception NotImplementedError. @wraps(f) def loader(language, word, *args, **kwargs): me...
python
def _load_language_or_die(f): ''' Decorator used to load a custom method for a given language. ''' # This decorator checks if there's a custom method for a given language. # If so, prefer the custom method, otherwise raise exception NotImplementedError. @wraps(f) def loader(language, word, *args, **kwargs): me...
[ "def", "_load_language_or_die", "(", "f", ")", ":", "# This decorator checks if there's a custom method for a given language.", "# If so, prefer the custom method, otherwise raise exception NotImplementedError.", "@", "wraps", "(", "f", ")", "def", "loader", "(", "language", ",", ...
Decorator used to load a custom method for a given language.
[ "Decorator", "used", "to", "load", "a", "custom", "method", "for", "a", "given", "language", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/decorators.py#L47-L71
train
lltk/lltk
lltk/textsamples/tatoeba.py
tatoeba
def tatoeba(language, word, minlength = 10, maxlength = 100): ''' Returns a list of suitable textsamples for a given word using Tatoeba.org. ''' word, sentences = unicode(word), [] page = requests.get('http://tatoeba.org/deu/sentences/search?query=%s&from=%s&to=und' % (word, lltk.locale.iso639_1to3(language))) tre...
python
def tatoeba(language, word, minlength = 10, maxlength = 100): ''' Returns a list of suitable textsamples for a given word using Tatoeba.org. ''' word, sentences = unicode(word), [] page = requests.get('http://tatoeba.org/deu/sentences/search?query=%s&from=%s&to=und' % (word, lltk.locale.iso639_1to3(language))) tre...
[ "def", "tatoeba", "(", "language", ",", "word", ",", "minlength", "=", "10", ",", "maxlength", "=", "100", ")", ":", "word", ",", "sentences", "=", "unicode", "(", "word", ")", ",", "[", "]", "page", "=", "requests", ".", "get", "(", "'http://tatoeba...
Returns a list of suitable textsamples for a given word using Tatoeba.org.
[ "Returns", "a", "list", "of", "suitable", "textsamples", "for", "a", "given", "word", "using", "Tatoeba", ".", "org", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/textsamples/tatoeba.py#L8-L18
train
lltk/lltk
lltk/it/scrapers/wordreference.py
WordreferenceIt.gender
def gender(self): ''' Tries to scrape the correct gender for a given word from wordreference.com ''' elements = self.tree.xpath('//table[@class="WRD"]') if len(elements): elements = self.tree.xpath('//table[@class="WRD"]')[0] if len(elements): if '/iten/' in self.page.url: elements = elements.xpat...
python
def gender(self): ''' Tries to scrape the correct gender for a given word from wordreference.com ''' elements = self.tree.xpath('//table[@class="WRD"]') if len(elements): elements = self.tree.xpath('//table[@class="WRD"]')[0] if len(elements): if '/iten/' in self.page.url: elements = elements.xpat...
[ "def", "gender", "(", "self", ")", ":", "elements", "=", "self", ".", "tree", ".", "xpath", "(", "'//table[@class=\"WRD\"]'", ")", "if", "len", "(", "elements", ")", ":", "elements", "=", "self", ".", "tree", ".", "xpath", "(", "'//table[@class=\"WRD\"]'",...
Tries to scrape the correct gender for a given word from wordreference.com
[ "Tries", "to", "scrape", "the", "correct", "gender", "for", "a", "given", "word", "from", "wordreference", ".", "com" ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/it/scrapers/wordreference.py#L20-L38
train
lltk/lltk
lltk/locale/locale.py
humanize
def humanize(iso639): ''' Converts ISO639 language identifier to the corresponding (human readable) language name. ''' for i, element in enumerate(LANGUAGES): if element[1] == iso639 or element[2] == iso639: return element[0] return None
python
def humanize(iso639): ''' Converts ISO639 language identifier to the corresponding (human readable) language name. ''' for i, element in enumerate(LANGUAGES): if element[1] == iso639 or element[2] == iso639: return element[0] return None
[ "def", "humanize", "(", "iso639", ")", ":", "for", "i", ",", "element", "in", "enumerate", "(", "LANGUAGES", ")", ":", "if", "element", "[", "1", "]", "==", "iso639", "or", "element", "[", "2", "]", "==", "iso639", ":", "return", "element", "[", "0...
Converts ISO639 language identifier to the corresponding (human readable) language name.
[ "Converts", "ISO639", "language", "identifier", "to", "the", "corresponding", "(", "human", "readable", ")", "language", "name", "." ]
d171de55c1b97695fddedf4b02401ae27bf1d634
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/locale/locale.py#L220-L226
train
getsentry/rb
rb/cluster.py
Cluster.add_host
def add_host(self, host_id=None, host='localhost', port=6379, unix_socket_path=None, db=0, password=None, ssl=False, ssl_options=None): """Adds a new host to the cluster. This is only really useful for unittests as normally hosts are added through the constructor and ...
python
def add_host(self, host_id=None, host='localhost', port=6379, unix_socket_path=None, db=0, password=None, ssl=False, ssl_options=None): """Adds a new host to the cluster. This is only really useful for unittests as normally hosts are added through the constructor and ...
[ "def", "add_host", "(", "self", ",", "host_id", "=", "None", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ",", "unix_socket_path", "=", "None", ",", "db", "=", "0", ",", "password", "=", "None", ",", "ssl", "=", "False", ",", "ssl_optio...
Adds a new host to the cluster. This is only really useful for unittests as normally hosts are added through the constructor and changes after the cluster has been used for the first time are unlikely to make sense.
[ "Adds", "a", "new", "host", "to", "the", "cluster", ".", "This", "is", "only", "really", "useful", "for", "unittests", "as", "normally", "hosts", "are", "added", "through", "the", "constructor", "and", "changes", "after", "the", "cluster", "has", "been", "...
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L111-L133
train
getsentry/rb
rb/cluster.py
Cluster.remove_host
def remove_host(self, host_id): """Removes a host from the client. This only really useful for unittests. """ with self._lock: rv = self._hosts.pop(host_id, None) is not None pool = self._pools.pop(host_id, None) if pool is not None: p...
python
def remove_host(self, host_id): """Removes a host from the client. This only really useful for unittests. """ with self._lock: rv = self._hosts.pop(host_id, None) is not None pool = self._pools.pop(host_id, None) if pool is not None: p...
[ "def", "remove_host", "(", "self", ",", "host_id", ")", ":", "with", "self", ".", "_lock", ":", "rv", "=", "self", ".", "_hosts", ".", "pop", "(", "host_id", ",", "None", ")", "is", "not", "None", "pool", "=", "self", ".", "_pools", ".", "pop", "...
Removes a host from the client. This only really useful for unittests.
[ "Removes", "a", "host", "from", "the", "client", ".", "This", "only", "really", "useful", "for", "unittests", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L135-L145
train
getsentry/rb
rb/cluster.py
Cluster.disconnect_pools
def disconnect_pools(self): """Disconnects all connections from the internal pools.""" with self._lock: for pool in self._pools.itervalues(): pool.disconnect() self._pools.clear()
python
def disconnect_pools(self): """Disconnects all connections from the internal pools.""" with self._lock: for pool in self._pools.itervalues(): pool.disconnect() self._pools.clear()
[ "def", "disconnect_pools", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "for", "pool", "in", "self", ".", "_pools", ".", "itervalues", "(", ")", ":", "pool", ".", "disconnect", "(", ")", "self", ".", "_pools", ".", "clear", "(", ")" ]
Disconnects all connections from the internal pools.
[ "Disconnects", "all", "connections", "from", "the", "internal", "pools", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L147-L152
train
getsentry/rb
rb/cluster.py
Cluster.get_router
def get_router(self): """Returns the router for the cluster. If the cluster reconfigures the router will be recreated. Usually you do not need to interface with the router yourself as the cluster's routing client does that automatically. This returns an instance of :class:`Bas...
python
def get_router(self): """Returns the router for the cluster. If the cluster reconfigures the router will be recreated. Usually you do not need to interface with the router yourself as the cluster's routing client does that automatically. This returns an instance of :class:`Bas...
[ "def", "get_router", "(", "self", ")", ":", "cached_router", "=", "self", ".", "_router", "ref_age", "=", "self", ".", "_hosts_age", "if", "cached_router", "is", "not", "None", ":", "router", ",", "router_age", "=", "cached_router", "if", "router_age", "==",...
Returns the router for the cluster. If the cluster reconfigures the router will be recreated. Usually you do not need to interface with the router yourself as the cluster's routing client does that automatically. This returns an instance of :class:`BaseRouter`.
[ "Returns", "the", "router", "for", "the", "cluster", ".", "If", "the", "cluster", "reconfigures", "the", "router", "will", "be", "recreated", ".", "Usually", "you", "do", "not", "need", "to", "interface", "with", "the", "router", "yourself", "as", "the", "...
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L154-L173
train
getsentry/rb
rb/cluster.py
Cluster.get_pool_for_host
def get_pool_for_host(self, host_id): """Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool ...
python
def get_pool_for_host(self, host_id): """Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool ...
[ "def", "get_pool_for_host", "(", "self", ",", "host_id", ")", ":", "if", "isinstance", "(", "host_id", ",", "HostInfo", ")", ":", "host_info", "=", "host_id", "host_id", "=", "host_info", ".", "host_id", "else", ":", "host_info", "=", "self", ".", "hosts",...
Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool manually.
[ "Returns", "the", "connection", "pool", "for", "the", "given", "host", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L175-L218
train
getsentry/rb
rb/cluster.py
Cluster.map
def map(self, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a map operation and joining over the result. `max_concurrency` defines how many outstanding parallel queries can exist before an implicit join takes plac...
python
def map(self, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a map operation and joining over the result. `max_concurrency` defines how many outstanding parallel queries can exist before an implicit join takes plac...
[ "def", "map", "(", "self", ",", "timeout", "=", "None", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "True", ")", ":", "return", "self", ".", "get_routing_client", "(", "auto_batch", ")", ".", "map", "(", "timeout", "=", "timeout", ",", "...
Shortcut context manager for getting a routing client, beginning a map operation and joining over the result. `max_concurrency` defines how many outstanding parallel queries can exist before an implicit join takes place. In the context manager the client available is a :class:`...
[ "Shortcut", "context", "manager", "for", "getting", "a", "routing", "client", "beginning", "a", "map", "operation", "and", "joining", "over", "the", "result", ".", "max_concurrency", "defines", "how", "many", "outstanding", "parallel", "queries", "can", "exist", ...
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L252-L269
train
getsentry/rb
rb/cluster.py
Cluster.fanout
def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a fanout operation and joining over the result. In the context manager the client available is a :class:`FanoutClient`. Ex...
python
def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a fanout operation and joining over the result. In the context manager the client available is a :class:`FanoutClient`. Ex...
[ "def", "fanout", "(", "self", ",", "hosts", "=", "None", ",", "timeout", "=", "None", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "True", ")", ":", "return", "self", ".", "get_routing_client", "(", "auto_batch", ")", ".", "fanout", "(", ...
Shortcut context manager for getting a routing client, beginning a fanout operation and joining over the result. In the context manager the client available is a :class:`FanoutClient`. Example usage:: with cluster.fanout(hosts='all') as client: client.flushdb()
[ "Shortcut", "context", "manager", "for", "getting", "a", "routing", "client", "beginning", "a", "fanout", "operation", "and", "joining", "over", "the", "result", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L271-L283
train
getsentry/rb
rb/cluster.py
Cluster.all
def all(self, timeout=None, max_concurrency=64, auto_batch=True): """Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb() """ return self.fanout('all', timeout=timeout, ...
python
def all(self, timeout=None, max_concurrency=64, auto_batch=True): """Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb() """ return self.fanout('all', timeout=timeout, ...
[ "def", "all", "(", "self", ",", "timeout", "=", "None", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "True", ")", ":", "return", "self", ".", "fanout", "(", "'all'", ",", "timeout", "=", "timeout", ",", "max_concurrency", "=", "max_concurre...
Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb()
[ "Fanout", "to", "all", "hosts", ".", "Works", "otherwise", "exactly", "like", ":", "meth", ":", "fanout", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L285-L295
train
getsentry/rb
rb/cluster.py
Cluster.execute_commands
def execute_commands(self, mapping, *args, **kwargs): """Concurrently executes a sequence of commands on a Redis cluster that are associated with a routing key, returning a new mapping where values are a list of results that correspond to the command in the same position. For example:: ...
python
def execute_commands(self, mapping, *args, **kwargs): """Concurrently executes a sequence of commands on a Redis cluster that are associated with a routing key, returning a new mapping where values are a list of results that correspond to the command in the same position. For example:: ...
[ "def", "execute_commands", "(", "self", ",", "mapping", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "is_script_command", "(", "command", ")", ":", "return", "isinstance", "(", "command", "[", "0", "]", ",", "Script", ")", "def", "check_...
Concurrently executes a sequence of commands on a Redis cluster that are associated with a routing key, returning a new mapping where values are a list of results that correspond to the command in the same position. For example:: >>> cluster.execute_commands({ ... 'foo...
[ "Concurrently", "executes", "a", "sequence", "of", "commands", "on", "a", "Redis", "cluster", "that", "are", "associated", "with", "a", "routing", "key", "returning", "a", "new", "mapping", "where", "values", "are", "a", "list", "of", "results", "that", "cor...
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L297-L392
train
getsentry/rb
rb/clients.py
auto_batch_commands
def auto_batch_commands(commands): """Given a pipeline of commands this attempts to merge the commands into more efficient ones if that is possible. """ pending_batch = None for command_name, args, options, promise in commands: # This command cannot be batched, return it as such. if...
python
def auto_batch_commands(commands): """Given a pipeline of commands this attempts to merge the commands into more efficient ones if that is possible. """ pending_batch = None for command_name, args, options, promise in commands: # This command cannot be batched, return it as such. if...
[ "def", "auto_batch_commands", "(", "commands", ")", ":", "pending_batch", "=", "None", "for", "command_name", ",", "args", ",", "options", ",", "promise", "in", "commands", ":", "# This command cannot be batched, return it as such.", "if", "command_name", "not", "in",...
Given a pipeline of commands this attempts to merge the commands into more efficient ones if that is possible.
[ "Given", "a", "pipeline", "of", "commands", "this", "attempts", "to", "merge", "the", "commands", "into", "more", "efficient", "ones", "if", "that", "is", "possible", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L56-L80
train
getsentry/rb
rb/clients.py
CommandBuffer.enqueue_command
def enqueue_command(self, command_name, args, options): """Enqueue a new command into this pipeline.""" assert_open(self) promise = Promise() self.commands.append((command_name, args, options, promise)) return promise
python
def enqueue_command(self, command_name, args, options): """Enqueue a new command into this pipeline.""" assert_open(self) promise = Promise() self.commands.append((command_name, args, options, promise)) return promise
[ "def", "enqueue_command", "(", "self", ",", "command_name", ",", "args", ",", "options", ")", ":", "assert_open", "(", "self", ")", "promise", "=", "Promise", "(", ")", "self", ".", "commands", ".", "append", "(", "(", "command_name", ",", "args", ",", ...
Enqueue a new command into this pipeline.
[ "Enqueue", "a", "new", "command", "into", "this", "pipeline", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L129-L134
train
getsentry/rb
rb/clients.py
CommandBuffer.send_buffer
def send_buffer(self): """Utility function that sends the buffer into the provided socket. The buffer itself will slowly clear out and is modified in place. """ buf = self._send_buf sock = self.connection._sock try: timeout = sock.gettimeout() sock...
python
def send_buffer(self): """Utility function that sends the buffer into the provided socket. The buffer itself will slowly clear out and is modified in place. """ buf = self._send_buf sock = self.connection._sock try: timeout = sock.gettimeout() sock...
[ "def", "send_buffer", "(", "self", ")", ":", "buf", "=", "self", ".", "_send_buf", "sock", "=", "self", ".", "connection", ".", "_sock", "try", ":", "timeout", "=", "sock", ".", "gettimeout", "(", ")", "sock", ".", "setblocking", "(", "False", ")", "...
Utility function that sends the buffer into the provided socket. The buffer itself will slowly clear out and is modified in place.
[ "Utility", "function", "that", "sends", "the", "buffer", "into", "the", "provided", "socket", ".", "The", "buffer", "itself", "will", "slowly", "clear", "out", "and", "is", "modified", "in", "place", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L143-L179
train
getsentry/rb
rb/clients.py
CommandBuffer.send_pending_requests
def send_pending_requests(self): """Sends all pending requests into the connection. The default is to only send pending data that fits into the socket without blocking. This returns `True` if all data was sent or `False` if pending data is left over. """ assert_open(self...
python
def send_pending_requests(self): """Sends all pending requests into the connection. The default is to only send pending data that fits into the socket without blocking. This returns `True` if all data was sent or `False` if pending data is left over. """ assert_open(self...
[ "def", "send_pending_requests", "(", "self", ")", ":", "assert_open", "(", "self", ")", "unsent_commands", "=", "self", ".", "commands", "if", "unsent_commands", ":", "self", ".", "commands", "=", "[", "]", "if", "self", ".", "auto_batch", ":", "unsent_comma...
Sends all pending requests into the connection. The default is to only send pending data that fits into the socket without blocking. This returns `True` if all data was sent or `False` if pending data is left over.
[ "Sends", "all", "pending", "requests", "into", "the", "connection", ".", "The", "default", "is", "to", "only", "send", "pending", "data", "that", "fits", "into", "the", "socket", "without", "blocking", ".", "This", "returns", "True", "if", "all", "data", "...
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L181-L208
train
getsentry/rb
rb/clients.py
CommandBuffer.wait_for_responses
def wait_for_responses(self, client): """Waits for all responses to come back and resolves the eventual results. """ assert_open(self) if self.has_pending_requests: raise RuntimeError('Cannot wait for responses if there are ' 'pending r...
python
def wait_for_responses(self, client): """Waits for all responses to come back and resolves the eventual results. """ assert_open(self) if self.has_pending_requests: raise RuntimeError('Cannot wait for responses if there are ' 'pending r...
[ "def", "wait_for_responses", "(", "self", ",", "client", ")", ":", "assert_open", "(", "self", ")", "if", "self", ".", "has_pending_requests", ":", "raise", "RuntimeError", "(", "'Cannot wait for responses if there are '", "'pending requests outstanding. You need '", "'t...
Waits for all responses to come back and resolves the eventual results.
[ "Waits", "for", "all", "responses", "to", "come", "back", "and", "resolves", "the", "eventual", "results", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L210-L227
train
getsentry/rb
rb/clients.py
MappingClient._get_command_buffer
def _get_command_buffer(self, host_id, command_name): """Returns the command buffer for the given command and arguments.""" buf = self._cb_poll.get(host_id) if buf is not None: return buf if self._max_concurrency is not None: while len(self._cb_poll) >= self._max...
python
def _get_command_buffer(self, host_id, command_name): """Returns the command buffer for the given command and arguments.""" buf = self._cb_poll.get(host_id) if buf is not None: return buf if self._max_concurrency is not None: while len(self._cb_poll) >= self._max...
[ "def", "_get_command_buffer", "(", "self", ",", "host_id", ",", "command_name", ")", ":", "buf", "=", "self", ".", "_cb_poll", ".", "get", "(", "host_id", ")", "if", "buf", "is", "not", "None", ":", "return", "buf", "if", "self", ".", "_max_concurrency",...
Returns the command buffer for the given command and arguments.
[ "Returns", "the", "command", "buffer", "for", "the", "given", "command", "and", "arguments", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L338-L353
train
getsentry/rb
rb/clients.py
MappingClient._release_command_buffer
def _release_command_buffer(self, command_buffer): """This is called by the command buffer when it closes.""" if command_buffer.closed: return self._cb_poll.unregister(command_buffer.host_id) self.connection_pool.release(command_buffer.connection) command_buffer.conn...
python
def _release_command_buffer(self, command_buffer): """This is called by the command buffer when it closes.""" if command_buffer.closed: return self._cb_poll.unregister(command_buffer.host_id) self.connection_pool.release(command_buffer.connection) command_buffer.conn...
[ "def", "_release_command_buffer", "(", "self", ",", "command_buffer", ")", ":", "if", "command_buffer", ".", "closed", ":", "return", "self", ".", "_cb_poll", ".", "unregister", "(", "command_buffer", ".", "host_id", ")", "self", ".", "connection_pool", ".", "...
This is called by the command buffer when it closes.
[ "This", "is", "called", "by", "the", "command", "buffer", "when", "it", "closes", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L355-L362
train
getsentry/rb
rb/clients.py
MappingClient.join
def join(self, timeout=None): """Waits for all outstanding responses to come back or the timeout to be hit. """ remaining = timeout while self._cb_poll and (remaining is None or remaining > 0): now = time.time() rv = self._cb_poll.poll(remaining) ...
python
def join(self, timeout=None): """Waits for all outstanding responses to come back or the timeout to be hit. """ remaining = timeout while self._cb_poll and (remaining is None or remaining > 0): now = time.time() rv = self._cb_poll.poll(remaining) ...
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "remaining", "=", "timeout", "while", "self", ".", "_cb_poll", "and", "(", "remaining", "is", "None", "or", "remaining", ">", "0", ")", ":", "now", "=", "time", ".", "time", "(", ")...
Waits for all outstanding responses to come back or the timeout to be hit.
[ "Waits", "for", "all", "outstanding", "responses", "to", "come", "back", "or", "the", "timeout", "to", "be", "hit", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L384-L418
train
getsentry/rb
rb/clients.py
FanoutClient.target
def target(self, hosts): """Temporarily retarget the client for one call. This is useful when having to deal with a subset of hosts for one call. """ if self.__is_retargeted: raise TypeError('Cannot use target more than once.') rv = FanoutClient(hosts, connection_poo...
python
def target(self, hosts): """Temporarily retarget the client for one call. This is useful when having to deal with a subset of hosts for one call. """ if self.__is_retargeted: raise TypeError('Cannot use target more than once.') rv = FanoutClient(hosts, connection_poo...
[ "def", "target", "(", "self", ",", "hosts", ")", ":", "if", "self", ".", "__is_retargeted", ":", "raise", "TypeError", "(", "'Cannot use target more than once.'", ")", "rv", "=", "FanoutClient", "(", "hosts", ",", "connection_pool", "=", "self", ".", "connecti...
Temporarily retarget the client for one call. This is useful when having to deal with a subset of hosts for one call.
[ "Temporarily", "retarget", "the", "client", "for", "one", "call", ".", "This", "is", "useful", "when", "having", "to", "deal", "with", "a", "subset", "of", "hosts", "for", "one", "call", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L444-L454
train
getsentry/rb
rb/clients.py
FanoutClient.target_key
def target_key(self, key): """Temporarily retarget the client for one call to route specifically to the one host that the given key routes to. In that case the result on the promise is just the one host's value instead of a dictionary. .. versionadded:: 1.3 """ ...
python
def target_key(self, key): """Temporarily retarget the client for one call to route specifically to the one host that the given key routes to. In that case the result on the promise is just the one host's value instead of a dictionary. .. versionadded:: 1.3 """ ...
[ "def", "target_key", "(", "self", ",", "key", ")", ":", "router", "=", "self", ".", "connection_pool", ".", "cluster", ".", "get_router", "(", ")", "host_id", "=", "router", ".", "get_host_for_key", "(", "key", ")", "rv", "=", "self", ".", "target", "(...
Temporarily retarget the client for one call to route specifically to the one host that the given key routes to. In that case the result on the promise is just the one host's value instead of a dictionary. .. versionadded:: 1.3
[ "Temporarily", "retarget", "the", "client", "for", "one", "call", "to", "route", "specifically", "to", "the", "one", "host", "that", "the", "given", "key", "routes", "to", ".", "In", "that", "case", "the", "result", "on", "the", "promise", "is", "just", ...
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L456-L468
train
getsentry/rb
rb/clients.py
RoutingClient.get_mapping_client
def get_mapping_client(self, max_concurrency=64, auto_batch=None): """Returns a thread unsafe mapping client. This client works similar to a redis pipeline and returns eventual result objects. It needs to be joined on to work properly. Instead of using this directly you shold use the :...
python
def get_mapping_client(self, max_concurrency=64, auto_batch=None): """Returns a thread unsafe mapping client. This client works similar to a redis pipeline and returns eventual result objects. It needs to be joined on to work properly. Instead of using this directly you shold use the :...
[ "def", "get_mapping_client", "(", "self", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "None", ")", ":", "if", "auto_batch", "is", "None", ":", "auto_batch", "=", "self", ".", "auto_batch", "return", "MappingClient", "(", "connection_pool", "=", ...
Returns a thread unsafe mapping client. This client works similar to a redis pipeline and returns eventual result objects. It needs to be joined on to work properly. Instead of using this directly you shold use the :meth:`map` context manager which automatically joins. Returns...
[ "Returns", "a", "thread", "unsafe", "mapping", "client", ".", "This", "client", "works", "similar", "to", "a", "redis", "pipeline", "and", "returns", "eventual", "result", "objects", ".", "It", "needs", "to", "be", "joined", "on", "to", "work", "properly", ...
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L522-L535
train
getsentry/rb
rb/clients.py
RoutingClient.get_fanout_client
def get_fanout_client(self, hosts, max_concurrency=64, auto_batch=None): """Returns a thread unsafe fanout client. Returns an instance of :class:`FanoutClient`. """ if auto_batch is None: auto_batch = self.auto_batch return FanoutClient(host...
python
def get_fanout_client(self, hosts, max_concurrency=64, auto_batch=None): """Returns a thread unsafe fanout client. Returns an instance of :class:`FanoutClient`. """ if auto_batch is None: auto_batch = self.auto_batch return FanoutClient(host...
[ "def", "get_fanout_client", "(", "self", ",", "hosts", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "None", ")", ":", "if", "auto_batch", "is", "None", ":", "auto_batch", "=", "self", ".", "auto_batch", "return", "FanoutClient", "(", "hosts", ...
Returns a thread unsafe fanout client. Returns an instance of :class:`FanoutClient`.
[ "Returns", "a", "thread", "unsafe", "fanout", "client", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L537-L547
train
getsentry/rb
rb/clients.py
RoutingClient.map
def map(self, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation. This runs multiple queries in parallel and then joins in the end to collect all results. In the context manager the client available is a :class:`MappingClient`. ...
python
def map(self, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation. This runs multiple queries in parallel and then joins in the end to collect all results. In the context manager the client available is a :class:`MappingClient`. ...
[ "def", "map", "(", "self", ",", "timeout", "=", "None", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "None", ")", ":", "return", "MapManager", "(", "self", ".", "get_mapping_client", "(", "max_concurrency", ",", "auto_batch", ")", ",", "timeo...
Returns a context manager for a map operation. This runs multiple queries in parallel and then joins in the end to collect all results. In the context manager the client available is a :class:`MappingClient`. Example usage:: results = {} with cluster.map() as ...
[ "Returns", "a", "context", "manager", "for", "a", "map", "operation", ".", "This", "runs", "multiple", "queries", "in", "parallel", "and", "then", "joins", "in", "the", "end", "to", "collect", "all", "results", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L549-L565
train
getsentry/rb
rb/clients.py
RoutingClient.fanout
def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation that fans out to manually specified hosts instead of using the routing system. This can for instance be used to empty the database on all hosts. The ...
python
def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation that fans out to manually specified hosts instead of using the routing system. This can for instance be used to empty the database on all hosts. The ...
[ "def", "fanout", "(", "self", ",", "hosts", "=", "None", ",", "timeout", "=", "None", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "None", ")", ":", "return", "MapManager", "(", "self", ".", "get_fanout_client", "(", "hosts", ",", "max_conc...
Returns a context manager for a map operation that fans out to manually specified hosts instead of using the routing system. This can for instance be used to empty the database on all hosts. The context manager returns a :class:`FanoutClient`. Example usage:: with cluster.fanout(...
[ "Returns", "a", "context", "manager", "for", "a", "map", "operation", "that", "fans", "out", "to", "manually", "specified", "hosts", "instead", "of", "using", "the", "routing", "system", ".", "This", "can", "for", "instance", "be", "used", "to", "empty", "...
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L567-L591
train
getsentry/rb
rb/promise.py
Promise.resolved
def resolved(value): """Creates a promise object resolved with a certain value.""" p = Promise() p._state = 'resolved' p.value = value return p
python
def resolved(value): """Creates a promise object resolved with a certain value.""" p = Promise() p._state = 'resolved' p.value = value return p
[ "def", "resolved", "(", "value", ")", ":", "p", "=", "Promise", "(", ")", "p", ".", "_state", "=", "'resolved'", "p", ".", "value", "=", "value", "return", "p" ]
Creates a promise object resolved with a certain value.
[ "Creates", "a", "promise", "object", "resolved", "with", "a", "certain", "value", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/promise.py#L22-L27
train
getsentry/rb
rb/promise.py
Promise.rejected
def rejected(reason): """Creates a promise object rejected with a certain value.""" p = Promise() p._state = 'rejected' p.reason = reason return p
python
def rejected(reason): """Creates a promise object rejected with a certain value.""" p = Promise() p._state = 'rejected' p.reason = reason return p
[ "def", "rejected", "(", "reason", ")", ":", "p", "=", "Promise", "(", ")", "p", ".", "_state", "=", "'rejected'", "p", ".", "reason", "=", "reason", "return", "p" ]
Creates a promise object rejected with a certain value.
[ "Creates", "a", "promise", "object", "rejected", "with", "a", "certain", "value", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/promise.py#L30-L35
train
getsentry/rb
rb/promise.py
Promise.resolve
def resolve(self, value): """Resolves the promise with the given value.""" if self is value: raise TypeError('Cannot resolve promise with itself.') if isinstance(value, Promise): value.done(self.resolve, self.reject) return if self._state != 'pending...
python
def resolve(self, value): """Resolves the promise with the given value.""" if self is value: raise TypeError('Cannot resolve promise with itself.') if isinstance(value, Promise): value.done(self.resolve, self.reject) return if self._state != 'pending...
[ "def", "resolve", "(", "self", ",", "value", ")", ":", "if", "self", "is", "value", ":", "raise", "TypeError", "(", "'Cannot resolve promise with itself.'", ")", "if", "isinstance", "(", "value", ",", "Promise", ")", ":", "value", ".", "done", "(", "self",...
Resolves the promise with the given value.
[ "Resolves", "the", "promise", "with", "the", "given", "value", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/promise.py#L46-L63
train
getsentry/rb
rb/promise.py
Promise.reject
def reject(self, reason): """Rejects the promise with the given reason.""" if self._state != 'pending': raise RuntimeError('Promise is no longer pending.') self.reason = reason self._state = 'rejected' errbacks = self._errbacks self._errbacks = None f...
python
def reject(self, reason): """Rejects the promise with the given reason.""" if self._state != 'pending': raise RuntimeError('Promise is no longer pending.') self.reason = reason self._state = 'rejected' errbacks = self._errbacks self._errbacks = None f...
[ "def", "reject", "(", "self", ",", "reason", ")", ":", "if", "self", ".", "_state", "!=", "'pending'", ":", "raise", "RuntimeError", "(", "'Promise is no longer pending.'", ")", "self", ".", "reason", "=", "reason", "self", ".", "_state", "=", "'rejected'", ...
Rejects the promise with the given reason.
[ "Rejects", "the", "promise", "with", "the", "given", "reason", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/promise.py#L65-L75
train
getsentry/rb
rb/promise.py
Promise.done
def done(self, on_success=None, on_failure=None): """Attaches some callbacks to the promise and returns the promise.""" if on_success is not None: if self._state == 'pending': self._callbacks.append(on_success) elif self._state == 'resolved': on_su...
python
def done(self, on_success=None, on_failure=None): """Attaches some callbacks to the promise and returns the promise.""" if on_success is not None: if self._state == 'pending': self._callbacks.append(on_success) elif self._state == 'resolved': on_su...
[ "def", "done", "(", "self", ",", "on_success", "=", "None", ",", "on_failure", "=", "None", ")", ":", "if", "on_success", "is", "not", "None", ":", "if", "self", ".", "_state", "==", "'pending'", ":", "self", ".", "_callbacks", ".", "append", "(", "o...
Attaches some callbacks to the promise and returns the promise.
[ "Attaches", "some", "callbacks", "to", "the", "promise", "and", "returns", "the", "promise", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/promise.py#L92-L104
train
getsentry/rb
rb/promise.py
Promise.then
def then(self, success=None, failure=None): """A utility method to add success and/or failure callback to the promise which will also return another promise in the process. """ rv = Promise() def on_success(v): try: rv.resolve(success(v)) ...
python
def then(self, success=None, failure=None): """A utility method to add success and/or failure callback to the promise which will also return another promise in the process. """ rv = Promise() def on_success(v): try: rv.resolve(success(v)) ...
[ "def", "then", "(", "self", ",", "success", "=", "None", ",", "failure", "=", "None", ")", ":", "rv", "=", "Promise", "(", ")", "def", "on_success", "(", "v", ")", ":", "try", ":", "rv", ".", "resolve", "(", "success", "(", "v", ")", ")", "exce...
A utility method to add success and/or failure callback to the promise which will also return another promise in the process.
[ "A", "utility", "method", "to", "add", "success", "and", "/", "or", "failure", "callback", "to", "the", "promise", "which", "will", "also", "return", "another", "promise", "in", "the", "process", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/promise.py#L106-L125
train
getsentry/rb
rb/router.py
BaseRouter.get_key
def get_key(self, command, args): """Returns the key a command operates on.""" spec = COMMANDS.get(command.upper()) if spec is None: raise UnroutableCommand('The command "%r" is unknown to the ' 'router and cannot be handled as a ' ...
python
def get_key(self, command, args): """Returns the key a command operates on.""" spec = COMMANDS.get(command.upper()) if spec is None: raise UnroutableCommand('The command "%r" is unknown to the ' 'router and cannot be handled as a ' ...
[ "def", "get_key", "(", "self", ",", "command", ",", "args", ")", ":", "spec", "=", "COMMANDS", ".", "get", "(", "command", ".", "upper", "(", ")", ")", "if", "spec", "is", "None", ":", "raise", "UnroutableCommand", "(", "'The command \"%r\" is unknown to t...
Returns the key a command operates on.
[ "Returns", "the", "key", "a", "command", "operates", "on", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/router.py#L60-L85
train
getsentry/rb
rb/router.py
BaseRouter.get_host_for_command
def get_host_for_command(self, command, args): """Returns the host this command should be executed against.""" return self.get_host_for_key(self.get_key(command, args))
python
def get_host_for_command(self, command, args): """Returns the host this command should be executed against.""" return self.get_host_for_key(self.get_key(command, args))
[ "def", "get_host_for_command", "(", "self", ",", "command", ",", "args", ")", ":", "return", "self", ".", "get_host_for_key", "(", "self", ".", "get_key", "(", "command", ",", "args", ")", ")" ]
Returns the host this command should be executed against.
[ "Returns", "the", "host", "this", "command", "should", "be", "executed", "against", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/router.py#L87-L89
train
getsentry/rb
rb/ketama.py
Ketama._rebuild_circle
def _rebuild_circle(self): """Updates the hash ring.""" self._hashring = {} self._sorted_keys = [] total_weight = 0 for node in self._nodes: total_weight += self._weights.get(node, 1) for node in self._nodes: weight = self._weights.get(node, 1) ...
python
def _rebuild_circle(self): """Updates the hash ring.""" self._hashring = {} self._sorted_keys = [] total_weight = 0 for node in self._nodes: total_weight += self._weights.get(node, 1) for node in self._nodes: weight = self._weights.get(node, 1) ...
[ "def", "_rebuild_circle", "(", "self", ")", ":", "self", ".", "_hashring", "=", "{", "}", "self", ".", "_sorted_keys", "=", "[", "]", "total_weight", "=", "0", "for", "node", "in", "self", ".", "_nodes", ":", "total_weight", "+=", "self", ".", "_weight...
Updates the hash ring.
[ "Updates", "the", "hash", "ring", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/ketama.py#L21-L43
train
getsentry/rb
rb/ketama.py
Ketama._get_node_pos
def _get_node_pos(self, key): """Return node position(integer) for a given key or None.""" if not self._hashring: return k = md5_bytes(key) key = (k[3] << 24) | (k[2] << 16) | (k[1] << 8) | k[0] nodes = self._sorted_keys pos = bisect(nodes, key) if ...
python
def _get_node_pos(self, key): """Return node position(integer) for a given key or None.""" if not self._hashring: return k = md5_bytes(key) key = (k[3] << 24) | (k[2] << 16) | (k[1] << 8) | k[0] nodes = self._sorted_keys pos = bisect(nodes, key) if ...
[ "def", "_get_node_pos", "(", "self", ",", "key", ")", ":", "if", "not", "self", ".", "_hashring", ":", "return", "k", "=", "md5_bytes", "(", "key", ")", "key", "=", "(", "k", "[", "3", "]", "<<", "24", ")", "|", "(", "k", "[", "2", "]", "<<",...
Return node position(integer) for a given key or None.
[ "Return", "node", "position", "(", "integer", ")", "for", "a", "given", "key", "or", "None", "." ]
569d1d13311f6c04bae537fc17e75da430e4ec45
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/ketama.py#L45-L58
train