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 proxy_for(widget):
"""Create a proxy for a Widget :param widget: A gtk.Widget to proxy This will raise a KeyError if there is no proxy type registered for th... |
proxy_type = widget_proxies.get(widget.__class__)
if proxy_type is None:
raise KeyError('There is no proxy type registered for %r' % widget)
return proxy_type(widget) |
<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, value):
"""Update the widget's value """ |
self.update_internal(value)
self.emit('changed', self.get_widget_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 update_internal(self, value):
"""Update the widget's value without firing a changed signal """ |
self.block()
self.set_widget_value(value)
self.unblock() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_widget(self):
"""Perform the initial connection of the widget the default implementation will connect to the widgets signal based on self.signal_name... |
if self.signal_name is not None:
# None for read only widgets
sid = self.widget.connect(self.signal_name, self.widget_changed)
self.connections.append(sid) |
<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_proxy_for(self, name, widget):
"""Create a proxy for a widget and add it to this group :param name: The name or key of the proxy, which will be emitted w... |
proxy = proxy_for(widget)
self.add_proxy(name, proxy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _urljoin(left, right):
"""Join two URLs. Takes URLs specified by left and right and joins them into a single URL. If right is an absolute URL, it is returned... |
# Handle the tricky case of right being a full URL
tmp = urlparse.urlparse(right)
if tmp.scheme or tmp.netloc:
# Go ahead and use urlparse.urljoin()
return urlparse.urljoin(left, right)
# Check for slashes
joincond = (left[-1:], right[:1])
if joincond == ('/', '/'):
# ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restmethod(method, reluri, *qargs, **headers):
"""Decorate a method to inject an HTTPRequest. Generates an HTTPRequest using the given HTTP method and relati... |
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Process the arguments against the original function
argmap, theSelf, req_name = _getcallargs(func, args, kwargs)
# Build the URL
url = _urljoin(theSelf._baseurl, reluri.form... |
<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_addons(widget, *addon_types, **named_addon_types):
"""Apply some addons to a widget. :param widget: The widget to apply addons to. :param addon_types: ... |
for addon_type in addon_types:
addon_type(widget)
for name, addon_type in named_addon_types.items():
addon_type(widget, addon_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 make_path(config, *endings):
""" Create a path based on component configuration. All paths are relative to the component's configuration directory; usually t... |
config_dir = config.get("dp.config_dir")
return os.path.join(config_dir, *endings) |
<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_json(payload):
""" Convert the JSON expression of a contact information into an instance `Contact. @param payload: a JSON expression representing a cont... |
contact_item_number = len(payload)
assert 2 <= contact_item_number <= 4, 'Invalid contact information format'
is_primary = is_verified = None
# Unpack the contact information to each component.
if contact_item_number == 2:
(name, value) = payload
elif conta... |
<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_object(obj):
""" Convert an object representing a contact information to an instance `Contact`. @param obj: an object containg the following attributes:... |
return obj if isinstance(obj, Contact) \
else Contact(cast.string_to_enum(obj.name, Contact.ContactName),
obj.value,
is_primary=obj.is_primary and cast.string_to_boolean(obj.is_primary, strict=True),
is_verified=obj.is_verif... |
<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, request, question_level, question_number, format=None):
""" Use this Function to submit. """ |
user = User.objects.get(username=request.user.username)
question = Question.objects.filter(question_level=question_level).filter(question_number=question_number)
if int(user.profile.user_access_level) < int(question_level):
content = {'user_nick':profile.user_nick, 'please move alo... |
<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, request, question_level, question_number, format=None):
""" Use this Function to submit Comment. """ |
user = User.objects.get(username=request.user.username)
question = Question.objects.filter(question_level=question_level).filter(question_number=question_number)
if int(user.profile.user_access_level) < int(question_level):
content = {'user_nick':profile.user_nick, 'please move alon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_base_sequence(base_offsets):
""" Return a sequence of characters corresponding to the specified base. Example:: '0123456789ABCDEF' @param base_offs... |
return ''.join([ chr(c) for c in list(itertools.chain.from_iterable(
[ range(ord(x), ord(y) + 1) for (x, y) in base_offsets ])) ]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_secured_key(value, key_nonce_separator='.', nonce_length=4, base=BASE62):
""" Generate a secured key composed of the integer value encoded in Base62... |
if not isinstance(value, (int, long)):
raise ValueError()
posix_time = int(time.mktime(datetime.datetime.now().timetuple()))
nonce = hashlib.md5(str(posix_time)).hexdigest()[:nonce_length]
key = int_to_key(value, base=base)
return key, nonce, '%s%s%s' % (key, key_nonce_separator, nonce) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def int_to_key(value, base=BASE62):
""" Convert the specified integer to a key using the given base. @param value: a positive integer. @param base: a sequence of... |
def key_sequence_generator(value, base):
"""
Generator for producing sequence of characters of a key providing an
integer value and a base of characters for encoding, such as Base62
for instance.
@param value: a positive integer.
@param base: a sequence of character... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_to_int(key, base=BASE62):
""" Convert the following key to an integer. @param key: a key. @param base: a sequence of characters that was used to encode t... |
base_length = len(base)
value = 0
for c in reversed(key):
value = (value * base_length) + base.index(c)
return 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 parse_secured_key(secured_key, key_nonce_separator='.', nonce_length=4, base=BASE62):
""" Parse a given secured key and return its associated integer, the ke... |
parts = secured_key.split(key_nonce_separator)
if len(parts) != 2:
raise ValueError('Invalid secured key format')
(key, nonce) = parts
if len(nonce) != nonce_length:
raise ValueError('Invalid length of the key nonce')
return key_to_int(key, base=base), key, nonce |
<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(args):
""" Get a template by name. """ |
m = TemplateManager(args.hosts)
t = m.get(args.name)
if t:
print(json.dumps(t, indent=2))
else:
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 delete(args):
""" Delete a template by name """ |
m = TemplateManager(args.hosts)
m.delete(args.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 user_parser(user):
""" Parses a user object """ |
if __is_deleted(user):
return deleted_parser(user)
if user['id'] in item_types:
raise Exception('Not a user name')
if type(user['id']) == int:
raise Exception('Not a user name')
return User(
user['id'],
user['delay'],
user['created'],
user['karm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def story_parser(story):
""" Parses a story object """ |
if __is_deleted(story):
return deleted_parser(story)
if story['type'] != 'story':
return item_parser(story)
return Story(
__check_key('id', story),
__check_key('by', story),
__check_key('kids', story),
__check_key('score', story),
__check_key('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 comment_parser(comment):
""" Parses a comment object """ |
try:
if comment['type'] != 'comment':
return item_parser(comment)
except KeyError:
return deleted_parser(comment)
return Comment(
comment['id'],
comment['by'],
__check_key('kids', comment), # some comments do not have kids key
comment['parent'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def poll_parser(poll):
""" Parses a poll object """ |
if __is_deleted(poll):
return deleted_parser(poll)
if poll['type'] not in poll_types:
raise Exception('Not a poll type')
return Poll(
poll['id'],
poll['by'],
__check_key('kids', poll), # poll and pollopt differ this property
__check_key('parts', poll), # po... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def item_parser(item):
""" Parses a item object It gives None for the property not present Used when some item types do not get parsed easily when using gevent "... |
if __is_deleted(item):
return deleted_parser(item)
return Item(
__check_key('id', item),
__check_key('deleted', item),
__check_key('type', item),
__check_key('by', item),
__check_key('time', item),
__check_key('text', item),
__check_key('dead', it... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_to_string(value, null_string_repr='[]', trimable=False):
""" Return a string representation of the specified JSON object. @param value: a JSON object. @... |
return null_string_repr if is_undefined(value) \
else obj.jsonify(value, trimable=trimable) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string_to_boolean(value, strict=False, default_value=False):
""" Return a boolean with a value represented by the specified string. @param value: a string re... |
if is_undefined(value) and default_value:
return default_value
if isinstance(value, bool):
return value
if isinstance(value, basestring) and value is not None:
value = value.lower()
is_true = value in ('yes', 'true', 't', '1')
if not is_true and strict == True and \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string_to_date(value):
""" Return a Python date that corresponds to the specified string representation. @param value: string representation of a date. @retu... |
if isinstance(value, datetime.date):
return value
return dateutil.parser.parse(value).date() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string_to_decimal(value, strict=True):
""" Return a decimal corresponding to the string representation of a number. @param value: a string representation of ... |
if is_undefined(value):
if strict:
raise ValueError('The value cannot be null')
return None
try:
return float(value)
except ValueError:
raise ValueError(
'The specified string "%s" does not represent an integer' % 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 string_to_enum(value, enumeration, strict=True, default_value=None):
""" Return the item of an enumeration that corresponds to the specified string represent... |
if not isinstance(enumeration, Enum):
raise ValueError('The specified enumeration is not an instance of Enum')
if is_undefined(value):
if strict:
raise ValueError('The value cannot be null')
if default_value is not None and not default_value in enumeration:
rai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string_to_integer(value, strict=False):
""" Return an integer corresponding to the string representation of a number. @param value: a string representation o... |
if is_undefined(value):
if strict:
raise ValueError('The value cannot be null')
return None
try:
return int(value)
except ValueError:
raise ValueError('The specified string "%s" does not represent an integer' % 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 string_to_ipv4(value, strict=False):
""" Return a tuple corresponding to the string representation of an IPv4 address. An IPv4 address is canonically represe... |
if is_undefined(value):
if strict:
raise ValueError('The value cannot be null')
return None
if not REGEX_IPV4.match(value):
raise ValueError('The specified string "%s" does not represent a IPv4' % value)
ipv4 = [ int(byte) for byte in value.split('.') if int(byte) < 25... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string_to_time(value):
""" Return an instance ``datetime.time`` that corresponds to the specified string representation. @param value: a string representatio... |
try:
return datetime.datetime.strptime(value, '%H:%M:%S').time()
except ValueError:
return datetime.datetime.strptime(value, '%H:%M').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 string_to_timestamp(value, second_digits=3, default_utc_offset=None, rounding_method=TimestampRoundingMethod.ceiling):
""" Return the ISO 8601 date time that... |
if second_digits < 0 or second_digits > 6:
raise ValueError('The number of second digits after the decimal point must be in 0..6')
if not value:
return None
if isinstance(value, datetime.date):
pydatetime = ISO8601DateTime.from_datetime(value)
else:
if default_utc_off... |
<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_app(debug=False):
""" Create the flask app :param debug: Use debug mode :type debug: bool :return: Created app :rtype: flask.Flask """ |
app = Flask(__name__)
app.secret_key = str(uuid.uuid4())
app.json_encoder = DateTimeEncoder
app.register_blueprint(page)
Bower(app)
api = Api(app)
api.add_resource(
PluginListAPI,
api_path + "plugins/",
endpoint="APIPlugins"
)
api.add_resource(
Plugin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plugin(plugin_key=None):
""" Serve plugin page :param plugin_key: Which plugin page to server; if None -> landing page (default: None) :type plugin_key: None... |
p = None
if plugin_key:
try:
p = db_plugin_instance.plugin_get(plugin_key)
except KeyError:
logger.error(u"Plugin '{}' not found".format(plugin_key))
return render_template("plugin.html", title="Plugins", plugin=p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_segment(point_p, point_q, point_r):
""" Given three colinear points p, q, r, the function checks if point q lies on line segment "pr" :param point_p: :typ... |
if (point_q.x <= max(point_p.x, point_r.x)
and point_q.x >= min(point_p.x, point_r.x)
and point_q.y <= max(point_p.y, point_r.y)
and point_q.y >= min(point_p.y, point_r.y)):
return True
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 is_intersect(line_a, line_b):
""" Determine if lina_a intersect with line_b :param lina_a: :type lina_a: models.Line :param lina_b: :type line_b: models.Line... |
# Find the four orientations needed for general and special cases
orientation_1 = orientation(line_a.endpoint_a, line_a.endpoint_b,
line_b.endpoint_a)
orientation_2 = orientation(line_a.endpoint_a, line_a.endpoint_b,
line_b.endpoint_b)
ori... |
<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_inside(point, region):
""" Detemine if point is in region :param point: :type point: models.Point :param region: :type region: Region """ |
points = region.vertices
extrame = models.Point(x=1000000, y=point.y)
points = points + [points[0]]
intersect_count = 0
for i in range(len(points) - 1):
if is_intersect(models.Line(point, extrame),
models.Line(points[i], points[i+1])):
intersect_count +=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze(qpi, r0, method="edge", model="projection", edgekw={}, imagekw={}, ret_center=False, ret_pha_offset=False, ret_qpi=False):
"""Determine refractive in... |
if method == "edge":
if model != "projection":
raise ValueError("`method='edge'` requires `model='projection'`!")
n, r, c = edgefit.analyze(qpi=qpi,
r0=r0,
edgekw=edgekw,
ret_center=Tru... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bg_phase_mask_from_sim(sim, radial_clearance=1.1):
"""Return the background phase mask of a qpsphere simulation Parameters sim: qpimage.QPImage Quantitative ... |
# Mask values around the object
cx, cy = sim["sim center"]
radius = sim["sim radius"]
px_um = sim["pixel size"]
x = np.arange(sim.shape[0]).reshape(-1, 1)
y = np.arange(sim.shape[1]).reshape(1, -1)
rsq = (x - cx)**2 + (y - cy)**2
mask = rsq > (radius/px_um * radial_clearance)**2
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bg_phase_mask_for_qpi(qpi, r0, method="edge", model="projection", edgekw={}, imagekw={}, radial_clearance=1.1):
"""Determine the background phase mask for a ... |
# fit sphere
_, _, sim = analyze(qpi=qpi,
r0=r0,
method=method,
model=model,
edgekw=edgekw,
imagekw=imagekw,
ret_qpi=True)
# determine mask
mask = bg_phase_mas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_subtype(self, subtype):
"""Add a subtype segment Args: subtype (str):
May be one of ``['a', 'c', 'r']``. See the `Reference Definition <https://electio... |
self._validate_subtype(subtype)
self.subtype = subtype
return 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 with_organisation(self, organisation):
"""Add an organisation segment. Args: organisation (str):
Official name of an administrative body holding an election... |
if organisation is None:
organisation = ''
organisation = slugify(organisation)
self._validate_organisation(organisation)
self.organisation = organisation
return 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 with_division(self, division):
"""Add a division segment Args: division (str):
Official name of an electoral division. Returns: IdBuilder Raises: ValueError... |
if division is None:
division = ''
division = slugify(division)
self._validate_division(division)
self.division = division
return 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 execute(cmd):
''' Call cmd and return output. return None if any exception occurs '''
try:
return safely_decode(check_output(cmd))
except Exception as e:
logger.warn(u'Couldnt execute cmd: %s.\nReason: %s' % (cmd, e))
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 create_environment(component_config):
""" Create a modified environment. Arguments component_config - The configuration for a component. """ |
ret = os.environ.copy()
for env in component_config.get_list("dp.env_list"):
real_env = env.upper()
value = os.environ.get(real_env)
value = _prepend_env(component_config, env, value)
value = _append_env(component_config, env, value)
_apply_change(ret, real_env, value, 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 set_scale_alpha_from_selection(self):
'''
Set scale marker to alpha for selected layer.
'''
# 1. Look up selected layer.
selection = self.treeview_layers.get_selection()
list_store, selected_iter = selection.get_selected()
# 2. Set adjustment to current alph... |
<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_alpha_for_selection(self, alpha):
'''
Set alpha for selected layer.
'''
# 1. Look up selected layer.
selection = self.treeview_layers.get_selection()
list_store, selected_iter = selection.get_selected()
# 2. Set alpha value for layer (if selected).
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_data(self, block):
"""expects Block from Compressor""" |
if hasattr(block, 'send_destinations') and block.send_destinations:
self.fire(events.FileProcessed(block))
self._log_in_db(block)
if self._sent_log_file:
self._log_in_sent_log(block)
self.log.info("Sent to '%s' file '%s' containing files: %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 should_send(self, request):
"""Returns whether or not the request should be sent to the modules, based on the filters.""" |
if self.filters.get('whitelist', None):
return request.tree.type in self.filters['whitelist']
elif self.filters.get('blacklist', None):
return request.tree.type not in self.filters['blacklist']
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(args):
""" Get a river by name. """ |
m = RiverManager(args.hosts)
r = m.get(args.name)
if r:
print(json.dumps(r, indent=2))
else:
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 create(args):
""" Create a river. This command expects to be fed a JSON document on STDIN. """ |
data = json.load(sys.stdin)
m = RiverManager(args.hosts)
m.create(args.name, data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(args):
""" Delete a river by name """ |
m = RiverManager(args.hosts)
m.delete(args.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 compare(args):
""" Compare the extant river with the given name to the passed JSON. The command will exit with a return code of 0 if the named river is confi... |
data = json.load(sys.stdin)
m = RiverManager(args.hosts)
if m.compare(args.name, data):
sys.exit(0)
else:
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 analyze(qpi, model, n0, r0, c0=None, imagekw={}, ret_center=False, ret_pha_offset=False, ret_qpi=False):
"""Fit refractive index and radius to a phase image ... |
res = match_phase(qpi, model=model, n0=n0, r0=r0, c0=c0,
ret_center=ret_center,
ret_pha_offset=ret_pha_offset,
ret_qpi=ret_qpi,
**imagekw)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rm_tempdirs():
''' Remove temporary build folders '''
tempdirs = [Dir.BUILD, Dir.COCOA_BUILD, Dir.LIB]
for tempdir in tempdirs:
if os.path.exists(tempdir):
shutil.rmtree(tempdir, ignore_errors=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reformat_pattern(pattern, compile=False):
'''
Apply the filters on user pattern to generate a new regular expression
pattern.
A user provided variable, should start with an alphabet, can be
alphanumeric and can have _.
'''
# User pattern: (w:<name>) --> Changes to (?P<name>\w)
rex_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def match_string(pattern, search_string):
'''
Match a pattern in a string
'''
rexobj = REX(pattern, None)
rexpatstr = reformat_pattern(pattern)
#print "rexpatstr: ", rexpatstr
rexpat = re.compile(rexpatstr)
rexobj.rex_patternstr = rexpatstr
rexobj.rex_pattern = rexpat
line_co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def populate_resobj(rexobj, mobj, loc):
'''
Popuate the result object and append it to the
rexobj results.
'''
resobj = REXResult(mobj, loc)
rexobj.matches.append(resobj)
rexobj.res_count += 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 match_file(pattern, filename):
'''
The function will match a pattern in a file and return
a rex object, which will have all the matches found in the file.
'''
# Validate user data.
if pattern is None:
return None
if os.stat(filename).st_size == 0:
return None
rexo... |
<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_tabular_string(search_string,
header_keys,
delimiter=None,
merge_list=None):
'''
Given a string in a tabular format, parse it and return a
dictionary
@args:
search_string: This is a string in tabular format (e.g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dump_rexobj_results(rexobj, options=None):
'''
print all the results.
'''
print("-" * 60)
print("Match count: ", rexobj.res_count)
matches = rexobj.matches
for match in matches:
print("Loc:", match.loc, ":: ")
for key in match.named_groups.keys():
print("%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 get_match_value(rexobj, key, index=0):
'''
Return a matched value for the key for a specific match from the
results.
'''
if rexobj is None:
return None
if rexobj.res_count == 0:
return None
try:
return rexobj.matches[index].named_groups[key]
except IndexErro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_resource(plugin_name, resource_name, resource_data):
""" Save a resource in local cache :param plugin_name: Name of plugin this resource belongs to :typ... |
path = os.path.join(resource_dir_path, plugin_name)
if not os.path.exists(path):
os.makedirs(path)
path = os.path.join(path, resource_name)
logger.debug("Saving {}".format(path))
with open(path, 'wb') as f:
f.write(base64.b64decode(resource_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 __convert_env(env, encoding):
"""Environment variables should be bytes not unicode on Windows.""" |
d = dict(os.environ, **(oget(env, {})))
# workaround for Windows+Python3 environment
if not SHOULD_NOT_ENCODE_ARGS:
return dict((k.encode(encoding), v.encode(encoding)) for k, v in d.items())
else:
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def length(self):
""" Calculate total length of the polyline :return: total length in meters :rtype: float """ |
total_length = 0
for location_a, location_b in zip(
self.locations[:-1], self.locations[1:]):
total_length += Line(location_a, location_b).length
return total_length |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_hook(dialog=SimpleExceptionDialog, invoke_old_hook=False, **extra):
""" install the configured exception hook wrapping the old exception hook don't u... |
global _old_hook
assert _old_hook is None
def new_hook(etype, eval, trace):
gobject.idle_add(dialog_handler, dialog, etype, eval, trace, extra)
if invoke_old_hook:
_old_hook(etype, eval, trace)
_old_hook = sys.excepthook
sys.excepthook = new_hook |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _summarize_action(self, root_action):
"""Return a dictionary with various information about this root_action. Note: Scoring assumes that each actor makes the... |
def is_target_node(node):
return isinstance(node, base.EOT) or (node is root_action)
# store per-turn results from the bottom up.
realistic_ends_by_node = dict()
for node in root_action.post_order_nodes(): # bottom up to this action
# only work with EOT or the r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _relative_score(self, start_eot, end_eot, active, passive):
"""Return the balance of perception between the two nodes. A positive score indicates the result ... |
active_start = self._score_eot_for_actor(start_eot, active)
passive_start = self._score_eot_for_actor(start_eot, passive)
active_end = self._score_eot_for_actor(end_eot, active)
passive_end = self._score_eot_for_actor(end_eot, passive)
return (active_end - passive_end) - (active... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _score_eot_for_actor(self, eot, actor):
"""Have the actor evaluate the end of turn for itself only.""" |
# currently just simple sum of own attributes
# could be much more sophisticated in both analysis (e.g. formulas)
# and breadth of items analyzed (e.g. require other actor, the board)
end_state = eot.parent
a = {'player': end_state.player,
'opponent': end_state.oppo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _summarize_result(self, root_action, leaf_eot):
"""Return a dict with useful information that summarizes this action.""" |
root_board = root_action.parent.board
action_detail = root_action.position_pair
score = self._relative_score(root_action, leaf_eot,
root_action.parent.player,
root_action.parent.opponent)
# mana drain info
... |
<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_phase_error_hdf5(h5path, identifier, index, phase, mphase, model, n0, r0, spi_params):
"""Export the phase error to an hdf5 file Parameters h5path: st... |
with h5py.File(h5path, mode="a") as h5:
if identifier in h5:
grp = h5[identifier]
else:
grp = h5.create_group(identifier)
ds = grp.create_dataset("phase_error_{:05d}".format(index),
data=mphase-phase)
ds.attrs["index initial"] ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scripts(cls, pkg, metadata, paths=[], **kwargs):
"""This class method is the preferred way to create SceneScript objects. :param str pkg: The dotted name of ... |
for path in paths:
try:
fP = pkg_resources.resource_filename(pkg, path)
except ImportError:
cls.log.warning(
"No package called {}".format(pkg)
)
else:
if not os.path.isfile(fP):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(text, name=None):
"""Read a block of text as a docutils document. :param str text: Scene script text. :param str name: An optional name for the document... |
doc = docutils.utils.new_document(name, SceneScript.settings)
parser = docutils.parsers.rst.Parser()
parser.parse(text, doc)
return doc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select(self, personae, relative=False, roles=1):
"""Select a persona for each entity declared in the scene. :param personae: A sequence of Personae. :param b... |
def constrained(entity):
return (
len(entity["options"].get("types", [])) +
len(entity["options"].get("states", []))
)
rv = OrderedDict()
performing = defaultdict(set)
pool = list(personae)
self.log.debug(pool)
en... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cast(self, mapping):
"""Allocate the scene script a cast of personae for each of its entities. :param mapping: A dictionary of {Entity, Persona} :return: The... |
# See 'citation' method in
# http://docutils.sourceforge.net/docutils/parsers/rst/states.py
for c, p in mapping.items():
self.doc.note_citation(c)
self.doc.note_explicit_target(c, c)
c.persona = p
self.log.debug("{0} to be played by {1}".format(
... |
<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):
"""Parse the script file. :rtype: :py:class:`~turberfield.dialogue.model.Model` """ |
model = Model(self.fP, self.doc)
self.doc.walkabout(model)
return model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def my_main(context):
""" The starting point for your app.""" |
print('starting MyApp...')
if context['debug']:
print('Context:')
for k in context:
print('Key: {}\nValue: {}'.format(k, context[k]))
print('Done!')
return 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 versus_summaries(turns=2, sims_to_average=2, async_results_q=None):
"""Return summaries of the likely resutls of each available action.. Arguments: - turns: ... |
board, player, opponent, extra_actions = _state_investigator.get_versus()
if extra_actions: extra_actions = 1 # limit value for realistic time
if board is None:
return tuple()
averaged_summaries = list() # default return value is empty
# keep a separate advisor for each simulation to aver... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_tree_pathname(filename, directory_depth=8, pathname_separator_character=os.sep):
""" Return a pathname built of the specified number of sub-directories... |
pathname = ''
(filename_without_extension, _file_extension_) = os.path.splitext(filename)
for i in range(min(directory_depth, len(filename_without_extension))):
pathname += filename_without_extension[i] + pathname_separator_character
return pathname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_tree_file_pathname(filename, directory_depth=8, pathname_separator_character=os.sep):
""" Return a file pathname which pathname is built of the specifi... |
return build_tree_pathname(filename, directory_depth, pathname_separator_character) + 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 find_root_path(absolute_path, relative_path):
""" Return the root path of a path relative to an absolute path. Example: @param absolute_path: an absolute pat... |
_absolute_path = os.path.normpath(absolute_path)
_relative_path = os.path.normpath(relative_path)
index = _absolute_path.rfind(_relative_path)
if index == -1 or len(_relative_path) + index < len(_absolute_path):
raise ValueError('The relative path does not end the specified absolute 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_file_checksum(file_path_name, hash_algorithm_name='md5'):
""" Generate the MD5 checksum of the specified file. @param file_path_name: the absolute path a... |
hash_algorithm = hashlib.new(hash_algorithm_name)
if sys.platform == "win32":
import ctypes
sectors_per_cluster = ctypes.c_ulonglong(0)
bytes_per_sector = ctypes.c_ulonglong(0)
root_path_name = ctypes.c_wchar_p(u"C:\\")
ctypes.windll.kernel32.GetDiskFreeSpaceW(root_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 make_directory_if_not_exists(path):
""" Create the specified path, making all intermediate-level directories needed to contain the leaf directory. Ignore any... |
try:
os.makedirs(path)
except OSError, error: # Ignore if the directory has been already created.
if error.errno <> errno.EEXIST:
raise error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_file(source_file_pathname, destination_file_pathname):
""" Move the the specified file to another location. If the destination already exists, it is rep... |
if os.path.exists(destination_file_pathname):
os.remove(destination_file_pathname)
shutil.move(source_file_pathname, destination_file_pathname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def which(exe_name):
""" Locate a program file in the user's path. @param exec_name: name of the executable file. @return: ``None`` if the executable has not bee... |
def is_exe(file_path_name):
return os.path.isfile(file_path_name) and os.access(file_path_name, os.X_OK)
is_platform_windows = (platform.system() == 'Windows')
fpath, _fname = os.path.split(exe_name)
if fpath:
if is_exe(exe_name):
return exe_name
else:
for 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_time(filename, tags):
"""
Get most reliable timestamp from a picture, running down a couple of options.
Filename, exif tags, modification time.
""" |
# use exif 'Image DateTime' field as the time
if 'Image DateTime' in tags.keys():
return time.strptime(str(tags['Image DateTime']), '%Y:%m:%d %H:%M:%S')
# very fuzzy time machting on filename
# TODO: very fuzzy part, now it just matches the iphone naming convention
m = re.match('^(\... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def location_filter(files_with_tags, location, radius):
'''
Get photos taken within the specified radius from a given point.
'''
on_location = dict()
for f, tags in files_with_tags.items():
if 'GPS GPSLatitude' in tags:
try:
lat = convert_to_decimal(str(ta... |
<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_based_on_time(files_with_tags, on_location):
'''
Sometimes the first photo in a series does not have gps coordinates because the phone
doesnt have a gps-fix yet. To add these photos as well we take the list of photos wich where
taken in the right location. Then add any photos taken whitin 10... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _debug(self, msg, *args, **kwargs):
"""Emit debugging messages.""" |
# Do nothing if debugging is disabled
if self._debug_stream is None or self._debug_stream is False:
return
# What are we passing to the format?
if kwargs:
fmtargs = kwargs
else:
fmtargs = args
# Emit the message
print >>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 _make_req(self, method, url, methname, headers=None):
"""Create a request object for the specified method and url.""" |
# Build up headers
hset = hdrs.HeaderDict()
# Walk through our global headers
for hdr, value in self._headers.items():
# If it's a callable, call it
if callable(value):
value = value(methname)
else:
# OK, just stringi... |
<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_plugins(entry_point_name):
""" Find everything with a specific entry_point. Results will be returned as a dictionary, with the name as the key and the ... |
entries = {}
for entry_point in pkg_resources.iter_entry_points(entry_point_name):
entries[entry_point.name] = entry_point.load()
return entries |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prefixedDec(nstr, schema):
""" !~~prefixedDec corresponding strings in documents must begin with the associated string in the schema, and the right part of s... |
if not nstr.startswith(schema):
return False
postfix = nstr[len(schema):]
try:
int(postfix)
except ValueError:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _transschema(x):
""" Transform a schema, once loaded from its YAML representation, to its final internal representation """ |
if isinstance(x, tuple):
return x.__class__(_transschema(x[0]), *x[1:])
elif isinstance(x, dict):
return dict((_qualify_map(key, _transschema(val)) for key, val in x.iteritems()))
elif isinstance(x, list):
return map(_transschema, x)
else:
return x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fill_entries(self):
"""Populate entries dictionaries from index.""" |
for file in self.index.files:
path = self.index.paths[file.pathIndex]
data_offset = file.dataOffset
data_size = file.dataSize
obj = RAFEntry(self._data_handle, path, data_offset, data_size)
# Add to full path dictionary
assert path not in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, path=None, name=None):
""" Returns most recent version of the matching file. If there are multiple files of the same name and version, a random on... |
if path is None and name is None:
# TODO: Correct error type
raise ValueError("Path or name is required.")
# Entries are sorted by version number, so the last will be the most recent
# TODO: Reduce redundancy with RAFArchive
if path:
return self.e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_re(self, pattern):
"""Find the most recent versions of all entries whose path matches a given pattern.""" |
# TODO: Reduce redundancy with RAFArchive
pattern = re.compile(pattern, re.I)
for k, v in six.iteritems(self.entries_full):
if pattern.search(k):
# Most recent version will be last
yield v[-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 colorize(string, color, *args, **kwargs):
""" Implements string formatting along with color specified in colorama.Fore """ |
string = string.format(*args, **kwargs)
return color + string + colorama.Fore.RESET |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def legitimize(text):
"""Converts a string to a valid filename. """ |
import platform
os_ = platform.system()
# POSIX systems
text = text.translate({
0: None,
ord('/'): '-',
ord('|'): '-',
})
if os_ == 'Windows':
# Windows (non-POSIX namespace)
text = text.translate({
# Reserved in Windows VFAT and NTFS
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.