text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self, **variables): """Formats the locator with specified parameters"""
return Locator(self.by, self.locator.format(**variables), self.description)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_requestdriver_cookies_into_webdriver(requestdriver, webdriverwrapper, handle_sub_domain=True): """Adds all cookies in the RequestDriver session to Webdr...
driver_hostname = urlparse(webdriverwrapper.current_url()).netloc for cookie in requestdriver.session.cookies: # Check if there will be a cross-domain violation and handle if necessary cookiedomain = cookie.domain if handle_sub_domain: if is_subdomain(cookiedomain, driver_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_webdriver_cookies_into_requestdriver(requestdriver, webdriverwrapper): """Adds all cookies in the Webdriver session to requestdriver @type requestdriver...
for cookie in webdriverwrapper.get_cookies(): # Wedbriver uses "expiry"; requests uses "expires", adjust for this expires = cookie.pop('expiry', {'expiry': None}) cookie.update({'expires': expires}) requestdriver.session.cookies.set(**cookie)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_firefox_binary(): """Gets the firefox binary @rtype: FirefoxBinary """
browser_config = BrowserConfig() constants_config = ConstantsConfig() log_dir = os.path.join(constants_config.get('logs_dir'), 'firefox') create_directory(log_dir) log_path = os.path.join(log_dir, '{}_{}.log'.format(datetime.datetime.now().isoformat('_'), words.random_word())) log_file = open(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _log_fail_callback(driver, *args, **kwargs): """Raises an assertion error if the page has severe console errors @param driver: ShapewaysDriver @return: None ...
try: logs = driver.get_browser_log(levels=[BROWSER_LOG_LEVEL_SEVERE]) failure_message = 'There were severe console errors on this page: {}'.format(logs) failure_message = failure_message.replace('{', '{{').replace('}', '}}') # Escape braces for error message driver.assertion.asser...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone_and_update(self, **kwargs): """Clones the object and updates the clone with the args @param kwargs: Keyword arguments to set @return: The cloned copy w...
cloned = self.clone() cloned.update(**kwargs) return cloned
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def message(self): """ Render the body of the message to a string. """
template_name = self.template_name() if \ callable(self.template_name) \ else self.template_name return loader.render_to_string( template_name, self.get_context(), request=self.request )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subject(self): """ Render the subject of the message to a string. """
template_name = self.subject_template_name() if \ callable(self.subject_template_name) \ else self.subject_template_name subject = loader.render_to_string( template_name, self.get_context(), request=self.request ) return ''.join(subject.splitlines())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context(self): """ Return the context used to render the templates for the email subject and body. By default, this context includes: * All of the valida...
if not self.is_valid(): raise ValueError( "Cannot generate Context from invalid contact form" ) return dict(self.cleaned_data, site=get_current_site(self.request))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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") shopify.Session.setup(api_key=settings.SHOPIFY_APP_API_KEY, secret=settings.SHOPIFY_APP_API_SECRET)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) # Never want to be able to log on externally. # Authentication will be taken care of by Shopify OAuth. user.set_unusable_passwor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 dicti...
# Parse the given URL into parts. url_parts = urllib.parse.urlparse(url) # Parse existing parameters and add new parameters. qs_args = urllib.parse.parse_qs(url_parts[4]) qs_args.update(query_parameters) # Sort parameters to ensure consistent order. sorted_qs_args = OrderedDict() for ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'] = channel_name self.logger.info("Connection: Sending event - %s" % event) try: self.socket.send(json.dumps(event)) except Exception as e: self.logger.error("Failed ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 even...
if self.connection: if event_name.startswith("client-"): if self.name.startswith("private-") or self.name.startswith("presence-"): self.connection.send_event(event_name, data, channel_name=self.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 t...
data = {'channel': channel_name} if auth is None: if channel_name.startswith('presence-'): data['auth'] = self._generate_presence_token(channel_name) data['channel_data'] = json.dumps(self.user_data) elif channel_name.startswith('private-'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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': channel_name, } ) del self.channels[channel_name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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....
if channel_name in self.channels: self.channels[channel_name]._handle_event(event_name, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 gene...
subject = "{}:{}".format(self.connection.socket_id, channel_name) h = hmac.new(self.secret_as_bytes, subject.encode('utf-8'), hashlib.sha256) auth_key = "{}:{}".format(self.key, h.hexdigest()) return auth_key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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:...
subject = "{}:{}:{}".format(self.connection.socket_id, channel_name, json.dumps(self.user_data)) h = hmac.new(self.secret_as_bytes, subject.encode('utf-8'), hashlib.sha256) auth_key = "{}:{}".format(self.key, h.hexdigest()) return auth_key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(' | ')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ', '')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def download(self): ''' Downloads HTML from url. ''' self.page = requests.get(self.url) self.tree = html.fromstring(self.page.text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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] = ['']...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def register(cache): ''' Registers a cache. ''' global caches name = cache().name if not caches.has_key(name): caches[name] = cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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,)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if host_id is None: raise RuntimeError('Host ID is required') elif not isinstance(host_id, (int, long)): raise ValueError('The host ID has to be an integer') host_id = int(host_id) with self._lock: if host_id in self.hosts: raise TypeE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: pool.disconnect() self._hosts_age += 1 return rv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
cached_router = self._router ref_age = self._hosts_age if cached_router is not None: router, router_age = cached_router if router_age == ref_age: return router with self._lock: router = self.router_cls(self, **(self.router_options or...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 d...
if isinstance(host_id, HostInfo): host_info = host_id host_id = host_info.host_id else: host_info = self.hosts.get(host_id) if host_info is None: raise LookupError('Host %r does not exist' % (host_id,)) rv = self._pools.get(host_i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
return self.get_routing_client(auto_batch).map( timeout=timeout, max_concurrency=max_concurrency)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a fanout ope...
return self.get_routing_client(auto_batch).fanout( hosts=hosts, timeout=timeout, max_concurrency=max_concurrency)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 command_name not in AUTO_BATCH_COMMANDS: if pending_batch: yield merge_batch(*pending_batch) pending_batch = None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.setblocking(False) try: for idx, item in enumerate(buf): sent = 0 while 1: try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 bl...
assert_open(self) unsent_commands = self.commands if unsent_commands: self.commands = [] if self.auto_batch: unsent_commands = auto_batch_commands(unsent_commands) buf = [] for command_name, args, options, promise in unsent_comm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 requests outstanding. You need ' 'to wait for pending requests to be sent ' 'f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_concurrency: self.join(timeout=1.0) def connect(): return self.connection_pool.get_connection...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.connection = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) if remaining is not None: remaining -= (time.time() - now) for command_buffer, event in rv: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_pool=self.connection_pool, max_concurrency=self._max_concurrency) rv._cb_poll = self._cb_poll rv.__is_retargeted = True return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 r...
router = self.connection_pool.cluster.get_router() host_id = router.get_host_for_key(key) rv = self.target([host_id]) rv.__resolve_singular_result = True return rv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(hosts, connection_pool=self.connection_pool, max_concurrency=max_concurrency, auto_batch=auto_batch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 th...
return MapManager(self.get_mapping_client(max_concurrency, auto_batch), timeout=timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolved(value): """Creates a promise object resolved with a certain value."""
p = Promise() p._state = 'resolved' p.value = value return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rejected(reason): """Creates a promise object rejected with a certain value."""
p = Promise() p._state = 'rejected' p.reason = reason return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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': raise RuntimeError('Promise is no longer pending.') self.v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 for errback in errbacks: errback(reason)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_success(self.value) if on_failure is not None: if self._state == 'pending': self._errbacks.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ' 'result.' % command) if 'movablekeys' in spec['flags']: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) ks = math.floor((40 * len(self._nodes) * weight) / t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_node(self, key): """Return node for a given key. Else return None."""
pos = self._get_node_pos(key) if pos is None: return None return self._hashring[self._sorted_keys[pos]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_error(result, func, cargs): "Error checking proper value returns" if result != 0: msg = 'Error in "%s": %s' % (func.__name__, get_errors(result) ) raise RTreeError(msg) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ddtodms(self, dd): """Take in dd string and convert to dms"""
negative = dd < 0 dd = abs(dd) minutes,seconds = divmod(dd*3600,60) degrees,minutes = divmod(minutes,60) if negative: if degrees > 0: degrees = -degrees elif minutes > 0: minutes = -minutes else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dmstodd(self, dms): """ convert dms to dd"""
size = len(dms) letters = 'WENS' is_annotated = False try: float(dms) except ValueError: for letter in letters: if letter in dms.upper(): is_annotated = True break if not is_annotated: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_fobj(fname, mode='w+'): """Obtain a proper file object. Parameters fname : string, file object, file descriptor If a string or file descriptor, then we c...
if is_string_like(fname): fobj = open(fname, mode) close = True elif hasattr(fname, 'write'): # fname is a file-like object, perhaps a StringIO (for example) fobj = fname close = False else: # assume it is a file descriptor fobj = os.fdopen(fname, mod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_from_dot_file(path): """Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be...
fd = open(path, 'rb') data = fd.read() fd.close() return graph_from_dot_data(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_from_edges(edge_list, node_prefix='', directed=False): """Creates a basic graph out of an edge list. The edge list has to be a list of tuples represent...
if edge_list is None: edge_list = [] graph_type = "digraph" if directed else "graph" with_prefix = functools.partial("{0}{1}".format, node_prefix) graph = Dot(graph_type=graph_type) for src, dst in edge_list: src = with_prefix(src) dst = with_prefix(dst) graph.ad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False): """Creates a basic graph out of an adjacency matrix. The matrix has to be a list of rows...
node_orig = 1 if directed: graph = Dot(graph_type='digraph') else: graph = Dot(graph_type='graph') for row in matrix: if not directed: skip = matrix.index(row) r = row[skip:] else: skip = 0 r = row node_dest = sk...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_from_incidence_matrix(matrix, node_prefix='', directed=False): """Creates a basic graph out of an incidence matrix. The matrix has to be a list of rows...
if directed: graph = Dot(graph_type='digraph') else: graph = Dot(graph_type='graph') for row in matrix: nodes = [] c = 1 for node in row: if node: nodes.append(c * node) c += 1 nodes.sort() if len(nodes) ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __find_executables(path): """Used by find_graphviz path - single directory as a string If any of the executables are found, it will return a dictionary conta...
success = False progs = { "dot": "", "twopi": "", "neato": "", "circo": "", "fdp": "", "sfdp": "", } was_quoted = False path = path.strip() if path.startswith('"') and path.endswith('"'): path = path[1:-1] was_quoted = True ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_graphviz(): """Locate Graphviz's executables in the system. Tries three methods: First: Windows Registry (Windows only) This requires Mark Hammond's pyw...
# Method 1 (Windows only) if os.sys.platform == 'win32': HKEY_LOCAL_MACHINE = 0x80000002 KEY_QUERY_VALUE = 0x0001 RegOpenKeyEx = None RegQueryValueEx = None RegCloseKey = None try: import win32api RegOpenKeyEx = win32api.RegOpenKeyEx ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_node_list(self): """Get the list of Node instances. This method returns the list of Node instances composing the graph. """
node_objs = list() for obj_dict_list in self.obj_dict['nodes'].values(): node_objs.extend([ Node(obj_dict=obj_d) for obj_d in obj_dict_list]) return node_objs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_edge_list(self): """Get the list of Edge instances. This method returns the list of Edge instances composing the graph. """
edge_objs = list() for obj_dict_list in self.obj_dict['edges'].values(): edge_objs.extend([ Edge(obj_dict=obj_d) for obj_d in obj_dict_list]) return edge_objs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_string(self): """Returns a string representation of the graph in dot language. It will return the graph and all its subelements in string from. """
graph = list() if self.obj_dict.get('strict', None) is not None: if self == self.get_parent_graph() and self.obj_dict['strict']: graph.append('strict ') if self.obj_dict['name'] == '': if ('show_keyword' in self.obj_dict and self.ob...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, path, prog=None, format='raw'): """Write graph to file in selected format. Given a filename 'path' it will open/create and truncate such file and...
if prog is None: prog = self.prog fobj, close = get_fobj(path, 'w+b') try: if format == 'raw': data = self.to_string() if isinstance(data, basestring): if not isinstance(data, unicode): try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_crumbs(self): """ Get crumbs for navigation links. Returns: tuple: concatenated list of crumbs using these crumbs and the crumbs of the parent classes th...
crumbs = [] for cls in reversed(type(self).__mro__[1:]): crumbs.extend(getattr(cls, 'crumbs', ())) crumbs.extend(list(self.crumbs)) return tuple(crumbs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, request, *args, **kwargs): """ Django view get function. Add items of extra_context, crumbs and grid to context. Args: request (): Django's reques...
context = self.get_context_data(**kwargs) context.update(self.extra_context) context['crumbs'] = self.get_crumbs() context['title'] = self.title context['suit'] = 'suit' in settings.INSTALLED_APPS if context.get('dashboard_grid', None) is None and self.grid: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def realtime(widget, url_name=None, url_regex=None, time_interval=None): """ Return a widget as real-time. Args: widget (Widget): the widget to register and ret...
if not hasattr(widget, 'get_updated_content'): raise AttributeError('Widget %s must implement get_updated_content ' 'method.' % widget) elif not callable(widget.get_updated_content): raise ValueError('get_updated_content in widget %s is not callable' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_realtime_urls(admin_view_func=lambda x: x): """ Get the URL for real-time widgets. Args: admin_view_func (callable): an admin_view method from an AdminS...
from .widgets import REALTIME_WIDGETS return [url(w.url_regex, admin_view_func(w.as_view()), name=w.url_name) for w in REALTIME_WIDGETS]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_time(self): """ Make sure our Honeypot time is consistent, and not too far off from the actual time. """
poll = self.config['timecheck']['poll'] ntp_poll = self.config['timecheck']['ntp_pool'] while True: clnt = ntplib.NTPClient() try: response = clnt.request(ntp_poll, version=3) diff = response.offset if abs(diff) >= 15: ...