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 clean(self):
"""Verifies that beginning date is before ending date.""" |
cleaned_data = super(DatasetUploadForm, self).clean()
date_begin = self.cleaned_data.get('date_begin')
date_end = self.cleaned_data.get('date_end')
if date_end < date_begin:
msg = u'End date should be after start date.'
self.add_error('date_begin', 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 _kwargs_to_attributes(self, kwargs):
""" Put keys from `kwargs` to `self`, if the keys are already there. """ |
for key, val in kwargs.iteritems():
if key not in self.__dict__:
raise ValueError(
"Can't set %s parameter - it is not defined here!" % key
)
self.__dict__[key] = val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assist(self, project_path, source, position, filename):
"""Return completion match and list of completion proposals :param project_path: absolute project pat... |
return self._call('assist', project_path, source, position, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_location(self, project_path, source, position, filename):
"""Return line number and file path where name under cursor is defined If line is None location... |
return self._call('get_location', project_path, source, position, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_docstring(self, project_path, source, position, filename):
"""Return signature and docstring for current cursor call context Some examples of call contex... |
return self._call('get_docstring', project_path, source, position, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_scope(self, project_path, source, lineno, filename, continous=True):
""" Return scope name at cursor position For example:: class Foo: def foo(self):
pa... |
return self._call('get_scope', project_path, source, lineno, filename, continous=continous) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _masquerade(origin: str, orig: ServiceDefn, new: ServiceDefn, **map: str) -> str: """build an origin URL such that the orig has all of the mappings to new def... |
origin: ParseResult = urlparse(origin)
prev_maps = {}
if origin.query:
prev_maps = {k: v for k, v in parse_qsl(origin.query)}
r_args = {}
for new_k, orig_k in map.items():
assert new_k in new.rpcs, [new_k, new.rpcs]
assert orig_k in orig.rpcs, [orig_k, orig.rpcs]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def masquerade(origin: str, orig: Type[TA], new: Type[TB], **map: str) -> str: """Make ``orig`` appear as new""" |
return _masquerade(origin, cache_get(orig), cache_get(new), **map) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendStatusPing(self):
""" Sends a status ping to Redunda with the instance key specified while constructing the object. """ |
data = parse.urlencode({"key": self.key, "version": self.version}).encode()
req = request.Request("https://redunda.sobotics.org/status.json", data)
response = request.urlopen(req)
jsonReturned = json.loads(response.read().decode("utf-8"))
self.location = jsonReturned["locatio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uploadFile(self, filename, ispickle=False, athome=False):
""" Uploads a single file to Redunda. :param str filename: The name of the file to upload :param bo... |
print("Uploading file {} to Redunda.".format(filename))
_, tail = os.path.split(filename)
url = "https://redunda.sobotics.org/bots/data/{}?key={}".format(tail, self.key)
#Set the content type to 'application/octet-stream'
header = {"Content-type": "application... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def downloadFile(self, filename, ispickle=False, athome=False):
""" Downloads a single file from Redunda. :param str filename: The name of the file you want to d... |
print("Downloading file {} from Redunda.".format(filename))
_, tail = os.path.split(filename)
url = "https://redunda.sobotics.org/bots/data/{}?key={}".format(tail, self.key)
requestToMake = request.Request(url)
#Make the request.
response = request.urlopen(requestToMa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uploadFiles(self):
""" Uploads all the files in 'filesToSync' """ |
for each_file in self.filesToSync:
self.uploadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def downloadFiles(self):
""" Downloads all the files in 'filesToSync' """ |
for each_file in self.filesToSync:
self.downloadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getEvents(self):
""" Gets all events from Redunda and returns them. :returns: Returns a dictionary of the events which were fetched. """ |
url = "https://redunda.sobotics.org/events.json"
data = parse.urlencode({"key": self.key}).encode()
req = request.Request(url, data)
response = request.urlopen(req)
return json.loads(response.read().decode("utf-8")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_client(cls, host: str = 'localhost', port: int = 11211, **client_args):
""" Configure a Memcached client. :param host: host name or ip address to c... |
assert check_argument_types()
client = Client(host, port, **client_args)
return client |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_features(self):
""" Extracts and sets the feature data from the log file necessary for a reduction """ |
for parsed_line in self.parsed_lines:
# If it's ssh, we can handle it
if parsed_line.get('program') == 'sshd':
result = self._parse_auth_message(parsed_line['message'])
# Add the ip if we have it
if 'ip' in result:
se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _analyze(self):
""" Decide which lines should be filtered out """ |
pids = []
for ip in self.filter['ips']:
if ip in self.ips_to_pids:
for pid in self.ips_to_pids[ip]:
pids.append(pid)
for line in self.parsed_lines:
if 'processid' in line and line['processid'] in pids:
self.noisy_logs... |
<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_epoch(self, ts):
""" Adds a year to the syslog timestamp because syslog doesn't use years :param ts: The timestamp to add a year to :return: Date/time st... |
year = self.year
tmpts = "%s %s" % (ts, str(self.year))
new_time = int(calendar.timegm(time.strptime(tmpts, "%b %d %H:%M:%S %Y")))
# If adding the year puts it in the future, this log must be from last year
if new_time > int(time.time()):
year -= 1
tmpt... |
<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_auth_message(self, auth_message):
""" Parse a message to see if we have ip addresses or users that we care about :param auth_message: The auth message... |
result = {}
has_matched = False
for regex in REGEXES_INVALID_USER:
# Check for the invalid user/ip messages
m = re.search(regex, auth_message)
if m and not has_matched:
has_matched = True
# Save the username and IP
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_until(data: bytes, *, return_tail: bool = True, from_=None) -> bytes: """ read until some bytes appear """ |
return (yield (Traps._read_until, data, return_tail, from_)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_int(nbytes: int, *, byteorder: str = "big", from_=None) -> int: """ read some bytes as integer """ |
return (yield (Traps._read_int, nbytes, byteorder, from_)) |
<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(self, data: bytes = b""):
""" send data for parsing """ |
self.input.extend(data)
self._process() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_bokeh_server(io_loop, files, argvs, host, port):
'''Start bokeh server with applications paths'''
from bokeh.server.server import Server
from bokeh.command.util import build_single_handler_applications
# Turn file paths into bokeh apps
apps = build_single_handler_applications(files, argv... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_request_handler_proxy(handler_class, handler_args, name):
"""When a tornado.web.RequestHandler gets mounted we create a launcher function""" |
@scope.inject
def request_handler_wrapper(app, handler, **kwargs):
handler = handler_class(app, handler.request, **handler_args)
handler._execute([], **kwargs)
request_handler_wrapper.__name__ = name
request_handler_wrapper.handler_class = handler_class
request_handler_wrapper.hand... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(self):
"""setup routing table""" |
# get all routes from submodules
for prefix, routes in self.sub_rt:
routes.prefix = self.prefix + prefix
routes.setup()
fn_name_prefixes = {}
for fn_key, fn in routes.fn_namespace.items():
self.fn_namespace[routes.name + '.' + fn_key] = f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version():
""" Loads the current module version from version.py and returns it. :returns: module version identifier. :rtype: str """ |
local_results = {}
version_file_path = os.path.join('pytextql', 'version.py')
# This is compatible with py3k which removed execfile.
with open(version_file_path, 'rb') as fin:
# Compiling instead of passing the text straight to exec
# associates any errors with the correct file 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 update(self, **args):
""" Updates a Clip. Parameters: - args Dictionary of other fields Accepted fields can be found here: https://github.com/kippt/api-docum... |
# JSONify our data.
data = json.dumps(args)
r = requests.put(
"https://kippt.com/api/clips/%s" % (self.id),
headers=self.kippt.header,
data=data)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def like(self):
""" Like a clip. """ |
r = requests.post(
"https://kippt.com/api/clips/%s/likes" % (self.id),
headers=self.kippt.header
)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment(self, body):
""" Comment on a clip. Parameters: - body (Required) """ |
# Merge our url as a parameter and JSONify it.
data = json.dumps({'body': body})
r = requests.post(
"https://kippt.com/api/clips/%s/comments" (self.id),
headers=self.kippt.header,
data=data
)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unlike(self):
""" Unlike a clip. """ |
r = requests.delete(
"https://kippt.com/api/clips/%s/likes" % (self.id),
headers=self.kippt.header)
return (r.json()) |
<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_json(value, pretty=False):
""" Serializes the given value to JSON. :param value: the value to serialize :param pretty: whether or not to format the output... |
options = {
'sort_keys': False,
'cls': BasicJSONEncoder,
}
if pretty:
options['indent'] = 2
options['separators'] = (',', ': ')
return json.dumps(value, **options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(value, native_datetimes=True):
""" Deserializes the given value from JSON. :param value: the value to deserialize :type value: str :param native_da... |
hook = BasicJsonDecoder(native_datetimes=native_datetimes)
result = json.loads(value, object_hook=hook)
if native_datetimes and isinstance(result, string_types):
return get_date_or_string(result)
return result |
<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_yaml(value, pretty=False):
""" Serializes the given value to YAML. :param value: the value to serialize :param pretty: whether or not to format the output... |
if not yaml:
raise NotImplementedError('No supported YAML library available')
options = {
'Dumper': BasicYamlDumper,
'allow_unicode': True,
}
options['default_flow_style'] = not pretty
return yaml.dump(value, **options).rstrip() |
<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_yaml(value, native_datetimes=True):
""" Deserializes the given value from YAML. :param value: the value to deserialize :type value: str :param native_da... |
if not yaml:
raise NotImplementedError('No supported YAML library available')
if native_datetimes:
loader = NativeDatesYamlLoader
else:
loader = StringedDatesYamlLoader
return yaml.load(value, Loader=loader) |
<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_toml(value, pretty=False):
# noqa: unused-argument """ Serializes the given value to TOML. :param value: the value to serialize :param pretty: this argume... |
if not toml:
raise NotImplementedError('No supported TOML library available')
return toml.dumps(make_toml_friendly(value)).rstrip() |
<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_toml(value, native_datetimes=True):
""" Deserializes the given value from TOML. :param value: the value to deserialize :type value: str :param native_da... |
if not toml:
raise NotImplementedError('No supported TOML library available')
result = toml.loads(value)
if native_datetimes:
result = convert_datetimes(result)
return result |
<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_true_table():
"""Merge all true table into single excel file. """ |
writer = pd.ExcelWriter("True Table.xlsx")
for p in Path(__file__).parent.select_by_ext(".csv"):
df = pd.read_csv(p.abspath, index_col=0)
df.to_excel(writer, p.fname, index=True)
writer.save() |
<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 send(self, *args, **kwargs):
"""Send args and kwargs to all registered callbacks""" |
for callback in self:
res = callback(*args, **kwargs)
if asyncio.iscoroutine(res) or isinstance(res, asyncio.Future):
await res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_logging(config=None):
"""Setup logging configuration.""" |
# TODO: integrate in general config file
print(__name__)
if config and config.get('logging'):
logging.config.dictConfig(config.get('logging'))
else:
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s',
level=logging.DEBUG) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_all_recommendations(cores, ip_views=False, config=None):
"""Calculate all recommendations in multiple processes.""" |
global _reco, _store
_reco = GraphRecommender(_store)
_reco.load_profile('Profiles')
if ip_views:
_reco.load_profile('Profiles_IP')
manager = Manager()
record_list = manager.list(_reco.all_records.keys())
# record_list = manager.list(list(_reco.all_records.keys())[:10])
num_re... |
<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_weeks(self, weeks, overwrite=False):
"""Fetch and cache the requested weeks.""" |
esf = ElasticsearchFetcher(self.store, self.config)
for year, week in weeks:
print("Fetch {}-{}".format(year, week))
esf.fetch(year, week, overwrite) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_all_recommendations(self, cores, ip_views=False):
"""Calculate the recommendations for all records.""" |
global _store
_store = self.store
_create_all_recommendations(cores, ip_views, self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def table_dataset_database_table( table = None, include_attributes = None, rows_limit = None, print_progress = False, ):
""" Create a pyprel table contents list ... |
if print_progress:
import shijian
progress = shijian.Progress()
progress.engage_quick_calculation_mode()
number_of_rows = len(table)
if include_attributes:
columns = include_attributes
else:
columns = table.columns
table_contents = [columns]
for ind... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def simple_nearest_indices(xs,res):
'''
Simple nearest interpolator that interpolates based on
the minima and maxima of points based on the passed
resolution in res.
Parameters:
-----------
xs -- A collection of `ndim` arrays of points.
res -- List of resolutions.
'''
maxs = [... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
""" Clears all of the build variables. """ |
for variable in self._project.variables.list(all=True):
variable.delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolved_type(self):
"""Return the type for the columns, and a flag to indicate that the column has codes.""" |
import datetime
self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None
for test, testf in tests + [(None, None)]}
# If it is more than 5% str, it's a str
try:
if self.type_ratios.get(text_type,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 promote_type(orig_type, new_type):
"""Given a table with an original type, decide whether a new determination of a new applicable type should overide the exi... |
if not new_type:
return orig_type
if not orig_type:
return new_type
try:
orig_type = orig_type.__name__
except AttributeError:
pass
try:
new_type = new_type.__name__
except AttributeError:
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_from_repaircafe_org():
"""Gets data from repaircafe_org.""" |
# Use Chrome as a browser
browser = webdriver.Chrome()
# Use PhantomJS as a browser
# browser = webdriver.PhantomJS('phantomjs')
browser.get("https://repaircafe.org/en/?s=Contact+the+local+organisers")
browser.maximize_window()
# Iterate over results (the #viewmore_link button)
viewmo... |
<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_labs(format):
"""Gets Repair Cafe data from repairecafe.org.""" |
data = data_from_repaircafe_org()
repaircafes = {}
# Load all the Repair Cafes
for i in data:
# Create a lab
current_lab = RepairCafe()
# Add existing data from first scraping
current_lab.name = i["name"]
slug = i["url"].replace("https://repaircafe.org/locatio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def archive_if_exists(filename):
""" Move `filename` out of the way, archiving it by appending the current datetime Can be a file or a directory """ |
if os.path.exists(filename):
current_time = datetime.datetime.now()
dt_format = '%Y-%m-%dT%H:%M:%S%z'
timestamp = current_time.strftime(dt_format)
dst = filename + '_' + timestamp
shutil.move(filename, dst) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_files(dirname, extension=None):
""" List all files in directory `dirname`, option to filter on file extension """ |
f = []
for (dirpath, dirnames, filenames) in os.walk(dirname):
f.extend(filenames)
break
if extension is not None:
# Filter on extension
filtered = []
for filename in f:
fn, ext = os.path.splitext(filename)
if ext.lower() == '.' + extension.lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filename_addstring(filename, text):
""" Add `text` to filename, keeping the extension in place For example when adding a timestamp to the filename """ |
fn, ext = os.path.splitext(filename)
return fn + text + ext |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_file_contents(filename):
""" Read file contents from file `filename` """ |
data = None
try:
with open(filename) as pf:
data = pf.read()
except IOError:
# File not found, return None
pass
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_name(cls, name):
""" Parses a name into a dictionary of identified subsections with accompanying information to correctly identify and replace if neces... |
parse_dict = dict.fromkeys(cls.PARSABLE, None)
parse_dict['date'] = cls.get_date(name)
parse_dict['version'] = cls.get_version(name)
parse_dict['udim'] = cls.get_udim(name)
parse_dict['side'] = cls.get_side(name)
parse_dict['basename'] = cls.get_base_naive(cls._reduce_na... |
<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_side(cls, name, ignore=''):
""" Checks a string for a possible side string token, this assumes its on its own and is not part of or camel cased and combi... |
for side in cls.CONFIG_SIDES:
""" Tried using a regex, however it would've taken too long to debug
side_regex = cls._build_abbreviation_regex(side)
result = cls._generic_search(name, side_regex, metadata={'side': side}, ignore=ignore)
if result:
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 get_discipline(cls, name, ignore='', min_length=3):
""" Checks a string for a possible discipline string token, this assumes its on its own and is not part o... |
for discipline in cls.CONFIG_DISCIPLINES:
re_abbr = '({RECURSE}(?=[0-9]|[A-Z]|{SEPARATORS}))'.format(
RECURSE=cls._build_abbreviation_regex(discipline),
SEPARATORS=cls.REGEX_SEPARATORS)
matches = cls._get_regex_search(name, re_abbr, ignore=ignore)
... |
<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_string_camel_patterns(cls, name, min_length=0):
""" Finds all permutations of possible camel casing of the given name :param name: str, the name we need ... |
# Have to check for longest first and remove duplicates
patterns = []
abbreviations = list(set(cls._get_abbreviations(name, output_length=min_length)))
abbreviations.sort(key=len, reverse=True)
for abbr in abbreviations:
# We won't check for abbreviations that are 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 _reduce_name(cls, name, parse_dict):
""" Reduces a name against matches found in a parse dictionary :param name: str, name to be reduced :param parse_dict: d... |
# Now remove all found entries to make basename regex have an easier time
removal_indices = []
for section, match in iteritems(parse_dict):
try:
matches = []
if isinstance(match, dict) and 'compound_matches' in match:
matches = 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 _get_regex_search(input_string, regex, metadata={}, match_index=None, ignore='', flags=0):
""" Using this so that all results from the functions return simil... |
generator = re.compile(regex, flags=flags).finditer(input_string)
matches = []
for obj in generator:
try:
span_a = obj.span(1)
group_a = obj.group(1)
except IndexError:
span_a = obj.span()
group_a = obj.grou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generic_search(cls, name, search_string, metadata={}, ignore=''):
""" Searches for a specific string given three types of regex search types. Also auto-chec... |
patterns = [cls.REGEX_ABBR_SEOS,
cls.REGEX_ABBR_ISLAND,
cls.REGEX_ABBR_CAMEL]
if not search_string[0].isupper():
patterns.remove(cls.REGEX_ABBR_CAMEL)
for pattern in patterns:
search_result = cls._get_regex_search(name,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_abbreviations(input_string, output_length=0):
""" Generates abbreviations for input_string :param input_string: str, name of object :param output_length... |
for i, j in itertools.combinations(range(len(input_string[1:]) + 1), 2):
abbr = input_string[0] + input_string[1:][i:j]
if len(abbr) >= output_length:
yield abbr
elif output_length == 0:
yield abbr
# Have to add the solitary letter as ... |
<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_casing_permutations(cls, input_string):
""" Takes a string and gives all possible permutations of casing for comparative purposes :param input_string: s... |
if not input_string:
yield ""
else:
first = input_string[:1]
for sub_casing in cls._get_casing_permutations(input_string[1:]):
yield first.lower() + sub_casing
yield first.upper() + sub_casing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _string_remove_slice(input_str, start, end):
""" Removes portions of a string :param input_str: str, input string :param start: int, end search index :param ... |
if 0 <= start < end <= len(input_str):
return input_str[:start] + input_str[end:]
return input_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 getvector(d,s):
'''
Get a vector flds data.
Parameters:
-----------
d -- flds data.
s -- key for the data.
'''
return np.array([d[s+"x"],d[s+"y"],d[s+"z"]]); |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def restrict(d,restrict):
'''
Restrict data by indices.
Parameters:
----------
d -- the flds/sclr data
restrict -- a tuple of [xmin,xmax,...] etx
'''
notqs = ['t','xs','ys','zs','fd','sd']
keys = [k for k in d if k not in notqs];
if len(restrict) == 2:
for k i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_logger(name, level='INFO'):
""" Creates a new ready-to-use logger. :param name: new logger's name :type name: str :param level: default logging level.... |
formatter = ColorFormatter(LOG_FORMAT, DATE_FORMAT)
if not isinstance(logging.getLevelName(level), int):
level = 'INFO'
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return log... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_contributors(authors, contrib_type, competing_interests=None):
""" Given a list of authors from the parser, instantiate contributors objects and build ... |
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_funding(award_groups):
""" Given a funding data, format it """ |
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_datasets(datasets_json):
""" Given datasets in JSON format, build and return a list of dataset objects """ |
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_data_availability(datasets_json):
""" Given datasets in JSON format, get the data availability from it if present """ |
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def component_title(component):
""" Label, title and caption Title is the label text plus the title text Title may contain italic tag, etc. """ |
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_components(components):
""" Given parsed components build a list of component objects """ |
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.ge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_related_articles(related_articles):
""" Given parsed data build a list of related article objects """ |
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = 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 build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-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 clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
""" Remove unwanted tags from abstract string, parsing it as HTML, the... |
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_articles_from_article_xmls(article_xmls, detail="full", build_parts=None, remove_tags=None):
""" Given a list of article XML filenames, convert to arti... |
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accounts():
"""Load the accounts YAML file and return a dict """ |
import yaml
for path in account_files:
try:
c_dir = os.path.dirname(path)
if not os.path.exists(c_dir):
os.makedirs(c_dir)
with open(path, 'rb') as f:
return yaml.load(f)['accounts']
except (OSError, IOError) as e:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_logger( name, file_name=None, stream=None, template=None, propagate=False):
"""Get a logger by name if file_name is specified, and the dirname() of the f... |
logger = logging.getLogger(name)
if propagate is not None:
logger.propagate = propagate
for handler in logger.handlers:
logger.removeHandler(handler)
if not template:
template = "%(name)s %(process)s %(levelname)s %(message)s"
formatter = logging.Formatter(template)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def md5_for_file(f, block_size=2 ** 20):
"""Generate an MD5 has for a possibly large file by breaking it into chunks""" |
import hashlib
md5 = hashlib.md5()
try:
# Guess that f is a FLO.
f.seek(0)
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest()
except AttributeError as e:
# Nope, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subcache(self, path):
"""Clone this case, and extend the prefix""" |
cache = self.clone()
cache.prefix = os.path.join(cache.prefix if cache.prefix else '', path)
return cache |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def store_list(self, cb=None):
"""List the cache and store it as metadata. This allows for getting the list from HTTP caches and other types where it is not poss... |
from StringIO import StringIO
import json
d = {}
for k, v in self.list().items():
if 'caches' in v:
del v['caches']
d[k] = v
strio = StringIO(json.dumps(d))
sink = self.put_stream('meta/_list.json')
copy_file_or_flo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach(self, upstream):
"""Attach an upstream to the last upstream. Can be removed with detach""" |
if upstream == self.last_upstream():
raise Exception("Can't attach a cache to itself")
self._prior_upstreams.append(self.last_upstream())
self.last_upstream().upstream = upstream |
<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_upstream(self, type_):
'''Return self, or an upstream, that has the given class type.
This is typically used to find upstream s that impoement the RemoteInterface
'''
if isinstance(self, type_):
return self
elif self.upstream and isinstance(self.upstream, typ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self, a_bytes, encoding):
"""A 'try as much as we can' strategy decoding method. 'try as much as we can' feature: Some time most of byte are encoded c... |
try:
return (a_bytes.decode(encoding), encoding)
except Exception as e:
ind = self.catch_position_in_UnicodeDecodeError_message(str(e))
return (a_bytes[:ind].decode(encoding) + self.decode(a_bytes[(ind + 2):], encoding)[0],
encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autodecode(self, a_bytes):
"""Automatically detect encoding, and decode bytes. """ |
try: # 如果装了chardet
analysis = chardet.detect(a_bytes)
if analysis["confidence"] >= 0.75: # 如果可信
return (self.decode(a_bytes, analysis["encoding"])[0],
analysis["encoding"])
else: # 如果不可信, 打印异常
raise Exception("Failed... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self, url, payload):
"""Performe log in. url is the login page url, for example: https://login.secureserver.net/index.php? payload includes the account... |
self.auth = requests.Session()
try:
self.auth.post(url, data=payload, timeout=self.default_timeout)
print("successfully logged in to %s" % url)
return True
except:
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 get_response(self, url, timeout=None):
"""Return http request response. """ |
if not timeout:
timeout = self.default_timeout
if self.default_sleeptime:
time.sleep(self.default_sleeptime)
try:
return self.auth.get(url, headers=self.default_header, timeout=self.default_timeout)
except:
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 html_with_encoding(self, url, timeout=None, encoding="utf-8"):
"""Manually get html with user encoding setting. """ |
response = self.get_response(url, timeout=timeout)
if response:
return self.decoder.decode(response.content, encoding)[0]
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def html(self, url, timeout=None):
"""High level method to get http request response in text. smartly handle the encoding problem. """ |
response = self.get_response(url, timeout=timeout)
if response:
domain = self.get_domain(url)
if domain in self.domain_encoding_map: # domain have been visited
try: # apply extreme decoding
html = self.decoder.decode(response.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 binary(self, url, timeout=None):
"""High level method to get http request response in bytes. """ |
response = self.get_response(url, timeout=timeout)
if response:
return response.content
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, url, dst, timeout=None):
"""Download the binary file at url to distination path. """ |
response = self.get_response(url, timeout=timeout)
if response:
with open(dst, "wb") as f:
for block in response.iter_content(1024):
if not block:
break
f.write(block) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changed(self, src, path, dest):
"""Called whenever `path` is changed in the source folder `src`. `dest` is the output folder. The default implementation call... |
try:
mtime = os.path.getmtime(os.path.join(src, path))
self._build(src, path, dest, mtime)
except EnvironmentError as e:
logging.error("{0} is inaccessible: {1}".format(
termcolor.colored(path, "yellow", attrs=["bold"]),
e.args[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 build(self, input_path, output_paths):
"""Should be extended by subclasses to actually do stuff. By default this will copy `input` over every file in the `ou... |
for output in output_paths:
shutil.copy(input_path, output_paths) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rebuild_references(self, src, path, reject=None):
"""Updates `parents` and `children` to be in sync with the changes to `src` if any.""" |
if reject is None:
reject = set()
reject.add(path)
try:
filename = os.path.join(src, path)
mtime = os.path.getmtime(filename)
contents = open(filename)
except EnvironmentError:
raise ValueError("Unable to open '{0}'".format(pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deleted(self, src, path):
"""Update the reference tree when a handled file is deleted.""" |
if self.parents[path] is not None:
for parent in self.parents[path]:
self.children[parent].remove(path)
if not self.children[parent]:
del self.children[parent]
del self.parents[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 clearScreen(cls):
"""Clear the screen""" |
if "win32" in sys.platform:
os.system('cls')
elif "linux" in sys.platform:
os.system('clear')
elif 'darwin' in sys.platform:
os.system('clear')
else:
cit.err("No clearScreen for " + sys.platform) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPyCmd(cls):
"""get OS's python command""" |
if "win32" in sys.platform:
return 'py'
elif "linux" in sys.platform:
return 'python3'
elif 'darwin' in sys.platform:
return 'python3'
else:
cit.err("No python3 command for " + sys.platform) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runCmd(cls, cmd):
"""run command and show if success or failed Args: cmd: string Returns: bool: if this command run successfully """ |
cit.echo(cmd, "command")
result = os.system(cmd)
cls.checkResult(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readCmd(cls, cmd):
"""run command and return the str format stdout Args: cmd: string Returns: str: what the command's echo """ |
args = shlex.split(cmd)
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
(proc_stdout, proc_stderr) = proc.communicate(input=None) # proc_stdin
return proc_stdout.decode() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.