text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Calls listen repeatedly until listen returns something else than None.
<END_TASK>
<USER_TASK:>
Description:
def listen_until_return(self, *temporary_handlers, timeout=0):
"""Calls listen repeatedly until listen returns something else than None.
Then returns listen's result. If timeout is not zero listen_until_return
stops after timeout seconds and returns None.""" |
start = time.time()
while timeout == 0 or time.time() - start < timeout:
res = self.listen(*temporary_handlers)
if res is not None:
return res |
<SYSTEM_TASK:>
Waits till one key was pressed n times.
<END_TASK>
<USER_TASK:>
Description:
def wait_for_n_keypresses(self, key, n=1):
"""Waits till one key was pressed n times.
:param key: the key to be pressed as defined by pygame. E.g.
pygame.K_LEFT for the left arrow key
:type key: int
:param n: number of repetitions till the function returns
:type n: int
""" |
my_const = "key_consumed"
counter = 0
def keypress_listener(e): return my_const \
if e.type == pygame.KEYDOWN and e.key == key \
else EventConsumerInfo.DONT_CARE
while counter < n:
if self.listen(keypress_listener) == my_const:
counter += 1 |
<SYSTEM_TASK:>
Waits until one of the specified keys was pressed, and returns
<END_TASK>
<USER_TASK:>
Description:
def wait_for_keys(self, *keys, timeout=0):
"""Waits until one of the specified keys was pressed, and returns
which key was pressed.
:param keys: iterable of integers of pygame-keycodes, or simply
multiple keys passed via multiple arguments
:type keys: iterable
:param timeout: number of seconds to wait till the function returns
:type timeout: float
:returns: The keycode of the pressed key, or None in case of timeout
:rtype: int
""" |
if len(keys) == 1 and _is_iterable(keys[0]):
keys = keys[0]
return self.listen_until_return(Handler.key_press(keys), timeout=timeout) |
<SYSTEM_TASK:>
The same as wait_for_keys, but returns a frozen_set which contains
<END_TASK>
<USER_TASK:>
Description:
def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys,
timeout=0):
"""The same as wait_for_keys, but returns a frozen_set which contains
the pressed key, and the modifier keys.
:param modifiers_to_check: iterable of modifiers for which the function
will check whether they are pressed
:type modifiers: Iterable[int]""" |
set_mods = pygame.key.get_mods()
return frozenset.union(
frozenset([self.wait_for_keys(*keys, timeout=timeout)]),
EventListener._contained_modifiers(set_mods, modifiers_to_check)) |
<SYSTEM_TASK:>
Does not support the full range of ways rar can split
<END_TASK>
<USER_TASK:>
Description:
def _find_all_first_files(self, item):
"""
Does not support the full range of ways rar can split
as it'd require reading the file to ensure you are using the
correct way.
""" |
for listed_item in item.list():
new_style = re.findall(r'(?i)\.part(\d+)\.rar^', listed_item.id)
if new_style:
if int(new_style[0]) == 1:
yield 'new', listed_item
elif listed_item.id.lower().endswith('.rar'):
yield 'old', listed_item |
<SYSTEM_TASK:>
Send birdsite message.
<END_TASK>
<USER_TASK:>
Description:
def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send birdsite message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
""" |
try:
status = self.api.update_status(text)
self.ldebug(f"Status object from tweet: {status}.")
return [TweetRecord(record_data={"tweet_id": status._json["id"], "text": text})]
except tweepy.TweepError as e:
return [self.handle_error(
message=(f"Bot {self.bot_name} encountered an error when "
f"sending post {text} without media:\n{e}\n"),
error=e)] |
<SYSTEM_TASK:>
Upload media to birdsite,
<END_TASK>
<USER_TASK:>
Description:
def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[]
) -> List[OutputRecord]:
"""
Upload media to birdsite,
and send status and media,
and captions if present.
:param text: tweet text.
:param files: list of files to upload with post.
:param captions: list of captions to include as alt-text with files.
:returns: list of output records,
each corresponding to either a single post,
or an error.
""" |
# upload media
media_ids = None
try:
self.ldebug(f"Uploading files {files}.")
media_ids = [self.api.media_upload(file).media_id_string for file in files]
except tweepy.TweepError as e:
return [self.handle_error(
message=f"Bot {self.bot_name} encountered an error when uploading {files}:\n{e}\n",
error=e)]
# apply captions, if present
self._handle_caption_upload(media_ids=media_ids, captions=captions)
# send status
try:
status = self.api.update_status(status=text, media_ids=media_ids)
self.ldebug(f"Status object from tweet: {status}.")
return [TweetRecord(record_data={
"tweet_id": status._json["id"],
"text": text,
"media_ids": media_ids,
"captions": captions,
"files": files
})]
except tweepy.TweepError as e:
return [self.handle_error(
message=(f"Bot {self.bot_name} encountered an error when "
f"sending post {text} with media ids {media_ids}:\n{e}\n"),
error=e)] |
<SYSTEM_TASK:>
Send DM to owner if something happens.
<END_TASK>
<USER_TASK:>
Description:
def send_dm_sos(self, message: str) -> None:
"""
Send DM to owner if something happens.
:param message: message to send to owner.
:returns: None.
""" |
if self.owner_handle:
try:
# twitter changed the DM API and tweepy (as of 2019-03-08)
# has not adapted.
# fixing with
# https://github.com/tweepy/tweepy/issues/1081#issuecomment-423486837
owner_id = self.api.get_user(screen_name=self.owner_handle).id
event = {
"event": {
"type": "message_create",
"message_create": {
"target": {
"recipient_id": f"{owner_id}",
},
"message_data": {
"text": message
}
}
}
}
self._send_direct_message_new(event)
except tweepy.TweepError as de:
self.lerror(f"Error trying to send DM about error!: {de}")
else:
self.lerror("Can't send DM SOS, no owner handle.") |
<SYSTEM_TASK:>
Handle uploading all captions.
<END_TASK>
<USER_TASK:>
Description:
def _handle_caption_upload(
self,
*,
media_ids: List[str],
captions: Optional[List[str]],
) -> None:
"""
Handle uploading all captions.
:param media_ids: media ids of uploads to attach captions to.
:param captions: captions to be attached to those media ids.
:returns: None.
""" |
if captions is None:
captions = []
if len(media_ids) > len(captions):
captions.extend([self.default_caption_message] * (len(media_ids) - len(captions)))
for i, media_id in enumerate(media_ids):
caption = captions[i]
self._upload_caption(media_id=media_id, caption=caption) |
<SYSTEM_TASK:>
Takes crash data via stdin and generates a Socorro signature
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Takes crash data via stdin and generates a Socorro signature""" |
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
args = parser.parse_args()
generator = SignatureGenerator(debug=args.verbose)
crash_data = json.loads(sys.stdin.read())
ret = generator.generate(crash_data)
print(json.dumps(ret, indent=2)) |
<SYSTEM_TASK:>
Update internel configuration dict with config and recheck
<END_TASK>
<USER_TASK:>
Description:
def add_config(self, config):
"""
Update internel configuration dict with config and recheck
""" |
for attr in self.__fixed_attrs:
if attr in config:
raise Exception("cannot set '%s' outside of init", attr)
# pre checkout
stages = config.get('stages', None)
if stages:
self.stages = stages
# maybe pre checkout
# validate options
self.__dry_run = config.get('dry_run', False)
self.system = str.lower(platform.system())
self.__start = config.get('start', None)
self.__end = config.get('end', None)
self.__only = config.get('only', None)
self.__build_docs = config.get('build_docs', False)
self.__chatty = config.get('chatty', False)
self.__clean = config.get('clean', False)
self.__devel = config.get('devel', False)
self.__debug = config.get('debug', False)
self.__skip_libcheck = config.get('skip_libcheck', False)
self.__debuginfo = config.get('debuginfo', False)
self.__release = config.get('release', False)
self.__skip_unit = config.get('skip_unit', False)
self.__static = config.get('static', False)
self.__make_dash_j = int(config.get('j', 0))
self.__target_only = config.get('target_only', None)
bits = config.get('bits', None)
if bits:
self.bits = int(bits)
else:
self.bits = self.sys_bits
self.compiler = config.get('compiler', None)
self.test_config = config.get('test_config', '-')
if not self.test_config:
self.test_config = '-'
self.use_ccache = config.get('use_ccache', False)
self.tmpl_engine = config.get('tmpl_engine', 'jinja2')
self.__write_codec = config.get('write_codec', None)
self.__codec = None
# TODO move out of init
if not config.get('skip_env_check', False):
if "LD_LIBRARY_PATH" in os.environ:
raise Exception("environment variable LD_LIBRARY_PATH is set")
self.check_config() |
<SYSTEM_TASK:>
called after config was modified to sanity check
<END_TASK>
<USER_TASK:>
Description:
def check_config(self):
"""
called after config was modified to sanity check
raises on error
""" |
# sanity checks - no config access past here
if not getattr(self, 'stages', None):
raise NotImplementedError("member variable 'stages' must be defined")
# start at stage
if self.__start:
self.__stage_start = self.find_stage(self.__start)
else:
self.__stage_start = 0
# end at stage
if self.__end:
self.__stage_end = self.find_stage(self.__end) + 1
self.opt_end = self.__end
else:
self.__stage_end = len(self.stages)
# only stage
if self.__only:
if self.__start or self.__end:
raise Exception(
"stage option 'only' cannot be used with start or end")
self.__stage_start = self.find_stage(self.__only)
self.__stage_end = self.__stage_start + 1
if self.__devel:
self.__devel = True
# force deploy skip
if self.__stage_end >= len(self.stages):
self.status_msg("removing deploy stage for development build")
# XXX self.__stage_end = self.__stage_end - 1
if self.stage_start >= self.stage_end:
raise Exception("start and end produce no stages")
if self.bits not in [32, 64]:
raise Exception(
"can't do a %d bit build: unknown build process" % self.bits)
if self.bits == 64 and not self.is_64b:
raise Exception(
"this machine is not 64 bit, cannot perform 64 bit build")
if self.system == 'windows':
self.compilertag = 'vc10'
elif self.system == 'linux':
self.compilertag = 'gcc44'
else:
raise RuntimeError("can't decide compilertag on " + self.system)
self.build_suffix = ''
if not self.is_unixy:
if self.__static:
runtime = 'MT'
else:
runtime = 'MD'
if self.__release:
self.configuration_name = 'Release'
else:
runtime += 'd'
self.configuration_name = 'Debug'
self.build_suffix = '-' + runtime
self.runtime = runtime
else:
self.configuration_name = 'CFNAME_INVALID_ON_LINUX'
self.runtime = 'RUNTIME_INVALID_ON_LINUX'
if self.test_config != '-':
self.test_config = os.path.abspath(self.test_config)
# split version
if self.version:
ver = self.version.split('.')
self.version_major = int(ver[0])
self.version_minor = int(ver[1])
self.version_patch = int(ver[2])
if(len(ver) == 4):
self.version_build = int(ver[3]) |
<SYSTEM_TASK:>
called after Defintion was loaded to sanity check
<END_TASK>
<USER_TASK:>
Description:
def check_definition(self):
"""
called after Defintion was loaded to sanity check
raises on error
""" |
if not self.write_codec:
self.__write_codec = self.defined.data_ext
# TODO need to add back a class scope target limited for subprojects with sub target sets
targets = self.get_defined_targets()
if self.__target_only:
if self.__target_only not in targets:
raise RuntimeError("invalid target '%s'" % self.__target_only)
self.targets = [self.__target_only]
else:
self.targets = targets |
<SYSTEM_TASK:>
find datafile and load them from codec
<END_TASK>
<USER_TASK:>
Description:
def load_datafile(self, name, search_path=None, **kwargs):
"""
find datafile and load them from codec
""" |
if not search_path:
search_path = self.define_dir
self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))
return codec.load_datafile(name, search_path, **kwargs) |
<SYSTEM_TASK:>
run all configured stages
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" run all configured stages """ |
self.sanity_check()
# TODO - check for devel
# if not self.version:
# raise Exception("no version")
# XXX check attr exist
if not self.release_environment:
raise Exception("no instance name")
time_start = time.time()
cwd = os.getcwd()
who = getpass.getuser()
self._make_outdirs()
append_notices = ""
if hasattr(self, 'opt_end'):
append_notices = ". shortened push, only to %s stage" % self.opt_end
if self.is_devel:
append_notices += ". devel build"
if hasattr(self, 'append_notices'):
append_notices += self.append_notices
line = "%s %s %s by %s%s" % (
sys.argv[0], self.version, self.release_environment, who, append_notices)
b = 'deploy begin %s' % line
e = 'deploy done %s' % line
if self.chatty:
self.alact(b)
ok = False
stage_passed = None
try:
for stage in self.stages[self.stage_start:self.stage_end]:
self.debug_msg("stage %s starting" % (stage,))
getattr(self, stage)()
self.chdir(cwd)
stage_passed = stage
self.debug_msg("stage %s complete" % (stage,))
ok = True
finally:
if not ok:
if self.chatty:
if not stage_passed:
self.alact(
'deploy failed %s. completed no stages' % line)
else:
self.alact('deploy failed %s. completed %s' %
(line, stage_passed))
self.status_msg('[OK]')
if self.chatty:
self.alact('%s in %0.3f sec' % (e, time.time() - time_start))
return 0 |
<SYSTEM_TASK:>
Repair a corrupted IterationRecord with a specific known issue.
<END_TASK>
<USER_TASK:>
Description:
def _repair(record: Dict[str, Any]) -> Dict[str, Any]:
"""Repair a corrupted IterationRecord with a specific known issue.""" |
output_records = record.get("output_records")
if record.get("_type", None) == "IterationRecord" and output_records is not None:
birdsite_record = output_records.get("birdsite")
# check for the bug
if isinstance(birdsite_record, dict) and birdsite_record.get("_type") == "IterationRecord":
# get to the bottom of the corrupted record
failed = False
while birdsite_record.get("_type") == "IterationRecord":
sub_record = birdsite_record.get("output_records")
if sub_record is None:
failed = True
break
birdsite_record = sub_record.get("birdsite")
if birdsite_record is None:
failed = True
break
if failed:
return record
# add type
birdsite_record["_type"] = TweetRecord.__name__
# lift extra keys, just in case
if "extra_keys" in birdsite_record:
record_extra_values = record.get("extra_keys", {})
for key, value in birdsite_record["extra_keys"].items():
if key not in record_extra_values:
record_extra_values[key] = value
record["extra_keys"] = record_extra_values
del birdsite_record["extra_keys"]
output_records["birdsite"] = birdsite_record
# pull that correct record up to the top level, fixing corruption
record["output_records"] = output_records
return record |
<SYSTEM_TASK:>
Post text-only to all outputs.
<END_TASK>
<USER_TASK:>
Description:
def send(
self,
*args: str,
text: str=None,
) -> IterationRecord:
"""
Post text-only to all outputs.
:param args: positional arguments.
expected: text to send as message in post.
keyword text argument is preferred over this.
:param text: text to send as message in post.
:returns: new record of iteration
""" |
if text is not None:
final_text = text
else:
if len(args) == 0:
raise BotSkeletonException(("Please provide text either as a positional arg or "
"as a keyword arg (text=TEXT)"))
else:
final_text = args[0]
# TODO there could be some annotation stuff here.
record = IterationRecord(extra_keys=self.extra_keys)
for key, output in self.outputs.items():
if output["active"]:
self.log.info(f"Output {key} is active, calling send on it.")
entry: Any = output["obj"]
output_result = entry.send(text=final_text)
record.output_records[key] = output_result
else:
self.log.info(f"Output {key} is inactive. Not sending.")
self.history.append(record)
self.update_history()
return record |
<SYSTEM_TASK:>
Post with one media item to all outputs.
<END_TASK>
<USER_TASK:>
Description:
def send_with_one_media(
self,
*args: str,
text: str=None,
file: str=None,
caption: str=None,
) -> IterationRecord:
"""
Post with one media item to all outputs.
Provide filename so outputs can handle their own uploads.
:param args: positional arguments.
expected:
text to send as message in post.
file to be uploaded.
caption to be paired with file.
keyword arguments preferred over positional ones.
:param text: text to send as message in post.
:param file: file to be uploaded in post.
:param caption: caption to be uploaded alongside file.
:returns: new record of iteration
""" |
final_text = text
if final_text is None:
if len(args) < 1:
raise TypeError(("Please provide either positional argument "
"TEXT, or keyword argument text=TEXT"))
else:
final_text = args[0]
final_file = file
if final_file is None:
if len(args) < 2:
raise TypeError(("Please provide either positional argument "
"FILE, or keyword argument file=FILE"))
else:
final_file = args[1]
# this arg is ACTUALLY optional,
# so the pattern is changed.
final_caption = caption
if final_caption is None:
if len(args) >= 3:
final_caption = args[2]
# TODO more error checking like this.
if final_caption is None or final_caption == "":
captions:List[str] = []
else:
captions = [final_caption]
record = IterationRecord(extra_keys=self.extra_keys)
for key, output in self.outputs.items():
if output["active"]:
self.log.info(f"Output {key} is active, calling media send on it.")
entry: Any = output["obj"]
output_result = entry.send_with_media(text=final_text,
files=[final_file],
captions=captions)
record.output_records[key] = output_result
else:
self.log.info(f"Output {key} is inactive. Not sending with media.")
self.history.append(record)
self.update_history()
return record |
<SYSTEM_TASK:>
Post with several media.
<END_TASK>
<USER_TASK:>
Description:
def send_with_many_media(
self,
*args: str,
text: str=None,
files: List[str]=None,
captions: List[str]=[],
) -> IterationRecord:
"""
Post with several media.
Provide filenames so outputs can handle their own uploads.
:param args: positional arguments.
expected:
text to send as message in post.
files to be uploaded.
captions to be paired with files.
keyword arguments preferred over positional ones.
:param text: text to send as message in post.
:param files: files to be uploaded in post.
:param captions: captions to be uploaded alongside files.
:returns: new record of iteration
""" |
if text is None:
if len(args) < 1:
raise TypeError(("Please provide either required positional argument "
"TEXT, or keyword argument text=TEXT"))
else:
final_text = args[0]
else:
final_text = text
if files is None:
if len(args) < 2:
raise TypeError(("Please provide either positional argument "
"FILES, or keyword argument files=FILES"))
else:
final_files = list(args[1:])
else:
final_files = files
# captions have never been permitted to be provided as positional args
# (kind of backed myself into that)
# so they just get defaulted and it's fine.
record = IterationRecord(extra_keys=self.extra_keys)
for key, output in self.outputs.items():
if output["active"]:
self.log.info(f"Output {key} is active, calling media send on it.")
entry: Any = output["obj"]
output_result = entry.send_with_media(text=final_text,
files=final_files,
captions=captions)
record.output_records[key] = output_result
else:
self.log.info(f"Output {key} is inactive. Not sending with media.")
self.history.append(record)
self.update_history()
return record |
<SYSTEM_TASK:>
Go to sleep for the duration of self.delay.
<END_TASK>
<USER_TASK:>
Description:
def nap(self) -> None:
"""
Go to sleep for the duration of self.delay.
:returns: None
""" |
self.log.info(f"Sleeping for {self.delay} seconds.")
for _ in progress.bar(range(self.delay)):
time.sleep(1) |
<SYSTEM_TASK:>
Store some extra value in the messaging storage.
<END_TASK>
<USER_TASK:>
Description:
def store_extra_info(self, key: str, value: Any) -> None:
"""
Store some extra value in the messaging storage.
:param key: key of dictionary entry to add.
:param value: value of dictionary entry to add.
:returns: None
""" |
self.extra_keys[key] = value |
<SYSTEM_TASK:>
Store several extra values in the messaging storage.
<END_TASK>
<USER_TASK:>
Description:
def store_extra_keys(self, d: Dict[str, Any]) -> None:
"""
Store several extra values in the messaging storage.
:param d: dictionary entry to merge with current self.extra_keys.
:returns: None
""" |
new_dict = dict(self.extra_keys, **d)
self.extra_keys = new_dict.copy() |
<SYSTEM_TASK:>
Load messaging history from disk to self.
<END_TASK>
<USER_TASK:>
Description:
def load_history(self) -> List["IterationRecord"]:
"""
Load messaging history from disk to self.
:returns: List of iteration records comprising history.
""" |
if path.isfile(self.history_filename):
with open(self.history_filename, "r") as f:
try:
dicts = json.load(f)
except json.decoder.JSONDecodeError as e:
self.log.error(f"Got error \n{e}\n decoding JSON history, overwriting it.\n"
f"Former history available in {self.history_filename}.bak")
copyfile(self.history_filename, f"{self.history_filename}.bak")
return []
history: List[IterationRecord] = []
for hdict_pre in dicts:
if "_type" in hdict_pre and hdict_pre["_type"] == IterationRecord.__name__:
# repair any corrupted entries
hdict = _repair(hdict_pre)
record = IterationRecord.from_dict(hdict)
history.append(record)
# Be sure to handle legacy tweetrecord-only histories.
# Assume anything without our new _type (which should have been there from the
# start, whoops) is a legacy history.
else:
item = IterationRecord()
# Lift extra keys up to upper record (if they exist).
extra_keys = hdict_pre.pop("extra_keys", {})
item.extra_keys = extra_keys
hdict_obj = TweetRecord.from_dict(hdict_pre)
# Lift timestamp up to upper record.
item.timestamp = hdict_obj.timestamp
item.output_records["birdsite"] = hdict_obj
history.append(item)
self.log.debug(f"Loaded history:\n {history}")
return history
else:
return [] |
<SYSTEM_TASK:>
Set up all output methods. Provide them credentials and anything else they need.
<END_TASK>
<USER_TASK:>
Description:
def _setup_all_outputs(self) -> None:
"""Set up all output methods. Provide them credentials and anything else they need.""" |
# The way this is gonna work is that we assume an output should be set up iff it has a
# credentials_ directory under our secrets dir.
for key in self.outputs.keys():
credentials_dir = path.join(self.secrets_dir, f"credentials_{key}")
# special-case birdsite for historical reasons.
if key == "birdsite" and not path.isdir(credentials_dir) \
and path.isfile(path.join(self.secrets_dir, "CONSUMER_KEY")):
credentials_dir = self.secrets_dir
if path.isdir(credentials_dir):
output_skeleton = self.outputs[key]
output_skeleton["active"] = True
obj: Any = output_skeleton["obj"]
obj.cred_init(secrets_dir=credentials_dir, log=self.log, bot_name=self.bot_name)
output_skeleton["obj"] = obj
self.outputs[key] = output_skeleton |
<SYSTEM_TASK:>
Create the directory of a fully qualified file name if it does not exist.
<END_TASK>
<USER_TASK:>
Description:
def make_dir(fname):
"""
Create the directory of a fully qualified file name if it does not exist.
:param fname: File name
:type fname: string
Equivalent to these Bash shell commands:
.. code-block:: bash
$ fname="${HOME}/mydir/myfile.txt"
$ dir=$(dirname "${fname}")
$ mkdir -p "${dir}"
:param fname: Fully qualified file name
:type fname: string
""" |
file_path, fname = os.path.split(os.path.abspath(fname))
if not os.path.exists(file_path):
os.makedirs(file_path) |
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def normalize_windows_fname(fname, _force=False):
r"""
Fix potential problems with a Microsoft Windows file name.
Superfluous backslashes are removed and unintended escape sequences are
converted to their equivalent (presumably correct and intended)
representation, for example :code:`r'\\\\x07pps'` is transformed to
:code:`r'\\\\\\\\apps'`. A file name is considered network shares if the
file does not include a drive letter and they start with a double backslash
(:code:`'\\\\\\\\'`)
:param fname: File name
:type fname: string
:rtype: string
""" |
if (platform.system().lower() != "windows") and (not _force): # pragma: no cover
return fname
# Replace unintended escape sequences that could be in
# the file name, like "C:\appdata"
rchars = {
"\x07": r"\\a",
"\x08": r"\\b",
"\x0C": r"\\f",
"\x0A": r"\\n",
"\x0D": r"\\r",
"\x09": r"\\t",
"\x0B": r"\\v",
}
ret = ""
for char in os.path.normpath(fname):
ret = ret + rchars.get(char, char)
# Remove superfluous double backslashes
network_share = False
tmp = None
network_share = fname.startswith(r"\\")
while tmp != ret:
tmp, ret = ret, ret.replace(r"\\\\", r"\\")
ret = ret.replace(r"\\\\", r"\\")
# Put back network share if needed
if network_share:
ret = r"\\" + ret.lstrip(r"\\")
return ret |
<SYSTEM_TASK:>
Enforce line separators to be the right one depending on platform.
<END_TASK>
<USER_TASK:>
Description:
def _homogenize_linesep(line):
"""Enforce line separators to be the right one depending on platform.""" |
token = str(uuid.uuid4())
line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "")
return line.replace(token, os.linesep) |
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def incfile(fname, fpointer, lrange=None, sdir=None):
r"""
Return a Python source file formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param fname: File name, relative to environment variable
:bash:`PKG_DOC_DIR`
:type fname: string
:param fpointer: Output function pointer. Normally is :code:`cog.out` but
other functions can be used for debugging
:type fpointer: function object
:param lrange: Line range to include, similar to Sphinx
`literalinclude <http://www.sphinx-doc.org/en/master/usage
/restructuredtext/directives.html
#directive-literalinclude>`_ directive
:type lrange: string
:param sdir: Source file directory. If None the :bash:`PKG_DOC_DIR`
environment variable is used if it is defined, otherwise
the directory where the module is located is used
:type sdir: string
For example:
.. code-block:: python
def func():
\"\"\"
This is a docstring. This file shows how to use it:
.. =[=cog
.. import docs.support.incfile
.. docs.support.incfile.incfile('func_example.py', cog.out)
.. =]=
.. code-block:: python
# func_example.py
if __name__ == '__main__':
func()
.. =[=end=]=
\"\"\"
return 'This is func output'
""" |
# pylint: disable=R0914
# Read file
file_dir = (
sdir
if sdir
else os.environ.get("PKG_DOC_DIR", os.path.abspath(os.path.dirname(__file__)))
)
fname = os.path.join(file_dir, fname)
with open(fname, "r") as fobj:
lines = fobj.readlines()
# Eliminate spurious carriage returns in Microsoft Windows
lines = [_homogenize_linesep(line) for line in lines]
# Parse line specification
inc_lines = (
_proc_token(lrange, len(lines)) if lrange else list(range(1, len(lines) + 1))
)
# Produce output
fpointer(".. code-block:: python" + os.linesep)
fpointer(os.linesep)
for num, line in enumerate(lines):
if num + 1 in inc_lines:
fpointer(
" " + line.replace("\t", " ").rstrip() + os.linesep
if line.strip()
else os.linesep
)
fpointer(os.linesep) |
<SYSTEM_TASK:>
Read input gene history file into the database.
<END_TASK>
<USER_TASK:>
Description:
def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col):
"""
Read input gene history file into the database.
Note that the arguments tax_id_col, id_col and symbol_col have been
converted into 0-based column indexes.
""" |
# Make sure that tax_id is not "" or " "
if not tax_id or tax_id.isspace():
raise Exception("Input tax_id is blank")
# Make sure that tax_id exists in Organism table in the database.
try:
organism = Organism.objects.get(taxonomy_id=tax_id)
except Organism.DoesNotExist:
raise Exception('Input tax_id %s does NOT exist in Organism table. '
'Please add it into Organism table first.' % tax_id)
if tax_id_col < 0 or id_col < 0 or symbol_col < 0:
raise Exception(
'tax_id_col, id_col and symbol_col must be positive integers')
for line_index, line in enumerate(file_handle):
if line.startswith('#'): # Skip comment lines.
continue
fields = line.rstrip().split('\t')
# Check input column numbers.
chk_col_numbers(line_index + 1, len(fields), tax_id_col, id_col,
symbol_col)
# Skip lines whose tax_id's do not match input tax_id.
if tax_id != fields[tax_id_col]:
continue
entrez_id = fields[id_col]
# If the gene already exists in database, set its "obsolete" attribute
# to True; otherwise create a new obsolete Gene record in database.
try:
gene = Gene.objects.get(entrezid=entrez_id)
if not gene.obsolete:
gene.obsolete = True
gene.save()
except Gene.DoesNotExist:
Gene.objects.create(entrezid=entrez_id, organism=organism,
systematic_name=fields[symbol_col],
obsolete=True) |
<SYSTEM_TASK:>
Send mastodon message.
<END_TASK>
<USER_TASK:>
Description:
def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send mastodon message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
""" |
try:
status = self.api.status_post(status=text)
return [TootRecord(record_data={
"toot_id": status["id"],
"text": text
})]
except mastodon.MastodonError as e:
return [self.handle_error((f"Bot {self.bot_name} encountered an error when "
f"sending post {text} without media:\n{e}\n"),
e)] |
<SYSTEM_TASK:>
Upload media to mastodon,
<END_TASK>
<USER_TASK:>
Description:
def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[],
) -> List[OutputRecord]:
"""
Upload media to mastodon,
and send status and media,
and captions if present.
:param text: post text.
:param files: list of files to upload with post.
:param captions: list of captions to include as alt-text with files.
:returns: list of output records,
each corresponding to either a single post,
or an error.
""" |
try:
self.ldebug(f"Uploading files {files}.")
if captions is None:
captions = []
if len(files) > len(captions):
captions.extend([self.default_caption_message] * (len(files) - len(captions)))
media_dicts = []
for i, file in enumerate(files):
caption = captions[i]
media_dicts.append(self.api.media_post(file, description=caption))
self.ldebug(f"Media ids {media_dicts}")
except mastodon.MastodonError as e:
return [self.handle_error(
f"Bot {self.bot_name} encountered an error when uploading {files}:\n{e}\n", e
)]
try:
status = self.api.status_post(status=text, media_ids=media_dicts)
self.ldebug(f"Status object from toot: {status}.")
return [TootRecord(record_data={
"toot_id": status["id"],
"text": text,
"media_ids": media_dicts,
"captions": captions
})]
except mastodon.MastodonError as e:
return [self.handle_error((f"Bot {self.bot_name} encountered an error when "
f"sending post {text} with media dicts {media_dicts}:"
f"\n{e}\n"),
e)] |
<SYSTEM_TASK:>
Request a callback for value modification.
<END_TASK>
<USER_TASK:>
Description:
def listen(self, you):
"""
Request a callback for value modification.
Parameters
----------
you : object
An instance having ``__call__`` attribute.
""" |
self._listeners.append(you)
self.raw.talk_to(you) |
<SYSTEM_TASK:>
must be applied to all inner functions that return contexts.
<END_TASK>
<USER_TASK:>
Description:
def _inner_func_anot(func):
"""must be applied to all inner functions that return contexts.
Wraps all instances of pygame.Surface in the input in Surface""" |
@wraps(func)
def new_func(*args):
return func(*_lmap(_wrap_surface, args))
return new_func |
<SYSTEM_TASK:>
Draws a cross centered in the target area
<END_TASK>
<USER_TASK:>
Description:
def Cross(width=3, color=0):
"""Draws a cross centered in the target area
:param width: width of the lines of the cross in pixels
:type width: int
:param color: color of the lines of the cross
:type color: pygame.Color
""" |
return Overlay(Line("h", width, color), Line("v", width, color)) |
<SYSTEM_TASK:>
Unifies loading of fonts.
<END_TASK>
<USER_TASK:>
Description:
def Font(name=None, source="sys", italic=False, bold=False, size=20):
"""Unifies loading of fonts.
:param name: name of system-font or filepath, if None is passed the default
system-font is loaded
:type name: str
:param source: "sys" for system font, or "file" to load a file
:type source: str
""" |
assert source in ["sys", "file"]
if not name:
return pygame.font.SysFont(pygame.font.get_default_font(),
size, bold=bold, italic=italic)
if source == "sys":
return pygame.font.SysFont(name,
size, bold=bold, italic=italic)
else:
f = pygame.font.Font(name, size)
f.set_italic(italic)
f.set_bold(bold)
return f |
<SYSTEM_TASK:>
Creates a padding by the remaining space after scaling the content.
<END_TASK>
<USER_TASK:>
Description:
def from_scale(scale_w, scale_h=None):
"""Creates a padding by the remaining space after scaling the content.
E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and
Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0)
because the content would not be scaled (since scale_h=1) and therefore
there would be no vertical padding.
If scale_h is not specified scale_h=scale_w is used as default
:param scale_w: horizontal scaling factors
:type scale_w: float
:param scale_h: vertical scaling factor
:type scale_h: float
""" |
if not scale_h: scale_h = scale_w
w_padding = [(1 - scale_w) * 0.5] * 2
h_padding = [(1 - scale_h) * 0.5] * 2
return Padding(*w_padding, *h_padding) |
<SYSTEM_TASK:>
Test if the argument is a string representing a valid hexadecimal digit.
<END_TASK>
<USER_TASK:>
Description:
def ishex(obj):
"""
Test if the argument is a string representing a valid hexadecimal digit.
:param obj: Object
:type obj: any
:rtype: boolean
""" |
return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits) |
<SYSTEM_TASK:>
Pass an API result down the pipeline
<END_TASK>
<USER_TASK:>
Description:
def receive(self, data, api_context):
"""Pass an API result down the pipeline""" |
self.log.debug(f"Putting data on the pipeline: {data}")
result = {
"api_contexts": self.api_contexts,
"api_context": api_context,
"strategy": dict(), # Shared strategy data
"result": data,
"log_level": api_context["log_level"],
}
self.strat.execute(self.strategy_context_schema().load(result).data) |
<SYSTEM_TASK:>
Course this node belongs to
<END_TASK>
<USER_TASK:>
Description:
def course(self):
"""
Course this node belongs to
""" |
course = self.parent
while course.parent:
course = course.parent
return course |
<SYSTEM_TASK:>
get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default
<END_TASK>
<USER_TASK:>
Description:
def title(self):
"""
get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default
value from stud.ip is used.
""" |
tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title
return secure_filename(tmp) |
<SYSTEM_TASK:>
list of all documents find in subtrees of this node
<END_TASK>
<USER_TASK:>
Description:
def deep_documents(self):
"""
list of all documents find in subtrees of this node
""" |
tree = []
for entry in self.contents:
if isinstance(entry, Document):
tree.append(entry)
else:
tree += entry.deep_documents
return tree |
<SYSTEM_TASK:>
run a get request against an url. Returns the response which can optionally be streamed
<END_TASK>
<USER_TASK:>
Description:
def _get(self, route, stream=False):
"""
run a get request against an url. Returns the response which can optionally be streamed
""" |
log.debug("Running GET request against %s" % route)
return r.get(self._url(route), auth=c.auth, stream=stream) |
<SYSTEM_TASK:>
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename.
<END_TASK>
<USER_TASK:>
Description:
def download_document(self, document: Document, overwrite=True, path=None):
"""
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename.
If overwrite is set the local version will be overwritten if the file was changed on studip since the last check
""" |
if not path:
path = os.path.join(os.path.expanduser(c["base_path"]), document.path)
if (self.modified(document) and overwrite) or not os.path.exists(join(path, document.title)):
log.info("Downloading %s" % join(path, document.title))
file = self._get('/api/documents/%s/download' % document.id, stream=True)
os.makedirs(path, exist_ok=True)
with open(join(path, document.title), 'wb') as f:
shutil.copyfileobj(file.raw, f) |
<SYSTEM_TASK:>
get the semester of a node
<END_TASK>
<USER_TASK:>
Description:
def get_semester_title(self, node: BaseNode):
"""
get the semester of a node
""" |
log.debug("Getting Semester Title for %s" % node.course.id)
return self._get_semester_from_id(node.course.semester) |
<SYSTEM_TASK:>
use the base_url and auth data from the configuration to list all courses the user is subscribed to
<END_TASK>
<USER_TASK:>
Description:
def get_courses(self):
"""
use the base_url and auth data from the configuration to list all courses the user is subscribed to
""" |
log.info("Listing Courses...")
courses = json.loads(self._get('/api/courses').text)["courses"]
courses = [Course.from_response(course) for course in courses]
log.debug("Courses: %s" % [str(entry) for entry in courses])
return courses |
<SYSTEM_TASK:>
Minimize a scalar function using Brent's method.
<END_TASK>
<USER_TASK:>
Description:
def _minimize_scalar(
self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True
):
"""
Minimize a scalar function using Brent's method.
Parameters
----------
verbose : bool
``True`` for verbose output; ``False`` otherwise.
""" |
from tqdm import tqdm
from numpy import asarray
from brent_search import minimize as brent_minimize
variables = self._variables.select(fixed=False)
if len(variables) != 1:
raise ValueError("The number of variables must be equal to one.")
var = variables[variables.names()[0]]
progress = tqdm(desc=desc, disable=not verbose)
def func(x):
progress.update(1)
var.value = x
return self.__sign * self.value()
r = asarray(
brent_minimize(func, a=var.bounds[0], b=var.bounds[1], rtol=rtol, atol=atol)
)
var.value = r[0]
progress.close() |
<SYSTEM_TASK:>
turn a string to CamelCase, omitting non-word characters
<END_TASK>
<USER_TASK:>
Description:
def camelify(self):
"""turn a string to CamelCase, omitting non-word characters""" |
outstring = self.titleify(allwords=True)
outstring = re.sub(r"&[^;]+;", " ", outstring)
outstring = re.sub(r"\W+", "", outstring)
return String(outstring) |
<SYSTEM_TASK:>
takes a string and makes a title from it
<END_TASK>
<USER_TASK:>
Description:
def titleify(self, lang='en', allwords=False, lastword=True):
"""takes a string and makes a title from it""" |
if lang in LOWERCASE_WORDS:
lc_words = LOWERCASE_WORDS[lang]
else:
lc_words = []
s = str(self).strip()
l = re.split(r"([_\W]+)", s)
for i in range(len(l)):
l[i] = l[i].lower()
if (
allwords == True
or i == 0
or (lastword == True and i == len(l) - 1)
or l[i].lower() not in lc_words
):
w = l[i]
if len(w) > 1:
w = w[0].upper() + w[1:]
else:
w = w.upper()
l[i] = w
s = "".join(l)
return String(s) |
<SYSTEM_TASK:>
Turn a CamelCase string into a string with spaces
<END_TASK>
<USER_TASK:>
Description:
def camelsplit(self):
"""Turn a CamelCase string into a string with spaces""" |
s = str(self)
for i in range(len(s) - 1, -1, -1):
if i != 0 and (
(s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper())
or (s[i].isnumeric() and s[i - 1].isalpha())
):
s = s[:i] + ' ' + s[i:]
return String(s.strip()) |
<SYSTEM_TASK:>
Pyramid pluggable and discoverable function.
<END_TASK>
<USER_TASK:>
Description:
def includeme(config):
"""Pyramid pluggable and discoverable function.""" |
global_settings = config.registry.settings
settings = local_settings(global_settings, PREFIX)
try:
file = settings['file']
except KeyError:
raise KeyError("Must supply '{}.file' configuration value "
"in order to configure logging via '{}'."
.format(PREFIX, PROJECT))
with open(file, 'r') as f:
logging_config = yaml.load(f)
dictConfig(logging_config)
# Enable transit logging?
if asbool(settings.get('transit_logging.enabled?', False)):
config.add_tween('pyramid_sawing.main.TransitLogger') |
<SYSTEM_TASK:>
Executed on each scheduled iteration
<END_TASK>
<USER_TASK:>
Description:
def call(self, callname, arguments=None):
"""Executed on each scheduled iteration""" |
# See if a method override exists
action = getattr(self.api, callname, None)
if action is None:
try:
action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
except AttributeError:
action = callname
if not callable(action):
request = self._generate_request(action, arguments)
if action is None:
return self._generate_result(
callname, self.api.call(*call_args(callname, arguments)))
return self._generate_result(
callname, self.api.call(*call_args(action, arguments)))
request = self._generate_request(callname, arguments)
return self._generate_result(callname, action(request)) |
<SYSTEM_TASK:>
Generate a request object for delivery to the API
<END_TASK>
<USER_TASK:>
Description:
def _generate_request(self, callname, request):
"""Generate a request object for delivery to the API""" |
# Retrieve path from API class
schema = self.api.request_schema()
schema.context['callname'] = callname
return schema.dump(request).data.get("payload") |
<SYSTEM_TASK:>
Generate a results object for delivery to the context object
<END_TASK>
<USER_TASK:>
Description:
def _generate_result(self, callname, result):
"""Generate a results object for delivery to the context object""" |
# Retrieve path from API class
schema = self.api.result_schema()
schema.context['callname'] = callname
self.callback(schema.load(result), self.context) |
<SYSTEM_TASK:>
create a key for index by converting index into a base-26 number, using A-Z as the characters.
<END_TASK>
<USER_TASK:>
Description:
def excel_key(index):
"""create a key for index by converting index into a base-26 number, using A-Z as the characters.""" |
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) |
<SYSTEM_TASK:>
Takes a text and drops all non-printable and non-ascii characters and
<END_TASK>
<USER_TASK:>
Description:
def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped
""" |
# Strip all non-ascii and non-printable characters
text = ''.join([c for c in text if c in ALLOWED_CHARS])
return text |
<SYSTEM_TASK:>
Parses a source file thing and returns the file name
<END_TASK>
<USER_TASK:>
Description:
def parse_source_file(source_file):
"""Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the filename or ``None`` if it couldn't determine one
""" |
if not source_file:
return None
vcsinfo = source_file.split(':')
if len(vcsinfo) == 4:
# These are repositories or cloud file systems (e.g. hg, git, s3)
vcstype, root, vcs_source_file, revision = vcsinfo
return vcs_source_file
if len(vcsinfo) == 2:
# These are directories on someone's Windows computer and vcstype is a
# file system (e.g. "c:", "d:", "f:")
vcstype, vcs_source_file = vcsinfo
return vcs_source_file
if source_file.startswith('/'):
# These are directories on OSX or Linux
return source_file
# We have no idea what this is, so return None
return None |
<SYSTEM_TASK:>
Predicate for whether the open token is in an exception context
<END_TASK>
<USER_TASK:>
Description:
def _is_exception(exceptions, before_token, after_token, token):
"""Predicate for whether the open token is in an exception context
:arg exceptions: list of strings or None
:arg before_token: the text of the function up to the token delimiter
:arg after_token: the text of the function after the token delimiter
:arg token: the token (only if we're looking at a close delimiter
:returns: bool
""" |
if not exceptions:
return False
for s in exceptions:
if before_token.endswith(s):
return True
if s in token:
return True
return False |
<SYSTEM_TASK:>
Collapses the text between two delimiters in a frame function value
<END_TASK>
<USER_TASK:>
Description:
def collapse(
function,
open_string,
close_string,
replacement='',
exceptions=None,
):
"""Collapses the text between two delimiters in a frame function value
This collapses the text between two delimiters and either removes the text
altogether or replaces it with a replacement string.
There are certain contexts in which we might not want to collapse the text
between two delimiters. These are denoted as "exceptions" and collapse will
check for those exception strings occuring before the token to be replaced
or inside the token to be replaced.
Before::
IPC::ParamTraits<nsTSubstring<char> >::Write(IPC::Message *,nsTSubstring<char> const &)
^ ^ open token
exception string occurring before open token
Inside::
<rayon_core::job::HeapJob<BODY> as rayon_core::job::Job>::execute
^ ^^^^ exception string inside token
open token
:arg function: the function value from a frame to collapse tokens in
:arg open_string: the open delimiter; e.g. ``(``
:arg close_string: the close delimiter; e.g. ``)``
:arg replacement: what to replace the token with; e.g. ``<T>``
:arg exceptions: list of strings denoting exceptions where we don't want
to collapse the token
:returns: new function string with tokens collapsed
""" |
collapsed = []
open_count = 0
open_token = []
for i, char in enumerate(function):
if not open_count:
if char == open_string and not _is_exception(exceptions, function[:i], function[i + 1:], ''): # noqa
open_count += 1
open_token = [char]
else:
collapsed.append(char)
else:
if char == open_string:
open_count += 1
open_token.append(char)
elif char == close_string:
open_count -= 1
open_token.append(char)
if open_count == 0:
token = ''.join(open_token)
if _is_exception(exceptions, function[:i], function[i + 1:], token):
collapsed.append(''.join(open_token))
else:
collapsed.append(replacement)
open_token = []
else:
open_token.append(char)
if open_count:
token = ''.join(open_token)
if _is_exception(exceptions, function[:i], function[i + 1:], token):
collapsed.append(''.join(open_token))
else:
collapsed.append(replacement)
return ''.join(collapsed) |
<SYSTEM_TASK:>
Takes the function value from a frame and drops prefix and return type
<END_TASK>
<USER_TASK:>
Description:
def drop_prefix_and_return_type(function):
"""Takes the function value from a frame and drops prefix and return type
For example::
static void * Allocator<MozJemallocBase>::malloc(unsigned __int64)
^ ^^^^^^ return type
prefix
This gets changes to this::
Allocator<MozJemallocBase>::malloc(unsigned __int64)
This tokenizes on space, but takes into account types, generics, traits,
function arguments, and other parts of the function signature delimited by
things like `', <>, {}, [], and () for both C/C++ and Rust.
After tokenizing, this returns the last token since that's comprised of the
function name and its arguments.
:arg function: the function value in a frame to drop bits from
:returns: adjusted function value
""" |
DELIMITERS = {
'(': ')',
'{': '}',
'[': ']',
'<': '>',
'`': "'"
}
OPEN = DELIMITERS.keys()
CLOSE = DELIMITERS.values()
# The list of tokens accumulated so far
tokens = []
# Keeps track of open delimiters so we can match and close them
levels = []
# The current token we're building
current = []
for i, char in enumerate(function):
if char in OPEN:
levels.append(char)
current.append(char)
elif char in CLOSE:
if levels and DELIMITERS[levels[-1]] == char:
levels.pop()
current.append(char)
else:
# This is an unmatched close.
current.append(char)
elif levels:
current.append(char)
elif char == ' ':
tokens.append(''.join(current))
current = []
else:
current.append(char)
if current:
tokens.append(''.join(current))
while len(tokens) > 1 and tokens[-1].startswith(('(', '[clone')):
# It's possible for the function signature to have a space between
# the function name and the parenthesized arguments or [clone ...]
# thing. If that's the case, we join the last two tokens. We keep doing
# that until the last token is nice.
#
# Example:
#
# somefunc (int arg1, int arg2)
# ^
# somefunc(int arg1, int arg2) [clone .cold.111]
# ^
# somefunc(int arg1, int arg2) [clone .cold.111] [clone .cold.222]
# ^ ^
tokens = tokens[:-2] + [' '.join(tokens[-2:])]
return tokens[-1] |
<SYSTEM_TASK:>
Takes crash data via args and generates a Socorro signature
<END_TASK>
<USER_TASK:>
Description:
def main(argv=None):
"""Takes crash data via args and generates a Socorro signature
""" |
parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
parser.add_argument(
'--format', help='specify output format: csv, text (default)'
)
parser.add_argument(
'--different-only', dest='different', action='store_true',
help='limit output to just the signatures that changed',
)
parser.add_argument(
'crashids', metavar='crashid', nargs='*', help='crash id to generate signatures for'
)
if argv is None:
args = parser.parse_args()
else:
args = parser.parse_args(argv)
if args.format == 'csv':
outputter = CSVOutput
else:
outputter = TextOutput
api_token = os.environ.get('SOCORRO_API_TOKEN', '')
generator = SignatureGenerator()
if args.crashids:
crashids_iterable = args.crashids
elif not sys.stdin.isatty():
# If a script is piping to this script, then isatty() returns False. If
# there is no script piping to this script, then isatty() returns True
# and if we do list(sys.stdin), it'll block waiting for input.
crashids_iterable = list(sys.stdin)
else:
crashids_iterable = []
if not crashids_iterable:
parser.print_help()
return 0
with outputter() as out:
for crash_id in crashids_iterable:
crash_id = crash_id.strip()
resp = fetch('/RawCrash/', crash_id, api_token)
if resp.status_code == 404:
out.warning('%s: does not exist.' % crash_id)
continue
if resp.status_code == 429:
out.warning('API rate limit reached. %s' % resp.content)
# FIXME(willkg): Maybe there's something better we could do here. Like maybe wait a
# few minutes.
return 1
if resp.status_code == 500:
out.warning('HTTP 500: %s' % resp.content)
continue
raw_crash = resp.json()
# If there's an error in the raw crash, then something is wrong--probably with the API
# token. So print that out and exit.
if 'error' in raw_crash:
out.warning('Error fetching raw crash: %s' % raw_crash['error'])
return 1
resp = fetch('/ProcessedCrash/', crash_id, api_token)
if resp.status_code == 404:
out.warning('%s: does not have processed crash.' % crash_id)
continue
if resp.status_code == 429:
out.warning('API rate limit reached. %s' % resp.content)
# FIXME(willkg): Maybe there's something better we could do here. Like maybe wait a
# few minutes.
return 1
if resp.status_code == 500:
out.warning('HTTP 500: %s' % resp.content)
continue
processed_crash = resp.json()
# If there's an error in the processed crash, then something is wrong--probably with the
# API token. So print that out and exit.
if 'error' in processed_crash:
out.warning('Error fetching processed crash: %s' % processed_crash['error'])
return 1
old_signature = processed_crash['signature']
crash_data = convert_to_crash_data(raw_crash, processed_crash)
result = generator.generate(crash_data)
if not args.different or old_signature != result.signature:
out.data(crash_id, old_signature, result, args.verbose) |
<SYSTEM_TASK:>
Join package and module with a dot.
<END_TASK>
<USER_TASK:>
Description:
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
""" |
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name |
<SYSTEM_TASK:>
Import the given name and return name, obj, parent, mod_name
<END_TASK>
<USER_TASK:>
Description:
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
""" |
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e) |
<SYSTEM_TASK:>
Return the members of mod of the given type
<END_TASK>
<USER_TASK:>
Description:
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
""" |
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items |
<SYSTEM_TASK:>
Return a dict for template rendering
<END_TASK>
<USER_TASK:>
Description:
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
""" |
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var |
<SYSTEM_TASK:>
Generage the rst files
<END_TASK>
<USER_TASK:>
Description:
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
""" |
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix) |
<SYSTEM_TASK:>
Parse the config of the app and initiate the generation process
<END_TASK>
<USER_TASK:>
Description:
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
""" |
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path) |
<SYSTEM_TASK:>
Determine if an object is a real number.
<END_TASK>
<USER_TASK:>
Description:
def _isreal(obj):
"""
Determine if an object is a real number.
Both Python standard data types and Numpy data types are supported.
:param obj: Object
:type obj: any
:rtype: boolean
""" |
# pylint: disable=W0702
if (obj is None) or isinstance(obj, bool):
return False
try:
cond = (int(obj) == obj) or (float(obj) == obj)
except:
return False
return cond |
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def _no_exp(number):
r"""
Convert a number to a string without using scientific notation.
:param number: Number to convert
:type number: integer or float
:rtype: string
:raises: RuntimeError (Argument \`number\` is not valid)
""" |
if isinstance(number, bool) or (not isinstance(number, (int, float))):
raise RuntimeError("Argument `number` is not valid")
mant, exp = _to_scientific_tuple(number)
if not exp:
return str(number)
floating_mant = "." in mant
mant = mant.replace(".", "")
if exp < 0:
return "0." + "0" * (-exp - 1) + mant
if not floating_mant:
return mant + "0" * exp + (".0" if isinstance(number, float) else "")
lfpart = len(mant) - 1
if lfpart < exp:
return (mant + "0" * (exp - lfpart)).rstrip(".")
return mant |
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def _to_scientific_tuple(number):
r"""
Return mantissa and exponent of a number expressed in scientific notation.
Full precision is maintained if the number is represented as a string.
:param number: Number
:type number: integer, float or string
:rtype: Tuple whose first item is the mantissa (*string*) and the second
item is the exponent (*integer*) of the number when expressed in
scientific notation
:raises: RuntimeError (Argument \`number\` is not valid)
""" |
# pylint: disable=W0632
if isinstance(number, bool) or (not isinstance(number, (int, float, str))):
raise RuntimeError("Argument `number` is not valid")
convert = not isinstance(number, str)
# Detect zero and return, simplifies subsequent algorithm
if (convert and (not number)) or (
(not convert) and (not number.strip("0").strip("."))
):
return ("0", 0)
# Break down number into its components, use Decimal type to
# preserve resolution:
# sign : 0 -> +, 1 -> -
# digits: tuple with digits of number
# exp : exponent that gives null fractional part
sign, digits, exp = Decimal(str(number) if convert else number).as_tuple()
mant = (
"{sign}{itg}.{frac}".format(
sign="-" if sign else "",
itg=digits[0],
frac="".join(str(item) for item in digits[1:]),
)
.rstrip("0")
.rstrip(".")
)
exp += len(digits) - 1
return (mant, exp) |
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def normalize(value, series, offset=0):
r"""
Scale a value to the range defined by a series.
:param value: Value to normalize
:type value: number
:param series: List of numbers that defines the normalization range
:type series: list
:param offset: Normalization offset, i.e. the returned value will be in
the range [**offset**, 1.0]
:type offset: number
:rtype: number
:raises:
* RuntimeError (Argument \`offset\` is not valid)
* RuntimeError (Argument \`series\` is not valid)
* RuntimeError (Argument \`value\` is not valid)
* ValueError (Argument \`offset\` has to be in the [0.0, 1.0] range)
* ValueError (Argument \`value\` has to be within the bounds of the
argument \`series\`)
For example::
>>> import pmisc
>>> pmisc.normalize(15, [10, 20])
0.5
>>> pmisc.normalize(15, [10, 20], 0.5)
0.75
""" |
if not _isreal(value):
raise RuntimeError("Argument `value` is not valid")
if not _isreal(offset):
raise RuntimeError("Argument `offset` is not valid")
try:
smin = float(min(series))
smax = float(max(series))
except:
raise RuntimeError("Argument `series` is not valid")
value = float(value)
offset = float(offset)
if not 0 <= offset <= 1:
raise ValueError("Argument `offset` has to be in the [0.0, 1.0] range")
if not smin <= value <= smax:
raise ValueError(
"Argument `value` has to be within the bounds of argument `series`"
)
return offset + ((1.0 - offset) * (value - smin) / (smax - smin)) |
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def per(arga, argb, prec=10):
r"""
Calculate percentage difference between numbers.
If only two numbers are given, the percentage difference between them is
computed. If two sequences of numbers are given (either two lists of
numbers or Numpy vectors), the element-wise percentage difference is
computed. If any of the numbers in the arguments is zero the value returned
is the maximum floating-point number supported by the Python interpreter.
:param arga: First number, list of numbers or Numpy vector
:type arga: float, integer, list of floats or integers, or Numpy vector
of floats or integers
:param argb: Second number, list of numbers or or Numpy vector
:type argb: float, integer, list of floats or integers, or Numpy vector
of floats or integers
:param prec: Maximum length of the fractional part of the result
:type prec: integer
:rtype: Float, list of floats or Numpy vector, depending on the arguments
type
:raises:
* RuntimeError (Argument \`arga\` is not valid)
* RuntimeError (Argument \`argb\` is not valid)
* RuntimeError (Argument \`prec\` is not valid)
* TypeError (Arguments are not of the same type)
""" |
# pylint: disable=C0103,C0200,E1101,R0204
if not isinstance(prec, int):
raise RuntimeError("Argument `prec` is not valid")
a_type = 1 * _isreal(arga) + 2 * (isiterable(arga) and not isinstance(arga, str))
b_type = 1 * _isreal(argb) + 2 * (isiterable(argb) and not isinstance(argb, str))
if not a_type:
raise RuntimeError("Argument `arga` is not valid")
if not b_type:
raise RuntimeError("Argument `argb` is not valid")
if a_type != b_type:
raise TypeError("Arguments are not of the same type")
if a_type == 1:
arga, argb = float(arga), float(argb)
num_min, num_max = min(arga, argb), max(arga, argb)
return (
0
if _isclose(arga, argb)
else (
sys.float_info.max
if _isclose(num_min, 0.0)
else round((num_max / num_min) - 1, prec)
)
)
# Contortions to handle lists and Numpy arrays without explicitly
# having to import numpy
ret = copy.copy(arga)
for num, (x, y) in enumerate(zip(arga, argb)):
if not _isreal(x):
raise RuntimeError("Argument `arga` is not valid")
if not _isreal(y):
raise RuntimeError("Argument `argb` is not valid")
x, y = float(x), float(y)
ret[num] = (
0
if _isclose(x, y)
else (
sys.float_info.max
if _isclose(x, 0.0) or _isclose(y, 0)
else (round((max(x, y) / min(x, y)) - 1, prec))
)
)
return ret |
<SYSTEM_TASK:>
Connect the provided channels
<END_TASK>
<USER_TASK:>
Description:
def connect_channels(self, channels):
"""Connect the provided channels""" |
self.log.info(f"Connecting to channels...")
for chan in channels:
chan.connect(self.sock)
self.log.info(f"\t{chan.channel}") |
<SYSTEM_TASK:>
Set Auth request received from websocket
<END_TASK>
<USER_TASK:>
Description:
def _on_set_auth(self, sock, token):
"""Set Auth request received from websocket""" |
self.log.info(f"Token received: {token}")
sock.setAuthtoken(token) |
<SYSTEM_TASK:>
Message received from websocket
<END_TASK>
<USER_TASK:>
Description:
def _on_auth(self, sock, authenticated): # pylint: disable=unused-argument
"""Message received from websocket""" |
def ack(eventname, error, data): # pylint: disable=unused-argument
"""Ack"""
if error:
self.log.error(f"""OnAuth: {error}""")
else:
self.connect_channels(self.channels)
self.post_conn_cb()
sock.emitack("auth", self.creds, ack) |
<SYSTEM_TASK:>
Error received from websocket
<END_TASK>
<USER_TASK:>
Description:
def _on_connect_error(self, sock, err): # pylint: disable=unused-argument
"""Error received from websocket""" |
if isinstance(err, SystemExit):
self.log.error(f"Shutting down websocket connection")
else:
self.log.error(f"Websocket error: {err}") |
<SYSTEM_TASK:>
Attach a given socket to a channel
<END_TASK>
<USER_TASK:>
Description:
def connect(self, sock):
"""Attach a given socket to a channel""" |
def cbwrap(*args, **kwargs):
"""Callback wrapper; passes in response_type"""
self.callback(self.response_type, *args, **kwargs)
self.sock = sock
self.sock.subscribe(self.channel)
self.sock.onchannel(self.channel, cbwrap) |
<SYSTEM_TASK:>
write all needed state info to filesystem
<END_TASK>
<USER_TASK:>
Description:
def write(self):
""" write all needed state info to filesystem """ |
dumped = self._fax.codec.dump(self.__state, open(self.state_file, 'w')) |
<SYSTEM_TASK:>
returns a list of params that this ConfigTemplate expects to receive
<END_TASK>
<USER_TASK:>
Description:
def expected_param_keys(self):
"""returns a list of params that this ConfigTemplate expects to receive""" |
expected_keys = []
r = re.compile('%\(([^\)]+)\)s')
for block in self.keys():
for key in self[block].keys():
s = self[block][key]
if type(s)!=str: continue
md = re.search(r, s)
while md is not None:
k = md.group(1)
if k not in expected_keys:
expected_keys.append(k)
s = s[md.span()[1]:]
md = re.search(r, s)
return expected_keys |
<SYSTEM_TASK:>
Takes a crash id, pulls down data from Socorro, generates signature data
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Takes a crash id, pulls down data from Socorro, generates signature data""" |
parser = argparse.ArgumentParser(
formatter_class=WrappedTextHelpFormatter,
description=DESCRIPTION
)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
parser.add_argument(
'crashid', help='crash id to generate signatures for'
)
args = parser.parse_args()
api_token = os.environ.get('SOCORRO_API_TOKEN', '')
crash_id = args.crashid.strip()
resp = fetch('/RawCrash/', crash_id, api_token)
if resp.status_code == 404:
printerr('%s: does not exist.' % crash_id)
return 1
if resp.status_code == 429:
printerr('API rate limit reached. %s' % resp.content)
# FIXME(willkg): Maybe there's something better we could do here. Like maybe wait a
# few minutes.
return 1
if resp.status_code == 500:
printerr('HTTP 500: %s' % resp.content)
return 1
raw_crash = resp.json()
# If there's an error in the raw crash, then something is wrong--probably with the API
# token. So print that out and exit.
if 'error' in raw_crash:
print('Error fetching raw crash: %s' % raw_crash['error'], file=sys.stderr)
return 1
resp = fetch('/ProcessedCrash/', crash_id, api_token)
if resp.status_code == 404:
printerr('%s: does not have processed crash.' % crash_id)
return 1
if resp.status_code == 429:
printerr('API rate limit reached. %s' % resp.content)
# FIXME(willkg): Maybe there's something better we could do here. Like maybe wait a
# few minutes.
return 1
if resp.status_code == 500:
printerr('HTTP 500: %s' % resp.content)
return 1
processed_crash = resp.json()
# If there's an error in the processed crash, then something is wrong--probably with the
# API token. So print that out and exit.
if 'error' in processed_crash:
printerr('Error fetching processed crash: %s' % processed_crash['error'])
return 1
crash_data = convert_to_crash_data(raw_crash, processed_crash)
print(json.dumps(crash_data, indent=2)) |
<SYSTEM_TASK:>
Wraps text like HelpFormatter, but doesn't squash lines
<END_TASK>
<USER_TASK:>
Description:
def _fill_text(self, text, width, indent):
"""Wraps text like HelpFormatter, but doesn't squash lines
This makes it easier to do lists and paragraphs.
""" |
parts = text.split('\n\n')
for i, part in enumerate(parts):
# Check to see if it's a bulleted list--if so, then fill each line
if part.startswith('* '):
subparts = part.split('\n')
for j, subpart in enumerate(subparts):
subparts[j] = super(WrappedTextHelpFormatter, self)._fill_text(
subpart, width, indent
)
parts[i] = '\n'.join(subparts)
else:
parts[i] = super(WrappedTextHelpFormatter, self)._fill_text(part, width, indent)
return '\n\n'.join(parts) |
<SYSTEM_TASK:>
Return a dict of services by name
<END_TASK>
<USER_TASK:>
Description:
def get_api_services_by_name(self):
"""Return a dict of services by name""" |
if not self.services_by_name:
self.services_by_name = dict({s.get('name'): s for s in self.conf
.get("api")
.get("services")})
return self.services_by_name |
<SYSTEM_TASK:>
Return a string corresponding to the exception type.
<END_TASK>
<USER_TASK:>
Description:
def _ex_type_str(exobj):
"""Return a string corresponding to the exception type.""" |
regexp = re.compile(r"<(?:\bclass\b|\btype\b)\s+'?([\w|\.]+)'?>")
exc_type = str(exobj)
if regexp.match(exc_type):
exc_type = regexp.match(exc_type).groups()[0]
exc_type = exc_type[11:] if exc_type.startswith("exceptions.") else exc_type
if "." in exc_type:
exc_type = exc_type.split(".")[-1]
return exc_type |
<SYSTEM_TASK:>
Calculate total energy production. Not rounded
<END_TASK>
<USER_TASK:>
Description:
def _production(self):
"""Calculate total energy production. Not rounded""" |
return self._nuclear + self._diesel + self._gas + self._wind + self._combined + self._vapor + self._solar + self._hydraulic + self._carbon + self._waste + self._other |
<SYSTEM_TASK:>
Calculate total energy production. Not Rounded
<END_TASK>
<USER_TASK:>
Description:
def _links(self):
"""Calculate total energy production. Not Rounded""" |
total = 0.0
for value in self.link.values():
total += value
return total |
<SYSTEM_TASK:>
Implement the interface for the adapter object
<END_TASK>
<USER_TASK:>
Description:
def interface(self, context):
"""Implement the interface for the adapter object""" |
self.context = context
self.callback = self.context.get("callback") |
<SYSTEM_TASK:>
Updates the Dict with the given values. Turns internal dicts into Dicts.
<END_TASK>
<USER_TASK:>
Description:
def update(xCqNck7t, **kwargs):
"""Updates the Dict with the given values. Turns internal dicts into Dicts.""" |
def dict_list_val(inlist):
l = []
for i in inlist:
if type(i)==dict:
l.append(Dict(**i))
elif type(i)==list:
l.append(make_list(i))
elif type(i)==bytes:
l.append(i.decode('UTF-8'))
else:
l.append(i)
return l
for k in list(kwargs.keys()):
if type(kwargs[k])==dict:
xCqNck7t[k] = Dict(**kwargs[k])
elif type(kwargs[k])==list:
xCqNck7t[k] = dict_list_val(kwargs[k])
else:
xCqNck7t[k] = kwargs[k] |
<SYSTEM_TASK:>
sort the keys before returning them
<END_TASK>
<USER_TASK:>
Description:
def keys(self, key=None, reverse=False):
"""sort the keys before returning them""" |
ks = sorted(list(dict.keys(self)), key=key, reverse=reverse)
return ks |
<SYSTEM_TASK:>
start the selenium Remote Server.
<END_TASK>
<USER_TASK:>
Description:
def start_server(self):
"""start the selenium Remote Server.""" |
self.__subp = subprocess.Popen(self.command)
#print("\tselenium jar pid[%s] is running." %self.__subp.pid)
time.sleep(2) |
<SYSTEM_TASK:>
Implements two's complement negation.
<END_TASK>
<USER_TASK:>
Description:
def negate_gate(wordlen, input='x', output='~x'):
"""Implements two's complement negation.""" |
neg = bitwise_negate(wordlen, input, "tmp")
inc = inc_gate(wordlen, "tmp", output)
return neg >> inc |
<SYSTEM_TASK:>
Recursively flattens a list.
<END_TASK>
<USER_TASK:>
Description:
def flatten_list(lobj):
"""
Recursively flattens a list.
:param lobj: List to flatten
:type lobj: list
:rtype: list
For example:
>>> import pmisc
>>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7]
""" |
ret = []
for item in lobj:
if isinstance(item, list):
for sub_item in flatten_list(item):
ret.append(sub_item)
else:
ret.append(item)
return ret |
<SYSTEM_TASK:>
load a configuration file. loads default config if file is not found
<END_TASK>
<USER_TASK:>
Description:
def load(self, file=CONFIG_FILE):
"""
load a configuration file. loads default config if file is not found
""" |
if not os.path.exists(file):
print("Config file was not found under %s. Default file has been created" % CONFIG_FILE)
self._settings = yaml.load(DEFAULT_CONFIG, yaml.RoundTripLoader)
self.save(file)
sys.exit()
with open(file, 'r') as f:
self._settings = yaml.load(f, yaml.RoundTripLoader) |
<SYSTEM_TASK:>
Save configuration to provided path as a yaml file
<END_TASK>
<USER_TASK:>
Description:
def save(self, file=CONFIG_FILE):
"""
Save configuration to provided path as a yaml file
""" |
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "w") as f:
yaml.dump(self._settings, f, Dumper=yaml.RoundTripDumper, width=float("inf")) |
<SYSTEM_TASK:>
Create the corresponding index. Will overwrite existing indexes of the same name.
<END_TASK>
<USER_TASK:>
Description:
def create(self):
"""Create the corresponding index. Will overwrite existing indexes of the same name.""" |
body = dict()
if self.mapping is not None:
body['mappings'] = self.mapping
if self.settings is not None:
body['settings'] = self.settings
else:
body['settings'] = self._default_settings()
self.instance.indices.create(self.index, body) |
<SYSTEM_TASK:>
Search the index with a query.
<END_TASK>
<USER_TASK:>
Description:
def search(self, query=None, size=100, unpack=True):
"""Search the index with a query.
Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned.
The default number of hits returned is 100.
""" |
logging.info('Download all documents from index %s.', self.index)
if query is None:
query = self.match_all
results = list()
data = self.instance.search(index=self.index, doc_type=self.doc_type, body=query, size=size)
if unpack:
for items in data['hits']['hits']:
if '_source' in items:
results.append(items['_source'])
else:
results.append(items)
else:
results = data['hits']['hits']
return results |
<SYSTEM_TASK:>
Scan the index with the query.
<END_TASK>
<USER_TASK:>
Description:
def scan_index(self, query: Union[Dict[str, str], None] = None) -> List[Dict[str, str]]:
"""Scan the index with the query.
Will return any number of results above 10'000. Important to note is, that
all the data is loaded into memory at once and returned. This works only with small
data sets. Use scroll otherwise which returns a generator to cycle through the resources
in set chunks.
:param query: The query used to scan the index. Default None will return the entire index.
:returns list of dicts: The list of dictionaries contains all the documents without metadata.
""" |
if query is None:
query = self.match_all
logging.info('Download all documents from index %s with query %s.', self.index, query)
results = list()
data = scan(self.instance, index=self.index, doc_type=self.doc_type, query=query)
for items in data:
if '_source' in items:
results.append(items['_source'])
else:
results.append(items)
return results |
<SYSTEM_TASK:>
Scroll an index with the specified search query.
<END_TASK>
<USER_TASK:>
Description:
def scroll(self, query=None, scroll='5m', size=100, unpack=True):
"""Scroll an index with the specified search query.
Works as a generator. Will yield `size` results per iteration until all hits are returned.
""" |
query = self.match_all if query is None else query
response = self.instance.search(index=self.index, doc_type=self.doc_type, body=query, size=size, scroll=scroll)
while len(response['hits']['hits']) > 0:
scroll_id = response['_scroll_id']
logging.debug(response)
if unpack:
yield [source['_source'] if '_source' in source else source for source in response['hits']['hits']]
else:
yield response['hits']['hits']
response = self.instance.scroll(scroll_id=scroll_id, scroll=scroll) |
<SYSTEM_TASK:>
Fetch document by _id.
<END_TASK>
<USER_TASK:>
Description:
def get(self, identifier):
"""Fetch document by _id.
Returns None if it is not found. (Will log a warning if not found as well. Should not be used
to search an id.)""" |
logging.info('Download document with id ' + str(identifier) + '.')
try:
record = self.instance.get(index=self.index, doc_type=self.doc_type, id=identifier)
if '_source' in record:
return record['_source']
else:
return record
except NotFoundError:
return None |
<SYSTEM_TASK:>
Index a single document into the index.
<END_TASK>
<USER_TASK:>
Description:
def index_into(self, document, id) -> bool:
"""Index a single document into the index.""" |
try:
self.instance.index(index=self.index, doc_type=self.doc_type, body=json.dumps(document, ensure_ascii=False), id=id)
except RequestError as ex:
logging.error(ex)
return False
else:
return True |
<SYSTEM_TASK:>
Takes a list of dictionaries and an identifier key and indexes everything into this index.
<END_TASK>
<USER_TASK:>
Description:
def bulk(self, data: List[Dict[str, str]], identifier_key: str, op_type='index', upsert=False, keep_id_key=False) -> bool:
"""
Takes a list of dictionaries and an identifier key and indexes everything into this index.
:param data: List of dictionaries containing the data to be indexed.
:param identifier_key: The name of the dictionary element which should be used as _id. This will be removed from
the body. Is ignored when None or empty string. This will cause elastic
to create their own _id.
:param op_type: What should be done: 'index', 'delete', 'update'.
:param upsert: The update op_type can be upserted, which will create a document if not already present.
:param keep_id_key Determines if the value designated as the identifier_key should be kept
as part of the document or removed from it.
:returns Returns True if all the messages were indexed without errors. False otherwise.
""" |
bulk_objects = []
for document in data:
bulk_object = dict()
bulk_object['_op_type'] = op_type
if identifier_key is not None and identifier_key != '':
bulk_object['_id'] = document[identifier_key]
if not keep_id_key:
document.pop(identifier_key)
if bulk_object['_id'] == '':
bulk_object.pop('_id')
if op_type == 'index':
bulk_object['_source'] = document
elif op_type == 'update':
bulk_object['doc'] = document
if upsert:
bulk_object['doc_as_upsert'] = True
bulk_objects.append(bulk_object)
logging.debug(str(bulk_object))
logging.info('Start bulk index for ' + str(len(bulk_objects)) + ' objects.')
errors = bulk(self.instance, actions=bulk_objects, index=self.index, doc_type=self.doc_type,
raise_on_error=False)
logging.info(str(errors[0]) + ' documents were successfully indexed/updated/deleted.')
if errors[0] - len(bulk_objects) != 0:
logging.error(str(len(bulk_objects) - errors[0]) + ' documents could not be indexed/updated/deleted.')
for error in errors[1]:
logging.error(str(error))
return False
else:
logging.debug('Finished bulk %s.', op_type)
return True |
<SYSTEM_TASK:>
Reindex the entire index.
<END_TASK>
<USER_TASK:>
Description:
def reindex(self, new_index_name: str, identifier_key: str, **kwargs) -> 'ElasticIndex':
"""Reindex the entire index.
Scrolls the old index and bulk indexes all data into the new index.
:param new_index_name:
:param identifier_key:
:param kwargs: Overwrite ElasticIndex __init__ params.
:return:
""" |
if 'url' not in kwargs:
kwargs['url'] = self.url
if 'doc_type' not in kwargs:
kwargs['doc_type'] = self.doc_type
if 'mapping' not in kwargs:
kwargs['mapping'] = self.mapping
new_index = ElasticIndex(new_index_name, **kwargs)
for results in self.scroll(size=500):
new_index.bulk(results, identifier_key)
return new_index |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.