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 find(self, path, match, flags):
""" find every matching child path under path """ |
try:
match = re.compile(match, flags)
except sre_constants.error as ex:
print("Bad regexp: %s" % (ex))
return
offset = len(path)
for cpath in Tree(self, path).get():
if match.search(cpath[offset:]):
yield cpath |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grep(self, path, content, flags):
""" grep every child path under path for content """ |
try:
match = re.compile(content, flags)
except sre_constants.error as ex:
print("Bad regexp: %s" % (ex))
return
for gpath, matches in self.do_grep(path, match):
yield (gpath, matches) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_grep(self, path, match):
""" grep's work horse """ |
try:
children = self.get_children(path)
except (NoNodeError, NoAuthError):
children = []
for child in children:
full_path = os.path.join(path, child)
try:
value, _ = self.get(full_path)
except (NoNodeError, NoAuthError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tree(self, path, max_depth, full_path=False, include_stat=False):
"""DFS generator which starts from a given path and goes up to a max depth. :param path: pa... |
for child_level_stat in self.do_tree(path, max_depth, 0, full_path, include_stat):
yield child_level_stat |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_tree(self, path, max_depth, level, full_path, include_stat):
""" tree's work horse """ |
try:
children = self.get_children(path)
except (NoNodeError, NoAuthError):
children = []
for child in children:
cpath = os.path.join(path, child) if full_path else child
if include_stat:
yield cpath, level, self.stat(os.path.join(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def equal(self, path_a, path_b):
""" compare if a and b have the same bytes """ |
content_a, _ = self.get_bytes(path_a)
content_b, _ = self.get_bytes(path_b)
return content_a == content_b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stat(self, path):
""" safely gets the Znode's Stat """ |
try:
stat = self.exists(str(path))
except (NoNodeError, NoAuthError):
stat = None
return stat |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reconnect(self):
""" forces a reconnect by shutting down the connected socket return True if the reconnect happened, False otherwise """ |
state_change_event = self.handler.event_object()
def listener(state):
if state is KazooState.SUSPENDED:
state_change_event.set()
self.add_listener(listener)
self._connection._socket.shutdown(socket.SHUT_RDWR)
state_change_event.wait(1)
if ... |
<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_by_server(self, hosts):
"""Returns the output of dump for each server. :param hosts: comma separated lists of members of the ZK ensemble. :returns: A di... |
dump_by_endpoint = {}
for endpoint in self._to_endpoints(hosts):
try:
out = self.cmd([endpoint], "dump")
except self.CmdFailed as ex:
out = ""
dump_by_endpoint[endpoint] = out
return dump_by_endpoint |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ephemerals_info(self, hosts):
"""Returns ClientInfo per path. :param hosts: comma separated lists of members of the ZK ensemble. :returns: A dictionary of (p... |
info_by_path, info_by_id = {}, {}
for server_endpoint, dump in self.dump_by_server(hosts).items():
server_ip, server_port = server_endpoint
sid = None
for line in dump.split("\n"):
mat = self.SESSION_REGEX.match(line)
if mat:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sessions_info(self, hosts):
"""Returns ClientInfo per session. :param hosts: comma separated lists of members of the ZK ensemble. :returns: A dictionary of (... |
info_by_id = {}
for server_endpoint, dump in self.dump_by_server(hosts).items():
server_ip, server_port = server_endpoint
for line in dump.split("\n"):
mat = self.IP_PORT_REGEX.match(line)
if mat is None:
continue
... |
<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, path, verbose=False):
""" if the path isn't being watched, start watching it if it is, stop watching it """ |
if path in self._by_path:
self.remove(path)
else:
self.add(path, verbose) |
<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_string(cls, string, exists=False, asynchronous=False, verbose=False):
""" if exists is bool, then check it either exists or it doesn't. if exists is Non... |
result = cls.parse(string)
if result.scheme not in cls.TYPES:
raise CopyError("Invalid scheme: %s" % (result.scheme))
return cls.TYPES[result.scheme](result, exists, asynchronous, verbose) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zk_walk(self, root_path, branch_path):
""" skip ephemeral znodes since there's no point in copying those """ |
full_path = os.path.join(root_path, branch_path) if branch_path else root_path
try:
children = self.client.get_children(full_path)
except NoNodeError:
children = set()
except NoAuthError:
raise AuthError("read children", full_path)
for child... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_path(self, path_value):
""" this will overwrite dst path - be careful """ |
parent_dir = os.path.dirname(self.path)
try:
os.makedirs(parent_dir)
except OSError:
pass
with open(self.path, "w") as fph:
fph.write(path_value.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 get(self, exclude_recurse=None):
""" Paths matching exclude_recurse will not be recursed. """ |
reqs = Queue()
pending = 1
path = self.path
zk = self.zk
def child_of(path):
return zk.get_children_async(path)
def dispatch(path):
return Request(path, child_of(path))
stat = zk.exists(path)
if stat is None or stat.numChildren ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_type(value, ptype):
""" Convert value to ptype """ |
if ptype == 'str':
return str(value)
elif ptype == 'int':
return int(value)
elif ptype == 'float':
return float(value)
elif ptype == 'bool':
if value.lower() == 'true':
return True
elif value.lower() == 'false':
return False
raise ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_one(cls, keystr):
""" validates one key string """ |
regex = r'%s$' % cls.ALLOWED_KEY
if re.match(regex, keystr) is None:
raise cls.Bad("Bad key syntax for: %s. Should be: key1.key2..." % (keystr))
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 validate(cls, keystr):
""" raises cls.Bad if keys has errors """ |
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
cls.validate_one(cls.extract(k))
else:
# plain keys str
cls.validate_one(keystr) |
<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(cls, obj, keys):
""" fetches the value corresponding to keys from obj """ |
current = obj
for key in keys.split("."):
if type(current) == list:
try:
key = int(key)
except TypeError:
raise cls.Missing(key)
try:
current = current[key]
except (IndexError, K... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(cls, obj, keystr):
""" gets the value corresponding to keys from obj. if keys is a template string, it extrapolates the keys in it """ |
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
v = cls.fetch(obj, cls.extract(k))
keystr = keystr.replace(k, str(v))
value = keystr
else:
# plain keys str
... |
<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(cls, obj, keys, value, fill_list_value=None):
""" sets the value for the given keys on obj. if any of the given keys does not exist, create the intermedi... |
current = obj
keys_list = keys.split(".")
for idx, key in enumerate(keys_list, 1):
if type(current) == list:
# Validate this key works with a list.
try:
key = int(key)
except ValueError:
raise 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 pretty_bytes(num):
""" pretty print the given number of bytes """ |
for unit in ['', 'KB', 'MB', 'GB']:
if num < 1024.0:
if unit == '':
return "%d" % (num)
else:
return "%3.1f%s" % (num, unit)
num /= 1024.0
return "%3.1f%s" % (num, 'TB') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid_ipv4(ip):
""" check if ip is a valid ipv4 """ |
match = _valid_ipv4.match(ip)
if match is None:
return False
octets = match.groups()
if len(octets) != 4:
return False
first = int(octets[0])
if first < 1 or first > 254:
return False
for i in range(1, 4):
octet = int(octets[i])
if octet < 0 or o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid_host(host):
""" check valid hostname """ |
for part in host.split("."):
if not _valid_host_part.match(part):
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 valid_host_with_port(hostport):
""" matches hostname or an IP, optionally with a port """ |
host, port = hostport.rsplit(":", 1) if ":" in hostport else (hostport, None)
# first, validate host or IP
if not valid_ipv4(host) and not valid_host(host):
return False
# now, validate port
if port is not None and not valid_port(port):
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 split(path):
""" splits path into parent, child """ |
if path == '/':
return ('/', None)
parent, child = path.rsplit('/', 1)
if parent == '':
parent = '/'
return (parent, child) |
<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_outliers(group, delta):
""" given a list of values, find those that are apart from the rest by `delta`. the indexes for the outliers is returned, if any... |
with_pos = sorted([pair for pair in enumerate(group)], key=lambda p: p[1])
outliers_start = outliers_end = -1
for i in range(0, len(with_pos) - 1):
cur = with_pos[i][1]
nex = with_pos[i + 1][1]
if nex - cur > delta:
# depending on where we are, outliers are the remaini... |
<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_matching(content, match):
""" filters out lines that don't include match """ |
if match != "":
lines = [line for line in content.split("\n") if match in line]
content = "\n".join(lines)
return content |
<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_remote_db(self):
""" Load remote S3 DB """ |
signature_version = self.settings_dict.get("SIGNATURE_VERSION", "s3v4")
s3 = boto3.resource(
's3',
config=botocore.client.Config(signature_version=signature_version),
)
if '/tmp/' not in self.settings_dict['NAME']:
try:
etag = ''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self, *args, **kwargs):
""" Engine closed, copy file to DB if it has changed """ |
super(DatabaseWrapper, self).close(*args, **kwargs)
signature_version = self.settings_dict.get("SIGNATURE_VERSION", "s3v4")
s3 = boto3.resource(
's3',
config=botocore.client.Config(signature_version=signature_version),
)
try:
with open(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 id(self):
# pylint: disable=invalid-name,too-many-branches,too-many-return-statements """Return a unique id for the detected chip, if any.""" |
# There are some times we want to trick the platform detection
# say if a raspberry pi doesn't have the right ID, or for testing
try:
return os.environ['BLINKA_FORCECHIP']
except KeyError: # no forced chip, continue with testing!
pass
# Special case, if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _linux_id(self):
"""Attempt to detect the CPU on a computer running the Linux kernel.""" |
linux_id = None
hardware = self.detector.get_cpuinfo_field("Hardware")
if hardware is None:
vendor_id = self.detector.get_cpuinfo_field("vendor_id")
if vendor_id in ("GenuineIntel", "AuthenticAMD"):
linux_id = GENERIC_X86
compatible = 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 id(self):
"""Return a unique id for the detected board, if any.""" |
# There are some times we want to trick the platform detection
# say if a raspberry pi doesn't have the right ID, or for testing
try:
return os.environ['BLINKA_FORCEBOARD']
except KeyError: # no forced board, continue with testing!
pass
chip_id = self.de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pi_id(self):
"""Try to detect id of a Raspberry Pi.""" |
# Check for Pi boards:
pi_rev_code = self._pi_rev_code()
if pi_rev_code:
for model, codes in _PI_REV_CODES.items():
if pi_rev_code in codes:
return model
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 _pi_rev_code(self):
"""Attempt to find a Raspberry Pi revision code for this board.""" |
# 2708 is Pi 1
# 2709 is Pi 2
# 2835 is Pi 3 (or greater) on 4.9.x kernel
# Anything else is not a Pi.
if self.detector.chip.id != ap_chip.BCM2XXX:
# Something else, not a Pi.
return None
return self.detector.get_cpuinfo_field('Revision') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _beaglebone_id(self):
"""Try to detect id of a Beaglebone.""" |
try:
with open("/sys/bus/nvmem/devices/0-00500/nvmem", "rb") as eeprom:
eeprom_bytes = eeprom.read(16)
except FileNotFoundError:
return None
if eeprom_bytes[:4] != b'\xaaU3\xee':
return None
id_string = eeprom_bytes[4:].decode("ascii... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tegra_id(self):
"""Try to detect the id of aarch64 board.""" |
board_value = self.detector.get_device_model()
if 'tx1' in board_value:
return JETSON_TX1
elif 'quill' in board_value:
return JETSON_TX2
elif 'xavier' in board_value:
return JETSON_XAVIER
elif 'nano' in board_value:
return JETSON_N... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def any_embedded_linux(self):
"""Check whether the current board is any embedded Linux device.""" |
return self.any_raspberry_pi or self.any_beaglebone or \
self.any_orange_pi or self.any_giant_board or self.any_jetson_board |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def middleware(request, handler):
""" Main middleware function, deals with all the X-Ray segment logic """ |
# Create X-Ray headers
xray_header = construct_xray_header(request.headers)
# Get name of service or generate a dynamic one from host
name = calculate_segment_name(request.headers['host'].split(':', 1)[0], xray_recorder)
sampling_req = {
'host': request.headers['host'],
'method': 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 to_id(self):
""" Convert TraceId object to a string. """ |
return "%s%s%s%s%s" % (TraceId.VERSION, TraceId.DELIMITER,
format(self.start_time, 'x'),
TraceId.DELIMITER, self.__number) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpatch():
""" Unpatch any previously patched modules. This operation is idempotent. """ |
_PATCHED_MODULES.discard('httplib')
setattr(httplib, PATCH_FLAG, False)
# _send_request encapsulates putrequest, putheader[s], and endheaders
unwrap(httplib.HTTPConnection, '_send_request')
unwrap(httplib.HTTPConnection, 'getresponse')
unwrap(httplib.HTTPResponse, 'read') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def task_factory(loop, coro):
""" Task factory function Fuction closely mirrors the logic inside of asyncio.BaseEventLoop.create_task. Then if there is a current... |
task = asyncio.Task(coro, loop=loop)
if task._source_traceback: # flake8: noqa
del task._source_traceback[-1] # flake8: noqa
# Share context with new task if possible
current_task = asyncio.Task.current_task(loop=loop)
if current_task is not None and hasattr(current_task, 'context'):
... |
<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(self, sampling_req):
""" Determines whether or not this sampling rule applies to the incoming request based on some of the request's parameters. Any ``... |
if sampling_req is None:
return False
host = sampling_req.get('host', None)
method = sampling_req.get('method', None)
path = sampling_req.get('path', None)
service = sampling_req.get('service', None)
service_type = sampling_req.get('service_type', 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 merge(self, rule):
""" Migrate all stateful attributes from the old rule """ |
with self._lock:
self._request_count = rule.request_count
self._borrow_count = rule.borrow_count
self._sampled_count = rule.sampled_count
self._reservoir = rule.reservoir
rule.reservoir = 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 borrow_or_take(self, now, can_borrow):
""" Decide whether to borrow or take one quota from the reservoir. Return ``False`` if it can neither borrow nor take.... |
with self._lock:
return self._borrow_or_take(now, can_borrow) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self, end_time=None):
""" Close the trace entity by setting `end_time` and flip the in progress flag to False. :param int end_time: Epoch in seconds. I... |
self._check_ended()
if end_time:
self.end_time = end_time
else:
self.end_time = time.time()
self.in_progress = 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 add_subsegment(self, subsegment):
""" Add input subsegment as a child subsegment. """ |
self._check_ended()
subsegment.parent_id = self.id
self.subsegments.append(subsegment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_http_meta(self, key, value):
""" Add http related metadata. :param str key: Currently supported keys are: * url * method * user_agent * client_ip * statu... |
self._check_ended()
if value is None:
return
if key == http.STATUS:
if isinstance(value, string_types):
value = int(value)
self.apply_status_code(value)
if key in http.request_keys:
if 'request' not in self.http:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_annotation(self, key, value):
""" Annotate segment or subsegment with a key-value pair. Annotations will be indexed for later search query. :param str ke... |
self._check_ended()
if not isinstance(key, string_types):
log.warning("ignoring non string type annotation key with type %s.", type(key))
return
if not isinstance(value, annotation_value_types):
log.warning("ignoring unsupported annotation value type %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 put_metadata(self, key, value, namespace='default'):
""" Add metadata to segment or subsegment. Metadata is not indexed but can be later retrieved by BatchGe... |
self._check_ended()
if not isinstance(namespace, string_types):
log.warning("ignoring non string type metadata namespace")
return
if namespace.startswith('AWS.'):
log.warning("Prefix 'AWS.' is reserved, drop metadata with namespace %s", namespace)
... |
<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_exception(self, exception, stack, remote=False):
""" Add an exception to trace entities. :param Exception exception: the catched exception. :param list s... |
self._check_ended()
self.add_fault_flag()
if hasattr(exception, '_recorded'):
setattr(self, 'cause', getattr(exception, '_cause_id'))
return
exceptions = []
exceptions.append(Throwable(exception, stack, remote))
self.cause['exceptions'] = excep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self):
""" Serialize to JSON document that can be accepted by the X-Ray backend service. It uses jsonpickle to perform serialization. """ |
try:
return jsonpickle.encode(self, unpicklable=False)
except Exception:
log.exception("got an exception during serialization") |
<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_empty_properties(self, properties):
""" Delete empty properties before serialization to avoid extra keys with empty values in the output json. """ |
if not self.parent_id:
del properties['parent_id']
if not self.subsegments:
del properties['subsegments']
if not self.aws:
del properties['aws']
if not self.http:
del properties['http']
if not self.cause:
del properties... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload_settings(*args, **kwargs):
""" Reload X-Ray user settings upon Django server hot restart """ |
global settings
setting, value = kwargs['setting'], kwargs['value']
if setting == XRAY_NAMESPACE:
settings = XRaySettings(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 add_subsegment(self, subsegment):
""" Add input subsegment as a child subsegment and increment reference counter and total subsegments counter. """ |
super(Segment, self).add_subsegment(subsegment)
self.increment() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_subsegment(self, subsegment):
""" Remove the reference of input subsegment. """ |
super(Segment, self).remove_subsegment(subsegment)
self.decrement_subsegments_size() |
<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_user(self, user):
""" set user of a segment. One segment can only have one user. User is indexed and can be later queried. """ |
super(Segment, self)._check_ended()
self.user = user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_rule_name(self, rule_name):
""" Add the matched centralized sampling rule name if a segment is sampled because of that rule. This method should be only u... |
if not self.aws.get('xray', None):
self.aws['xray'] = {}
self.aws['xray']['sampling_rule_name'] = rule_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 inject_trace_header(headers, entity):
""" Extract trace id, entity id and sampling decision from the input entity and inject these information to headers. :p... |
if not entity:
return
if hasattr(entity, 'type') and entity.type == 'subsegment':
header = entity.parent_segment.get_origin_trace_header()
else:
header = entity.get_origin_trace_header()
data = header.data if header else None
to_insert = TraceHeader(
root=entity.tr... |
<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_sampling_decision(trace_header, recorder, sampling_req):
""" Return 1 or the matched rule name if should sample and 0 if should not. The sampling d... |
if trace_header.sampled is not None and trace_header.sampled != '?':
return trace_header.sampled
elif not recorder.sampling:
return 1
else:
decision = recorder.sampler.should_trace(sampling_req)
return decision if decision else 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 construct_xray_header(headers):
""" Construct a ``TraceHeader`` object from dictionary headers of the incoming request. This method should always return a ``... |
header_str = headers.get(http.XRAY_HEADER) or headers.get(http.ALT_XRAY_HEADER)
if header_str:
return TraceHeader.from_header_str(header_str)
else:
return TraceHeader() |
<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_segment_name(host_name, recorder):
""" Returns the segment name based on recorder configuration and input host name. This is a helper generally use... |
if recorder.dynamic_naming:
return recorder.dynamic_naming.get_name(host_name)
else:
return recorder.service |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_response_header(origin_header, segment):
""" Prepare a trace header to be inserted into response based on original header and the request segment. ""... |
if origin_header and origin_header.sampled == '?':
new_header = TraceHeader(root=segment.trace_id,
sampled=segment.sampled)
else:
new_header = TraceHeader(root=segment.trace_id)
return new_header.to_header_str() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_snake_case(name):
""" Convert the input string to snake-cased string. """ |
s1 = first_cap_re.sub(r'\1_\2', name)
# handle acronym words
return all_cap_re.sub(r'\1_\2', s1).lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch():
""" Patch botocore client so it generates subsegments when calling AWS services. """ |
if hasattr(botocore.client, '_xray_enabled'):
return
setattr(botocore.client, '_xray_enabled', True)
wrapt.wrap_function_wrapper(
'botocore.client',
'BaseClient._make_api_call',
_xray_traced_botocore,
)
wrapt.wrap_function_wrapper(
'botocore.endpoint',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, sampling=None, plugins=None, context_missing=None, sampling_rules=None, daemon_address=None, service=None, context=None, emitter=None, streami... |
if sampling is not None:
self.sampling = sampling
if sampler:
self.sampler = sampler
if service:
self.service = os.getenv(TRACING_NAME_KEY, service)
if sampling_rules:
self._load_sampling_rules(sampling_rules)
if emitter:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def begin_segment(self, name=None, traceid=None, parent_id=None, sampling=None):
""" Begin a segment on the current thread and return it. The recorder only keeps... |
seg_name = name or self.service
if not seg_name:
raise SegmentNameMissingException("Segment name is required.")
# Sampling decision is None if not sampled.
# In a sampled case it could be either a string or 1
# depending on if centralized or local sampling rule take... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_segment(self, end_time=None):
""" End the current segment and send it to X-Ray daemon if it is ready to send. Ready means segment and all its subsegments... |
self.context.end_segment(end_time)
segment = self.current_segment()
if segment and segment.ready_to_send():
self._send_segment() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current_segment(self):
""" Return the currently active segment. In a multithreading environment, this will make sure the segment returned is the one created ... |
entity = self.get_trace_entity()
if self._is_subsegment(entity):
return entity.parent_segment
else:
return entity |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def begin_subsegment(self, name, namespace='local'):
""" Begin a new subsegment. If there is open subsegment, the newly created subsegment will be the child of l... |
segment = self.current_segment()
if not segment:
log.warning("No segment found, cannot begin subsegment %s." % name)
return None
if not segment.sampled:
subsegment = DummySubsegment(segment, name)
else:
subsegment = Subsegment(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 end_subsegment(self, end_time=None):
""" End the current active subsegment. If this is the last one open under its parent segment, the entire segment will be... |
if not self.context.end_subsegment(end_time):
return
# if segment is already close, we check if we can send entire segment
# otherwise we check if we need to stream some subsegments
if self.current_segment().ready_to_send():
self._send_segment()
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_annotation(self, key, value):
""" Annotate current active trace entity with a key-value pair. Annotations will be indexed for later search query. :param ... |
entity = self.get_trace_entity()
if entity and entity.sampled:
entity.put_annotation(key, 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 put_metadata(self, key, value, namespace='default'):
""" Add metadata to the current active trace entity. Metadata is not indexed but can be later retrieved ... |
entity = self.get_trace_entity()
if entity and entity.sampled:
entity.put_metadata(key, value, namespace) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stream_subsegments(self):
""" Stream all closed subsegments to the daemon and remove reference to the parent segment. No-op for a not sampled segment. """ |
segment = self.current_segment()
if self.streaming.is_eligible(segment):
self.streaming.stream(segment, self._stream_subsegment_out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send_segment(self):
""" Send the current segment to X-Ray daemon if it is present and sampled, then clean up context storage. The emitter will handle failur... |
segment = self.current_segment()
if not segment:
return
if segment.sampled:
self.emitter.send_entity(segment)
self.clear_trace_entities() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def applies(self, host, method, path):
""" Determines whether or not this sampling rule applies to the incoming request based on some of the request's parameters... |
return (not host or wildcard_match(self.host, host)) \
and (not method or wildcard_match(self.method, method)) \
and (not path or wildcard_match(self.path, 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 ready(self):
""" Configure global XRay recorder based on django settings under XRAY_RECORDER namespace. This method could be called twice during server start... |
if not settings.AWS_XRAY_TRACING_NAME:
raise SegmentNameMissingException('Segment name is required.')
xray_recorder.configure(
daemon_address=settings.AWS_XRAY_DAEMON_ADDRESS,
sampling=settings.SAMPLING,
sampling_rules=settings.SAMPLING_RULES,
... |
<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):
""" Start rule poller and target poller once X-Ray daemon address and context manager is in place. """ |
if not global_sdk_config.sdk_enabled():
return
with self._lock:
if not self._started:
self._rule_poller.start()
self._target_poller.start()
self._started = 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 should_trace(self, sampling_req=None):
""" Return the matched sampling rule name if the sampler finds one and decide to sample. If no sampling rule matched, ... |
if not global_sdk_config.sdk_enabled():
return False
if not self._started:
self.start() # only front-end that actually uses the sampler spawns poller threads
now = int(time.time())
if sampling_req and not sampling_req.get('service_type', None):
samp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch():
"""Patch PynamoDB so it generates subsegements when calling DynamoDB.""" |
import pynamodb
if hasattr(botocore.vendored.requests.sessions, '_xray_enabled'):
return
setattr(botocore.vendored.requests.sessions, '_xray_enabled', True)
wrapt.wrap_function_wrapper(
'botocore.vendored.requests.sessions',
'Session.send',
_xray_traced_pynamodb,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_segment(self, end_time=None):
""" End the current active segment. :param int end_time: epoch in seconds. If not specified the current system time will be... |
entity = self.get_trace_entity()
if not entity:
log.warning("No segment to end")
return
if self._is_subsegment(entity):
entity.parent_segment.close(end_time)
else:
entity.close(end_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 put_subsegment(self, subsegment):
""" Store the subsegment created by ``xray_recorder`` to the context. If you put a new subsegment while there is already an... |
entity = self.get_trace_entity()
if not entity:
log.warning("Active segment or subsegment not found. Discarded %s." % subsegment.name)
return
entity.add_subsegment(subsegment)
self._local.entities.append(subsegment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_subsegment(self, end_time=None):
""" End the current active segment. Return False if there is no subsegment to end. :param int end_time: epoch in seconds... |
subsegment = self.get_trace_entity()
if self._is_subsegment(subsegment):
subsegment.close(end_time)
self._local.entities.pop()
return True
else:
log.warning("No subsegment to end.")
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 handle_context_missing(self):
""" Called whenever there is no trace entity to access or mutate. """ |
if self.context_missing == 'RUNTIME_ERROR':
log.error(MISSING_SEGMENT_MSG)
raise SegmentNotFoundException(MISSING_SEGMENT_MSG)
else:
log.error(MISSING_SEGMENT_MSG) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_in_lambda():
""" Return None if SDK is not loaded in AWS Lambda worker. Otherwise drop a touch file and return a lambda context. """ |
if not os.getenv(LAMBDA_TASK_ROOT_KEY):
return None
try:
os.mkdir(TOUCH_FILE_DIR)
except OSError:
log.debug('directory %s already exists', TOUCH_FILE_DIR)
try:
f = open(TOUCH_FILE_PATH, 'w+')
f.close()
# utime force second parameter in python2.7
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _refresh_context(self):
""" Get current facade segment. To prevent resource leaking in Lambda worker, every time there is segment present, we compare its tra... |
header_str = os.getenv(LAMBDA_TRACE_HEADER_KEY)
trace_header = TraceHeader.from_header_str(header_str)
if not global_sdk_config.sdk_enabled():
trace_header._sampled = False
segment = getattr(self._local, 'segment', None)
if segment:
# Ensure customers 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 _initialize_context(self, trace_header):
""" Create a facade segment based on environment variables set by AWS Lambda and initialize storage for subsegments.... |
sampled = None
if not global_sdk_config.sdk_enabled():
# Force subsequent subsegments to be disabled and turned into DummySegments.
sampled = False
elif trace_header.sampled == 0:
sampled = False
elif trace_header.sampled == 1:
sampled = T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_sdk_enabled(cls, value):
""" Modifies the enabled flag if the "AWS_XRAY_SDK_ENABLED" environment variable is not set, otherwise, set the enabled flag to ... |
# Environment Variables take precedence over hardcoded configurations.
if cls.XRAY_ENABLED_KEY in os.environ:
cls.__SDK_ENABLED = str(os.getenv(cls.XRAY_ENABLED_KEY, 'true')).lower() != 'false'
else:
if type(value) == bool:
cls.__SDK_ENABLED = 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 _xray_register_type_fix(wrapped, instance, args, kwargs):
"""Send the actual connection or curser to register type.""" |
our_args = list(copy.copy(args))
if len(our_args) == 2 and isinstance(our_args[1], (XRayTracedConn, XRayTracedCursor)):
our_args[1] = our_args[1].__wrapped__
return wrapped(*our_args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_header_str(cls, header):
""" Create a TraceHeader object from a tracing header string extracted from a http request headers. """ |
if not header:
return cls()
try:
params = header.strip().split(HEADER_DELIMITER)
header_dict = {}
data = {}
for param in params:
entry = param.split('=')
key = entry[0]
if key in (ROOT, 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 to_header_str(self):
""" Convert to a tracing header string that can be injected to outgoing http request headers. """ |
h_parts = []
if self.root:
h_parts.append(ROOT + '=' + self.root)
if self.parent:
h_parts.append(PARENT + '=' + self.parent)
if self.sampled is not None:
h_parts.append(SAMPLE + '=' + str(self.sampled))
if self.data:
for key in sel... |
<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_name(self, host_name):
""" Returns the segment name based on the input host name. """ |
if wildcard_match(self._pattern, host_name):
return host_name
else:
return self._fallback |
<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_daemon_address(self, address):
""" Set up UDP ip and port from the raw daemon address string using ``DaemonConfig`` class utlities. """ |
if address:
daemon_config = DaemonConfig(address)
self._ip, self._port = daemon_config.udp_ip, daemon_config.udp_port |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch():
""" Patch aiobotocore client so it generates subsegments when calling AWS services. """ |
if hasattr(aiobotocore.client, '_xray_enabled'):
return
setattr(aiobotocore.client, '_xray_enabled', True)
wrapt.wrap_function_wrapper(
'aiobotocore.client',
'AioBaseClient._make_api_call',
_xray_traced_aiobotocore,
)
wrapt.wrap_function_wrapper(
'aiobotoco... |
<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_eligible(self, segment):
""" A segment is eligible to have its children subsegments streamed if it is sampled and it breaches streaming threshold. """ |
if not segment or not segment.sampled:
return False
return segment.get_total_subsegments_size() > self.streaming_threshold |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stream(self, entity, callback):
""" Stream out all eligible children of the input entity. :param entity: The target entity to be streamed. :param callback: T... |
with self._lock:
self._stream(entity, callback) |
<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_bind(bind):
"""Parses a connection string and creates SQL trace metadata""" |
if isinstance(bind, Connection):
engine = bind.engine
else:
engine = bind
m = re.match(r"Engine\((.*?)\)", str(engine))
if m is not None:
u = urlparse(m.group(1))
# Add Scheme to uses_netloc or // will be missing from url.
uses_netloc.append(u.scheme)
saf... |
<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_subsegment(self, subsegment):
""" Add input subsegment as a child subsegment and increment reference counter and total subsegments counter of the parent ... |
super(Subsegment, self).add_subsegment(subsegment)
self.parent_segment.increment() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_subsegment(self, subsegment):
""" Remove input subsegment from child subsegemnts and decrement parent segment total subsegments count. :param Subsegme... |
super(Subsegment, self).remove_subsegment(subsegment)
self.parent_segment.decrement_subsegments_size() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.