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()
if 2 in self.event_flags:
self.elapsed_milliseconds = 0
#Print the fps that the game is running at.
if self.print_frames:
self.fpsTimer += elapsed_milliseconds
if self.fpsTimer > self.print_fps_frequency:
print "FPS: ", self.__clock.get_fps()
self.fpsTimer = 0.0
#Update all of our objects
if not 0 in self.event_flags:
world.update(elapsed_milliseconds)
#Draw all of our objects
if not 1 in self.event_flags:
world.draw(elapsed_milliseconds)
#Make our world visible
pygame.display.flip() |
<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.source.width = self.image.get_width()
self.source.height = self.image.get_height()
center = Vector2(self.source.width / 2.0,
self.source.height / 2.0)
self.set_origin(center) |
<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
## self.rect = self.image.get_rect()
##
## #Reset the coordinates of the rectangle to the user defined value
## self.set_coords(self.w_coords)
#We must now resize the source rectangle to prevent clipping
self.source.width = self.image.get_width()
self.source.height = self.image.get_height() |
<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
## self.image = pygame.transform.smoothscale(self.image, scaled_value)
## else:
##Surface doesn't support smooth scale, revert to regular scale
self.image = pygame.transform.scale(self.image, scaled_value)
self.__resize_surface_extents() |
<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
if distance <= radi_sum:
#There has been a collision
## print "Distance: ", distance, "\nRadi Sum: ", radi_sum
## print "Self Coords: ", self.coords, "\nOther Coords: ", other.coords
return True
#No collision.
return False |
<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 object that we are colliding with.
colliding.append(obj)
return colliding |
<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 and handles all collision reactions. """ |
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.
obj.collision_response(collision)
collision.collision_response(obj)
elif self.collision_depth == self.DEEP_DEPTH:
for obj in collidable_objects:
collisions = self.query_all_collisions(obj)
for collision in collisions:
#Execute the reactions for both of the colliding objects.
obj.collision_response(collision)
collision.collision_response(obj) |
<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 defines what button causes the menu selection to move up. move_down is from the pygame.KEYS enum that defines what button causes the menu selection to move down. select is from the pygame.KEYS enum that defines what button causes the button to be selected. """ |
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:
#The user has just moved the mouse over the button. Set it as active.
old_index = self.current_index
self.current_index = self.gui_buttons.index(button)
self.__handle_selections(old_index, self.current_index)
elif Ragnarok.get_world().Mouse.is_clicked(self.mouse_select_button) and button.is_mouse_hovering:
#The main mouse button has just depressed, click the current button.
button.clicked_action() |
<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.parent.coords = self.exitWarp.coords |
<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 "":
continue
#An empty character is the same as collision type 0
elif char is " ":
char = "0"
elif char is "s":
#Placing the start location
self.start_location = self.tiles_to_pixels(Vector2(x_index, y_index))
char = "0"
elif not (char in self.tile_bindings):
continue
self.tiles[y_index][x_index].binding_type = self.tile_bindings[char]
x_index += 1
x_index = 0
y_index += 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 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, cYMax) )
end_pos += Vector2(1, 1)
start_pos.X, start_pos.Y = self.clamp_within_range(start_pos.X, start_pos.Y)
end_pos.X, end_pos.Y = self.clamp_within_range(end_pos.X, end_pos.Y)
cam_pos = cam.get_world_pos()
for x in range(start_pos.X, end_pos.X + 1):
for y in range(start_pos.Y, end_pos.Y + 1):
tile = self.tiles[y][x]
translate_posX = tile.coords.X - cam_pos.X
translate_posY = tile.coords.Y - cam_pos.Y
surface.blit(self.spritesheet.image, (translate_posX, translate_posY), tile.source, special_flags = 0) |
<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_to_camera(cam):
#Offset all of our objects by the camera offset.
old_pos = obj.coords
xVal = obj.coords.X - camPos.X
yVal = obj.coords.Y - camPos.Y
obj.coords = Vector2(xVal, yVal)
obj.draw(milliseconds, self.backbuffer)
obj.coords = old_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 mark_time(times, msg=None):
""" Time measurement utility. Measures times of execution between subsequent calls using time.clock(). The time is printed if the msg argument is not None. Examples -------- elapsed 0.1 elapsed again 0.05 [0.10000000000000001, 0.050000000000000003] """ |
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 = False
if package_name is not None:
mod = __import__('.'.join((package_name, name)), fromlist=[name])
else:
mod = __import__(name)
if force_reload:
reload(mod)
if remove_path:
sys.path.pop(-1)
return 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 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,
ff.co_name, f.f_lineno)
spause() |
<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 collection of ids this method can be used asynchronously as a background process (celery) """ |
# 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)
return friend_ids |
<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 social network Return: User collection """ |
# 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(friend_ids)
# Match them with the ones on the website
if USING_ALLAUTH:
return User.objects.filter(socialaccount__uid__in=friend_ids).all()
else:
return User.objects.filter(social_auth__uid__in=friend_ids).all() |
<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_secret().filter(show=show, pub_date__lt=obj.pub_date).count()
obj.index = index + 1
obj.index_next = obj.index + 1
obj.index_previous = obj.index - 1
return obj |
<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 FacebookFriendsProvider
friends_provider = FacebookFriendsProvider()
elif backend_name == 'vkontakte-oauth2':
from social_friends_finder.backends.vkontakte_backend import VKontakteFriendsProvider
friends_provider = VKontakteFriendsProvider()
else:
raise NotImplementedError("provider: %s is not implemented")
return friends_provider |
<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 UserSocialAuth if using social auth, or a SocialAccount if using allauth Returns: collection of friend objects fetched from VKontakte """ |
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_backend = VKOAuth2Backend()
# Get the access_token
tokens = social_auth_backend.tokens(user)
oauth_token = tokens['access_token']
api = vkontakte.API(token=oauth_token)
return api.get("friends.get") |
<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', 'key3'), 'text_value') is equivalent to doing self['key1']['key2']['key3'] = 'text_value' """ |
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: self._array_setitem(array_name, index, ('key1', 'key2', 'key3'), 'text_value') is equivalent to doing self.array(array_name)[index]['key1']['key2']['key3'] = 'text_value' """ |
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:
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 _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 DuplicateKeysError if appropriate. """ |
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:
return parent_toplevel
for entry in table_toplevels:
if entry.name.is_qualified:
parent = parent_of(entry)
if parent:
child_name = entry.name.without_prefix(parent.name)
parent.table_element.set_fallback({child_name.sub_names[0]: entry.table_element}) |
<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)]
elements += [fresh_table, element_factory.create_newline_element()]
self.append_elements(elements)
else:
# It's an anonymous table
self.prepend_elements([fresh_table, element_factory.create_newline_element()]) |
<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 has a language set. - User has a language set in the profile. - Headers of the HTTP request. - Default language from ``BABEL_DEFAULT_LOCALE``. Will only accept languages defined in ``I18N_LANGUAGES``. """ |
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 of the user has set a language for the current session.
language_session_key = current_app.config['I18N_SESSION_KEY']
if language_session_key in session:
language = session[language_session_key]
if language in locales:
return language
# In the case of the registered user has a prefered language.
language_user_key = current_app.config['I18N_USER_LANG_ATTR']
if language_user_key is not None and \
hasattr(current_app, 'login_manager') and \
current_user.is_authenticated:
language = getattr(current_user, language_user_key, None)
if language is not None and language in locales:
return language
# Using the headers that the navigator has sent.
headers_best_match = request.accept_languages.best_match(locales)
if headers_best_match is not None:
return headers_best_match
# If there is no way to know the language, return BABEL_DEFAULT_LOCALE
return current_app.config['BABEL_DEFAULT_LOCALE'] |
<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_file: Contents of a json file from the DB :param language: The user's language (en, es, etc.) """ |
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 file for the provided _id """ |
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 language: The user's language (en, es, etc.) :return: The filename """ |
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 :param language: The user's language (en, es, etc.) :raises: All kind of exceptions if the file doesn't exist or JSON is invalid. :return: None """ |
# 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 files to
# be valid
data = {
'_id': raw['id'],
'title': raw['title'],
'description': DBVuln.handle_ref(raw['description'], language=language),
'severity': raw['severity'],
'wasc': raw.get('wasc', []),
'tags': raw.get('tags', []),
'cwe': raw.get('cwe', []),
'owasp_top_10': raw.get('owasp_top_10', {}),
'fix_effort': raw['fix']['effort'],
'fix_guidance': DBVuln.handle_ref(raw['fix']['guidance'], language=language),
'references': DBVuln.handle_references(raw.get('references', [])),
'db_file': db_file,
}
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 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.auth_method
out['sshKey'] = self.ssh_key
return json.dumps(out, indent=4) |
<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:
ssh_opts = '-o PreferredAuthentications=publickey -i %s' % self.system.ssh_key
elif self.system.auth_method:
ssh_opts = '-o PreferredAuthentications=%s' % self.system.auth_method
else:
ssh_opts = '-o PreferredAuthentications=password'
cmd = ("{cmd_before_mount} &&"
" sshfs -o ssh_command="
"'ssh -o ConnectTimeout={timeout} -p {port} {ssh_opts}'"
" {sshfs_opts} {user}@{host}:{remote_path} {local_path}")
cmd = cmd.format(
cmd_before_mount = self.system.cmd_before_mount,
timeout = self.SSH_CONNECT_TIMEOUT,
port = self.system.port,
ssh_opts = ssh_opts,
sshfs_opts = sshfs_opts,
host = self.system.host,
user = self.system.user,
remote_path = self.mount_point_remote,
local_path = self.mount_point_local,
)
output = shell_exec(cmd).strip()
if not self.mounted:
# Clean up the directory tree
self._mount_point_local_delete()
if output == '':
output = 'Mounting failed for a reason unknown to sftpman.'
raise SftpMountException(cmd, output) |
<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:
self._kill()
shell_exec(cmd)
self._mount_point_local_delete() |
<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 book API wrapper. :rtype: quadriga.book.OrderBook :raise InvalidOrderBookError: If an invalid order book is given. **Example**: .. doctest:: """ |
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", "eth"). :type currency: str | unicode :return: Deposit address. :rtype: str | unicode """ |
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 lowercase (e.g. "btc", "eth"). :type currency: str | unicode :param amount: Withdrawal amount. :type amount: int | float | str | unicode | decimal.Decimal :param address: Wallet address. :type address: str | unicode .. warning:: Specifying incorrect major currency or wallet address could result in permanent loss of your coins. Please be careful when using this method! """ |
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:
if n.name not in master_map:
continue
master_name = master_map[n.name]
target = self.get_node(master_name)
if not target:
raise NodeNotFound(master_name)
n.replicate(target.name)
n.flush_cache()
target.flush_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 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_mode is False, there is only one master node doing
replication at the same time.
If fast_mode is True, only after the current slave has finshed
its sync, will the next slave on the same host start replication.
'''
new_nodes, master_map = self._prepare_for_adding(new_slaves)
slaves = defaultdict(list)
for s in new_nodes:
slaves[s.host].append(s)
waiting = set()
while len(slaves) > 0:
for host in slaves.keys():
if self.check_action_stopped():
logger.warning('Slaves adding was stopped, ' \
'waiting for the last slave to be finished')
slave_list = slaves[host]
s = slave_list[0]
if not fast_mode and len(waiting) > 0 and s not in waiting:
continue
if s not in waiting:
if self.check_action_stopped():
raise ActionStopped(
'Slaves adding was successfully stopped')
master_name = master_map[s.name]
target = self.get_node(master_name)
if not target:
raise NodeNotFound(master_name)
self._add_as_master(s, self.nodes[0])
s.replicate(target.name)
waiting.add(s)
continue
role = s.execute_command('ROLE')
# role[3] being changed to 'connected' means sync is finished
if role[0] == 'master' or role[3] != 'connected':
continue
waiting.remove(s)
slave_list.pop(0)
if len(slave_list) == 0:
slaves.pop(host)
if len(waiting) > 0:
waiting_list = ['{}:{}'.format(n.host, n.port) for n in waiting]
logger.info('sync waiting list: {}'.format(waiting_list))
time.sleep(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 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 "master" in node:
target = self.get_node(node["master"])
if not target:
raise NodeNotFound(node["master"])
else:
masters = sorted(self.masters, key=lambda x: len(x.slaves(x.name)))
target = masters[0]
new.replicate(target.name)
new.flush_cache()
target.flush_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 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_locale', old_locale) |
<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
continue
try:
# Merge catalog into global catalog
translations.merge(catalog)
except AttributeError:
# Translations is probably NullTranslations
if isinstance(catalog, NullTranslations):
current_app.logger.debug(
'Compiled translations seems to be missing'
' in {0}.'.format(dirname))
continue
raise
return translations or NullTranslations() |
<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 of the request or if a translation cannot be found. """ |
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_locale(locale)
cache[str(locale)] = translations
return translations |
<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 cls(**param) |
<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
sys.stdout = self.log_file
sys.stderr = self.log_file
print('Started %s' % start_time)
doit_main = DoitMain(self)
doit_main.run(['run'])
stop_time = time.strftime(self.timestamp_fmt)
if self.log_filename:
print('Stopped %s' % stop_time)
print()
sys.stdout = orig_stdout
sys.stderr = orig_stderr
self.log_file.close()
print('Stopped %s' % stop_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 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:
yield next_item(iterable)
except (IndexError, KeyError):
raise StopIteration |
<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, node6] } => [node1, node3, node5] """ |
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.
session[current_app.config['I18N_SESSION_KEY']] = lang_code.lower()
# Redirect user back.
target = get_redirect_target()
if not target:
endpoint = current_app.config['I18N_DEFAULT_REDIRECT_ENDPOINT']
target = url_for(endpoint) if endpoint else '/'
return redirect(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 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,
methods=['GET'])
return blueprint |
<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 shaderc to compile your glsl file code into Spir-V code. Args: filepath (strs):
Absolute path to your shader file stage (str):
Pipeline stage in ['vert', 'tesc', 'tese', 'geom', 'frag', 'comp'] optimization (str):
'zero' (no optimization) or 'size' (reduce size) warnings_as_errors (bool):
Turn warnings into errors Returns: bytes: Compiled Spir-V binary. Raises: CompilationError: If compilation fails. """ |
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 into Spir-V binary. This function uses shaderc to compile your glsl or hlsl code into Spir-V code. You can refer to the shaderc documentation. Args: raw (bytes):
glsl or hlsl code (bytes format, not str) stage (str):
Pipeline stage in ['vert', 'tesc', 'tese', 'geom', 'frag', 'comp'] filepath (str):
Absolute path of the file (needed for #include) language (str):
'glsl' or 'hlsl' optimization (str):
'zero' (no optimization) or 'size' (reduce size) suppress_warnings (bool):
True to suppress warnings warnings_as_errors (bool):
Turn warnings into errors Returns: bytes: Compiled Spir-V binary. Raises: CompilationError: If compilation fails. """ |
# 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_optimization_level(options, opt)
lib.shaderc_compile_options_set_target_env(
options, lib.shaderc_target_env_vulkan, 0)
lib.shaderc_compile_options_set_auto_bind_uniforms(options, False)
lib.shaderc_compile_options_set_include_callbacks(
options, lib.resolve_callback, lib.release_callback, ffi.NULL)
if suppress_warnings:
lib.shaderc_compile_options_set_suppress_warnings(options)
if warnings_as_errors:
lib.shaderc_compile_options_set_warnings_as_errors(options)
# initialize compiler
compiler = lib.shaderc_compiler_initialize()
# compile
result = lib.shaderc_compile_into_spv(compiler, raw, len(raw), stage,
str.encode(filepath), b"main",
options)
# extract result
status = lib.shaderc_result_get_compilation_status(result)
if status != lib.shaderc_compilation_status_success:
msg = _get_log(result)
lib.shaderc_compile_options_release(options)
lib.shaderc_result_release(result)
lib.shaderc_compiler_release(compiler)
raise CompilationError(msg)
length = lib.shaderc_result_get_length(result)
output_pointer = lib.shaderc_result_get_bytes(result)
tmp = bytearray(length)
ffi.memmove(tmp, output_pointer, length)
spirv = bytes(tmp)
# release resources
lib.shaderc_compile_options_release(options)
lib.shaderc_result_release(result)
lib.shaderc_compiler_release(compiler)
return spirv |
<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 expfiles:
if not os.path.exists(path):
sys.stderr.write('%s: No such file or directory\n' % path)
return expfiles |
<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 '
'surrounded by quotation marks.\nPress ENTER when you\'re done: ')
if "win" in sys.platform:
# the POSIX shlex.split uses backslashes for escape sequences, so Windows paths need to set posix=False
file_list = shlex.split(files_str, posix=False)
# the non-POSIX shlex.split does not automatically clean quotation marks from the final product
file_list = [f.replace('"', '').replace("'", "") for f in file_list]
else:
file_list = shlex.split(files_str, posix=True)
# substitute in shell variables and get absolute paths
for i in range(len(file_list)):
file_list[i] = os.path.abspath( os.path.expanduser(os.path.expandvars(file_list[i])) )
return file_list |
<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_node(master).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 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] = timer.dumps()
return timer.duration() |
<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: Response body. :rtype: dict :raise quadriga.exceptions.RequestError: If HTTP OK was not returned. """ |
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:
raise RequestError(
response=resp,
message='[HTTP {}] response body: {}'.format(
http_code,
resp.text
)
)
else:
if 'error' in body:
error_code = body['error'].get('code', '?')
raise RequestError(
response=resp,
message='[HTTP {}][ERR {}] {}'.format(
resp.status_code,
error_code,
body['error'].get('message', 'no error message')
),
error_code=error_code
)
return body |
<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 parameters. :type params: dict :return: Response body from QuadrigaCX. :rtype: dict :raise quadriga.exceptions.RequestError: If HTTP OK was not returned. """ |
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: Request payload. :type payload: dict :return: Response body from QuadrigaCX. :rtype: dict :raise quadriga.exceptions.RequestError: If HTTP OK was not returned. """ |
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 = {}
payload['key'] = self._api_key
payload['nonce'] = nonce
payload['signature'] = signature
response = self._session.post(
url=self._url + endpoint,
json=payload,
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 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 price are grouped. :type group: bool :return: Public orders currently open. :rtype: dict """ |
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" for trades in the last minute, or "hour" for trades in the last hour (default: "hour"). :type time_frame: str | unicode :return: Public trades completed recently. :rtype: [dict] """ |
self._log('get public trades')
return self._rest_client.get(
endpoint='/transactions',
params={'book': self.name, 'time': time_frame}
) |