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 run(self): """Start the game loop"""
global world self.__is_running = True while(self.__is_running): #Our game loop #Catch our events self.__handle_events() #Update our clock self.__clock.tick(self.preferred_fps) elapsed_milliseconds = self.__clock.get_time() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request_object(self): """Grab an object from the pool. If the pool is empty, a new object will be generated and returned."""
obj_to_return = None if self.queue.count > 0: obj_to_return = self.__dequeue() else: #The queue is empty, generate a new item. self.__init_object() object_to_return = self.__dequeue() self.active_objects += 1 return obj_to_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 apply_texture(self, image): """Place a preexisting texture as the sprite's texture."""
self.image = image.convert_alpha() self.untransformed_image = self.image.copy() ## self.rect.x = 0 ## self.rect.y = 0 ## self.rect.width = self.image.get_width() ## self.rect.height = self.image.get_height() self.source.x = 0 self.source.y = 0 self.so...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __resize_surface_extents(self): """Handles surface cleanup once a scale or rotation operation has been performed."""
#Set the new location of the origin, as the surface size may increase with rotation self.__origin.X = self.image.get_width() * self.__untransformed_nor_origin.X self.__origin.Y = self.image.get_height() * self.__untransformed_nor_origin.Y ## #Update the size of the rectangle ## s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __execute_scale(self, surface, size_to_scale_from): """Execute the scaling operation"""
x = size_to_scale_from[0] * self.__scale[0] y = size_to_scale_from[1] * self.__scale[1] scaled_value = (int(x), int(y)) ## #Find out what scaling technique we should use. ## if self.image.get_bitsize >= 24: ## #We have sufficient bit depth to run smooth scale ## ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_colliding(self, other): """Check to see if two circles are colliding."""
if isinstance(other, BoundingCircle): #Calculate the distance between two circles. distance = Vector2.distance(self.coords, other.coords) #Check to see if the sum of thier radi are greater than or equal to the distance. radi_sum = self.radius + other.radius ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_all_collisions(collision_object): """ Check for and return the full list of objects colliding with collision_object """
global collidable_objects colliding = [] for obj in collidable_objects: #Make sure we don't check ourself against ourself. if obj is not collision_object: if collision_object.is_colliding(obj): #A collision has been detected. Add the o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_brute(self): """ A nightmare if looked at by a performance standpoint, but it gets the job done, at least for now. Checks everything against everything a...
global collidable_objects if self.collision_depth == self.SHALLOW_DEPTH: for obj in collidable_objects: collision = self.query_collision(obj) if collision is not None: #Execute the reactions for both of the colliding objects. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_keyboard_focus(self, move_up, move_down, select): """ Set the keyboard as the object that controls the menu. move_up is from the pygame.KEYS enum that de...
self.input_focus = StateTypes.KEYBOARD self.move_up_button = move_up self.move_down_button = move_down self.select_button = select
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __update_mouse(self, milliseconds): """ Use the mouse to control selection of the buttons. """
for button in self.gui_buttons: was_hovering = button.is_mouse_hovering button.update(milliseconds) #Provides capibilities for the mouse to select a button if the mouse is the focus of input. if was_hovering == False and button.is_mouse_hovering: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def warp_object(self, tileMapObj): """Warp the tile map object from one warp to another."""
print "Collision" if tileMapObj.can_warp: #Check to see if we need to load a different tile map if self.map_association != self.exitWarp.map_association: #Load the new tile map. TileMapManager.load(exitWarp.map_association) tileMapObj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_collisions(self): """Parses the collision map and sets the tile states as necessary."""
fs = open(self.collisionmap_path, "r") self.collisionmap = fs.readlines() fs.close() x_index = 0 y_index = 0 for line in self.collisionmap: if line[0] is "#": continue for char in line: if char is "": ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self, milliseconds, surface): """Draw out the tilemap."""
self.drawn_rects = [] cam = Ragnarok.get_world().Camera cX, cY, cXMax, cYMax = cam.get_cam_bounds() #Draw out only the tiles visible to the camera. start_pos = self.pixels_to_tiles( (cX, cY) ) start_pos -= Vector2(1, 1) end_pos = self.pixels_to_tiles( (cXMax, cY...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self, milliseconds): """Draws all of the objects in our world."""
cam = Ragnarok.get_world().Camera camPos = cam.get_world_pos() self.__sort_draw() self.clear_backbuffer() for obj in self.__draw_objects: #Check to see if the object is visible to the camera before doing anything to it. if obj.is_static or obj.is_visible_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark_time(times, msg=None): """ Time measurement utility. Measures times of execution between subsequent calls using time.clock(). The time is printed if the...
tt = time.clock() times.append(tt) if (msg is not None) and (len(times) > 1): print msg, times[-1] - times[-2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_file(filename, package_name=None): """ Import a file as a module. The module is explicitly reloaded to prevent undesirable interactions. """
path = os.path.dirname(filename) if not path in sys.path: sys.path.append( path ) remove_path = True else: remove_path = False name = os.path.splitext(os.path.basename(filename))[0] if name in sys.modules: force_reload = True else: force_reload = Fals...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause( msg = None ): """ Prints the line number and waits for a keypress. If you press: This is useful for debugging. """
f = sys._getframe(1) ff = f.f_code if (msg): print '%s, %d: %s(), %d: %s' % (ff.co_filename, ff.co_firstlineno, ff.co_name, f.f_lineno, msg) else: print '%s, %d: %s(), %d' % (ff.co_filename, ff.co_firstlineno, 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 update(self, other, **kwargs): """ A dict-like update for Struct attributes. """
if other is None: return if not isinstance(other, dict): other = other.to_dict() self.__dict__.update(other, **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 fetch_social_friend_ids(self, social_auth_user): """ fetches the user's social friends from its provider user is an instance of UserSocialAuth returns collec...
# Type check self.assert_user_is_social_auth_user(social_auth_user) # Get friend finder backend friends_provider = SocialFriendsFinderBackendFactory.get_backend(social_auth_user.provider) # Get friend ids friend_ids = friends_provider.fetch_friend_ids(social_auth_user...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def existing_social_friends(self, user_social_auth=None, friend_ids=None): """ fetches and matches social friends if friend_ids is None, then fetches them from s...
# Type check self.assert_user_is_social_auth_user(user_social_auth) if not friend_ids: friend_ids = self.fetch_social_friend_ids(user_social_auth) # Convert comma sepearated string to the list if isinstance(friend_ids, basestring): friend_ids = eval(fri...
<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_object(self, queryset=None): """Return object with episode number attached to episode."""
if settings.PODCAST_SINGULAR: show = get_object_or_404(Show, id=settings.PODCAST_ID) else: show = get_object_or_404(Show, slug=self.kwargs['show_slug']) obj = get_object_or_404(Episode, show=show, slug=self.kwargs['slug']) index = Episode.objects.is_public_or_sec...
<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_backend(self, backend_name): """ returns the given backend instance """
if backend_name == 'twitter': from social_friends_finder.backends.twitter_backend import TwitterFriendsProvider friends_provider = TwitterFriendsProvider() elif backend_name == 'facebook': from social_friends_finder.backends.facebook_backend import FacebookFriendsPro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_friends(self, user): """ fethces friends from VKontakte using the access_token fethched by django-social-auth. Note - user isn't a user - it's a UserSo...
if USING_ALLAUTH: raise NotImplementedError("VKontakte support is not implemented for django-allauth") #social_app = SocialApp.objects.get_current('vkontakte') #oauth_token = SocialToken.objects.get(account=user, app=social_app).token else: social_auth_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addQuickElement(self, name, contents=None, attrs=None, escape=True, cdata=False): """Convenience method for adding an element with no children."""
if attrs is None: attrs = {} self.startElement(name, attrs) if contents is not None: self.characters(contents, escape=escape, cdata=cdata) self.endElement(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 _setitem_with_key_seq(self, key_seq, value): """ Sets a the value in the TOML file located by the given key sequence. Example: self._setitem(('key1', 'key2',...
table = self key_so_far = tuple() for key in key_seq[:-1]: key_so_far += (key,) self._make_sure_table_exists(key_so_far) table = table[key] table[key_seq[-1]] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _array_setitem_with_key_seq(self, array_name, index, key_seq, value): """ Sets a the array value in the TOML file located by the given key sequence. Example:...
table = self.array(array_name)[index] key_so_far = tuple() for key in key_seq[:-1]: key_so_far += (key,) new_table = self._array_make_sure_table_exists(array_name, index, key_so_far) if new_table is not None: table = new_table 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 _detect_toplevels(self): """ Returns a sequence of TopLevel instances for the current state of this table. """
return tuple(e for e in toplevels.identify(self.elements) if isinstance(e, toplevels.Table))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_table_fallbacks(self, table_toplevels): """ Updates the fallbacks on all the table elements to make relative table access possible. Raises DuplicateK...
if len(self.elements) <= 1: return def parent_of(toplevel): # Returns an TopLevel parent of the given entry, or None. for parent_toplevel in table_toplevels: if toplevel.name.sub_names[:-1] == parent_toplevel.name.sub_names: retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array(self, name): """ Returns the array of tables with the given name. """
if name in self._navigable: if isinstance(self._navigable[name], (list, tuple)): return self[name] else: raise NoArrayFoundError else: return ArrayOfTables(toml_file=self, name=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 append_elements(self, elements): """ Appends more elements to the contained internal elements. """
self._elements = self._elements + list(elements) self._on_element_change()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepend_elements(self, elements): """ Prepends more elements to the contained internal elements. """
self._elements = list(elements) + self._elements self._on_element_change()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_fresh_table(self, fresh_table): """ Gets called by FreshTable instances when they get written to. """
if fresh_table.name: elements = [] if fresh_table.is_array: elements += [element_factory.create_array_of_tables_header_element(fresh_table.name)] else: elements += [element_factory.create_table_header_element(fresh_table.name)] el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell_exec(command): """Executes the given shell command and returns its output."""
out = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return out.decode('utf-8')
<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_locale(): """Get locale. Searches for locale in the following the order: - User has specified a concrete language in the query string. - Current session ...
locales = [x[0] for x in current_app.extensions['invenio-i18n'].get_languages()] # In the case of the user specifies a language for the resource. if 'ln' in request.args: language = request.args.get('ln') if language in locales: return language # In the case...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_file(cls, db_file, language=DEFAULT_LANG): """ This is an alternative "constructor" for the DBVuln class which loads the data from a file. :param db_fil...
data = DBVuln.load_from_json(db_file, language=language) return cls(**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 from_id(cls, _id, language=DEFAULT_LANG): """ This is an alternative "constructor" for the DBVuln class which searches the db directory to find the right fil...
db_file = DBVuln.get_file_for_id(_id, language=language) data = DBVuln.load_from_json(db_file, language=language) return cls(**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 get_file_for_id(_id, language=DEFAULT_LANG): """ Given _id, search the DB for the file which contains the data :param _id: The id to search (int) :param lang...
file_start = '%s-' % _id json_path = DBVuln.get_json_path(language=language) for _file in os.listdir(json_path): if _file.startswith(file_start): return os.path.join(json_path, _file) raise NotFoundException('No data for ID %s' % _id)
<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_from_json(db_file, language=DEFAULT_LANG): """ Parses the JSON data and returns it :param db_file: File and path pointing to the JSON file to parse :par...
# There are a couple of things I don't do here, and are on purpose: # - I want to fail if the file doesn't exist # - I want to fail if the file doesn't contain valid JSON raw = json.loads(file(db_file).read()) # Here I don't do any error handling either, I expect the JSON 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 export(self): """Serializes to JSON."""
fields = ['id', 'host', 'port', 'user'] out = {} for field in fields: out[field] = getattr(self, field, None) out['mountOptions'] = self.mount_opts out['mountPoint'] = self.mount_point out['beforeMount'] = self.cmd_before_mount out['authType'] = self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mount(self): """Mounts the sftp system if it's not already mounted."""
if self.mounted: return self._mount_point_local_create() if len(self.system.mount_opts) == 0: sshfs_opts = "" else: sshfs_opts = " -o %s" % " -o ".join(self.system.mount_opts) if self.system.auth_method == self.system.AUTH_METHOD_PUBLIC_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 unmount(self): """Unmounts the sftp system if it's currently mounted."""
if not self.mounted: return # Try to unmount properly. cmd = 'fusermount -u %s' % self.mount_point_local shell_exec(cmd) # The filesystem is probably still in use. # kill sshfs and re-run this same command (which will work then). if self.mounted: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def book(self, name): """Return an API wrapper for the given order book. :param name: Order book name (e.g. "btc_cad"). :type name: str | unicode :return: Order ...
self._validate_order_book(name) return OrderBook(name, self._rest_client, self._logger)
<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_deposit_address(self, currency): """Return the deposit address for the given major currency. :param currency: Major currency name in lowercase (e.g. "btc...
self._validate_currency(currency) self._log('get deposit address for {}'.format(currency)) coin_name = self.major_currencies[currency] return self._rest_client.post( endpoint='/{}_deposit_address'.format(coin_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 withdraw(self, currency, amount, address): """Withdraw a major currency from QuadrigaCX to the given wallet. :param currency: Major currency name in lowercas...
self._validate_currency(currency) self._log('withdraw {} {} to {}'.format(amount, currency, address)) coin_name = self.major_currencies[currency] return self._rest_client.post( endpoint='/{}_withdrawal'.format(coin_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 add_nodes(self, nodes): '''The format of node is similar to add_node. If node contains a key 'cluster_node' whose value is an instance of ClusterNode, it will be used directly. ''' new_nodes, master_map = self._add_nodes_as_master(nodes) for n in new_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 add_slaves(self, new_slaves, fast_mode=False): '''This is almost the same with `add_nodes`. The difference is that it will add slaves in two slower way. This is mainly used to avoid huge overhead caused by full sync when large amount of slaves are added to cluster. If fast_mo...
<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_node(self, node): """Add a node to cluster. :param node: should be formated like this `{"addr": "", "role": "slave", "master": "master_node_id"} """
new = ClusterNode.from_uri(node["addr"]) cluster_member = self.nodes[0] check_new_nodes([new], [cluster_member]) new.meet(cluster_member.host, cluster_member.port) self.nodes.append(new) self.wait() if node["role"] != "slave": return if "m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ifelse(self, node): 'ifelse = "if" expr "then" expr "else" expr' _, cond, _, cons, _, alt = node return self.eval(cons) if self.eval(cond) else self.eval(alt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assignment(self, node, children): 'assignment = lvalue "=" expr' lvalue, _, expr = children self.env[lvalue] = expr return expr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_locale(ln): """Set Babel localization in request context. :param ln: Language identifier. """
ctx = _request_ctx_stack.top if ctx is None: raise RuntimeError('Working outside of request context.') new_locale = current_app.extensions['babel'].load_locale(ln) old_locale = getattr(ctx, 'babel_locale', None) setattr(ctx, 'babel_locale', new_locale) yield setattr(ctx, 'babel_loca...
<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_entrypoint(self, entry_point_group): """Load translations from an entry point."""
for ep in iter_entry_points(group=entry_point_group): if not resource_isdir(ep.module_name, 'translations'): continue dirname = resource_filename(ep.module_name, 'translations') self.add_path(dirname)
<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_path(self, path): """Load translations from an existing path."""
if not os.path.exists(path): raise RuntimeError('Path does not exists: %s.' % path) self.paths.append(path)
<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_translation_for_locale(self, locale): """Get translation for a specific locale."""
translations = None for dirname in self.paths: # Load a single catalog. catalog = Translations.load(dirname, [locale], domain=self.domain) if translations is None: if isinstance(catalog, Translations): translations = catalog ...
<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_translations(self): """Return the correct gettext translations for a request. This will never fail and return a dummy translation object if used outside ...
ctx = _request_ctx_stack.top if ctx is None: return NullTranslations() locale = get_locale() cache = self.get_translations_cache(ctx) translations = cache.get(str(locale)) if translations is None: translations = self._get_translation_for_local...
<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_lazystring_encoder(app): """Return a JSONEncoder for handling lazy strings from Babel. Installed on Flask application by default by :class:`InvenioI18N`....
from speaklater import _LazyString class JSONEncoder(app.json_encoder): def default(self, o): if isinstance(o, _LazyString): return text_type(o) return super(JSONEncoder, self).default(o) return JSONEncoder
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_languages(self): """Iterate over list of languages."""
default_lang = self.babel.default_locale.language default_title = self.babel.default_locale.get_display_name( default_lang) yield (default_lang, default_title) for l, title in current_app.config.get('I18N_LANGUAGES', []): yield l, title
<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_languages(self): """Get list of languages."""
if self._languages_cache is None: self._languages_cache = list(self.iter_languages()) return self._languages_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 get_locales(self): """Get a list of supported locales. Computes the list using ``I18N_LANGUAGES`` configuration variable. """
if self._locales_cache is None: langs = [self.babel.default_locale] for l, dummy_title in current_app.config.get('I18N_LANGUAGES', []): langs.append(self.babel.load_locale(l)) self._locales_cache = langs return self._locales_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 from_nodes(cls, nodes, new_nodes, max_slaves_limit=None): '''When this is used only for peeking reuslt `new_nodes` can be any type with `host` and `port` attributes ''' param = gen_distribution(nodes, new_nodes) param['max_slaves_limit'] = max_slaves_limit return c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gen_tasks(self): """generate doit tasks for each file"""
for filename in self.args: path = os.path.abspath(filename) yield { 'name': path, # 'file_dep': [path], 'actions': [(self.fun, (filename,))], }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Begin executing tasks."""
if self.log_filename: print('Output will be logged to `%s`.' % self.log_filename) start_time = time.strftime(self.timestamp_fmt) print('Started %s' % start_time) if self.log_filename: orig_stdout = sys.stdout orig_stderr = sys.stderr s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drain(iterable): """ Helper method that empties an iterable as it is iterated over. Works for: * ``dict`` * ``collections.deque`` * ``list`` * ``set`` """
if getattr(iterable, "popleft", False): def next_item(coll): return coll.popleft() elif getattr(iterable, "popitem", False): def next_item(coll): return coll.popitem() else: def next_item(coll): return coll.pop() while True: 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 divide(n, m): """Divide integer n to m chunks """
avg = int(n / m) remain = n - m * avg data = list(itertools.repeat(avg, m)) for i in range(len(data)): if not remain: break data[i] += 1 remain -= 1 return 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 spread(nodes, n): """Distrubute master instances in different nodes { "192.168.0.1": [node1, node2], "192.168.0.2": [node3, node4], "192.168.0.3": [node5, no...
target = [] while len(target) < n and nodes: for ip, node_group in list(nodes.items()): if not node_group: nodes.pop(ip) continue target.append(node_group.pop(0)) if len(target) >= n: break return target
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_local_url(target): """Determine if URL is safe to redirect to."""
ref_url = urlparse(request.host_url) test_url = urlparse(urljoin(request.host_url, target)) return test_url.scheme in ('http', 'https') and \ ref_url.netloc == test_url.netloc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_lang(lang_code=None): """Set language in session and redirect."""
# Check if language is available. lang_code = lang_code or request.values.get('lang_code') languages = dict(current_app.extensions['invenio-i18n'].get_languages()) if lang_code is None or lang_code not in languages: abort(404 if request.method == 'GET' else 400) # Set language in session. ...
<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_blueprint(register_default_routes=True): """Create Invenio-I18N blueprint."""
blueprint = Blueprint( 'invenio_i18n', __name__, template_folder='templates', static_folder='static', ) if register_default_routes: blueprint.add_url_rule('/', view_func=set_lang, methods=['POST']) blueprint.add_url_rule('/<lang_code>', view_func=set_lang, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_file_into_spirv(filepath, stage, optimization='size', warnings_as_errors=False): """Compile shader file into Spir-V binary. This function uses shader...
with open(filepath, 'rb') as f: content = f.read() return compile_into_spirv(content, stage, filepath, optimization=optimization, warnings_as_errors=warnings_as_errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_into_spirv(raw, stage, filepath, language="glsl", optimization='size', suppress_warnings=False, warnings_as_errors=False): """Compile shader code int...
# extract parameters stage = stages_mapping[stage] lang = languages_mapping[language] opt = opt_mapping[optimization] # initialize options options = lib.shaderc_compile_options_initialize() lib.shaderc_compile_options_set_source_language(options, lang) lib.shaderc_compile_options_set_o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand_folder(files): """Return a clone of file list files where all directories are recursively replaced with their contents."""
expfiles = [] for file in files: if os.path.isdir(file): for dirpath, dirnames, filenames in os.walk(file): for filename in filenames: expfiles.append(os.path.join(dirpath, filename)) else: expfiles.append(file) for path in expfil...
<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_file_list(): """Return a list of strings corresponding to file names supplied by drag and drop or standard input."""
if len(sys.argv) > 1: file_list = list(sys.argv[1:]) # make copy else: files_str = input('Select the files you want to process and drag and drop them onto this window, ' 'or type their names separated by spaces. Paths containing spaces should be ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(args): """Delete nodes from the cluster """
nodes = [ClusterNode.from_uri(n) for n in args.nodes] cluster = Cluster.from_node(ClusterNode.from_uri(args.cluster)) echo("Deleting...") for node in nodes: cluster.delete_node(node) cluster.wait()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reshard(args): """Balance slots in the cluster. This command will try its best to distribute slots equally. """
cluster = Cluster.from_node(ClusterNode.from_uri(args.cluster)) cluster.reshard()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replicate(ctx, args): """Make node to be the slave of a master. """
slave = ClusterNode.from_uri(args.node) master = ClusterNode.from_uri(args.master) if not master.is_master(): ctx.abort("Node {!r} is not a master.".format(args.master)) try: slave.replicate(master.name) except redis.ResponseError as e: ctx.abort(str(e)) Cluster.from_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flushall(args): """Execute flushall in all cluster nodes. """
cluster = Cluster.from_node(ClusterNode.from_uri(args.cluster)) for node in cluster.masters: node.flushall()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(label, at=None): """Begins the countdown"""
t = at if at is not None else time.time() marker = Marker().start(t) labels[label] = marker.dumps()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(label, at=None, remove_from_labels=False, stop_once=True): """Stops the countdown"""
t = at if at is not None else time.time() if label not in labels: return None timer = Marker().loads(labels[label]) if timer.is_running() or (timer.is_stopped() and not stop_once): timer.stop(t) if remove_from_labels: del labels[label] else: labels[label] = 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 duration(label, stop_it=True, stop_at=None): """Returns duration in seconds for label"""
if label not in labels: return None if "duration" in labels[label]: return Duration(labels[label]["duration"]) if stop_it: return stop(label, at=stop_at) else: 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 _handle_response(self, resp): """Handle the response from QuadrigaCX. :param resp: Response from QuadrigaCX. :type resp: requests.models.Response :return: Re...
http_code = resp.status_code if http_code not in self.http_success_status_codes: raise RequestError( response=resp, message='[HTTP {}] {}'.format(http_code, resp.reason) ) try: body = resp.json() except ValueError: ...
<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, endpoint, params=None): """Send an HTTP GET request to QuadrigaCX. :param endpoint: API endpoint. :type endpoint: str | unicode :param params: URL ...
response = self._session.get( url=self._url + endpoint, params=params, timeout=self._timeout ) return self._handle_response(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, endpoint, payload=None): """Send an HTTP POST request to QuadrigaCX. :param endpoint: API endpoint. :type endpoint: str | unicode :param payload: ...
nonce = int(time.time() * 10000) hmac_msg = str(nonce) + self._client_id + self._api_key signature = hmac.new( key=self._hmac_key, msg=hmac_msg.encode('utf-8'), digestmod=hashlib.sha256 ).hexdigest() if payload is None: payload = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_help(self, *args, **kwargs): """Displays this help menu."""
print("Commands available:\n") for name in dir(self): if not name.startswith("command_"): continue name_clean = name[len("command_"):] print("%s:\n - %s\n" % (name_clean, getattr(self, name).__doc__.strip()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_preflight_check(self): """Detects whether we have everything needed to mount sshfs filesystems. """
checks_pass, failures = self.environment.perform_preflight_check() if checks_pass: print('All checks pass.') else: sys.stderr.write('Problems encountered:\n') for msg in failures: sys.stderr.write(' - %s\n' % msg) sys.exit(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 _log(self, message): """Log a debug message prefixed with order book name. :param message: Debug message. :type message: str | unicode """
self._logger.debug("{}: {}".format(self.name, message))
<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_ticker(self): """Return the latest ticker information. :return: Latest ticker information. :rtype: dict """
self._log('get ticker') return self._rest_client.get( endpoint='/ticker', params={'book': 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 get_public_orders(self, group=False): """Return public orders that are currently open. :param group: If set to True (default: False), orders with the same pr...
self._log('get public orders') return self._rest_client.get( endpoint='/order_book', params={'book': self.name, 'group': int(group)} )
<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_public_trades(self, time_frame='hour'): """Return public trades that were completed recently. :param time_frame: Time frame. Allowed values are "minute" ...
self._log('get public trades') return self._rest_client.get( endpoint='/transactions', params={'book': self.name, 'time': time_frame} )