Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>an http:// or https:// protocol specified.
"""
class HTTPBackend(BaseStorageBackend):
"""
Abstracts access to HTTP via the common set of file storage backend methods.
.. note:: ``upload_file`` is not implemented yet, not sure how
it should work.
"""
... | logger.debug("HTTPBackend.download_file(): " \ |
Given the code snippet: <|code_start|>"""
This module contains an HTTPBackend class for working with URIs that have
an http:// or https:// protocol specified.
"""
class HTTPBackend(BaseStorageBackend):
"""
Abstracts access to HTTP via the common set of file storage backend methods.
.. note:: ``upload_file... | raise InfileNotFoundException(message) |
Next line prediction: <|code_start|> """
Abstracts storing and retrieving job state information to and from
SimpleDB_. Jobs are represented through the :py:class:`EncodingJob` class,
which are instantiated and returned as needed.
"""
JOB_STATES = ['PENDING', 'DOWNLOADING', 'ENCODING', 'UPLOADING'... | settings.AWS_ACCESS_KEY_ID, |
Based on the snippet: <|code_start|> # Start populating values.
self.creation_dtime = now_dtime
self.job_state = 'PENDING'
else:
# Retrieve the existing item for the job.
job = JobStateBackend._get_sdb_job_state_domain().get_item(self.unique_id)
... | logger.debug("EncodingJob.save(): Item pre-save values: %s" % job) |
Based on the snippet: <|code_start|> .. tip:: You generally won't be instantiating these objects yourself.
To retrieve an existing job, you may
use :py:meth:`JobStateBackend.get_job_object_from_id`.
"""
def __init__(self, source_path, dest_path, nommer, job_options,
unique_id... | self.nommer = import_class_from_module_string(str(nommer))(self) |
Using the snippet: <|code_start|>Contains the :py:class:`NodeStateManager` class, which is an abstraction layer
for storing and communicating the status of EC2_ nodes.
"""
class NodeStateManager(object):
"""
Tracks this node's state, reports it to :doc:`../feederd`, and terminates
itself if certain condit... | settings.AWS_ACCESS_KEY_ID, |
Using the snippet: <|code_start|> if not.
"""
if not cls.is_ec2_instance():
# Developing locally, don't go here.
return False
# This is -1 since this is also a thread doing the contemplation.
# This would always be 1, even if we had no jobs encoding, i... | logger.info("Goodbye, cruel world.") |
Here is a snippet: <|code_start|> item.save()
@classmethod
def contemplate_termination(cls, thread_count_mod=0):
"""
Looks at how long it's been since this worker has done something, and
decides whether to self-terminate.
:param int thread_count_mod: Add this... | inactive_secs = total_seconds(tdelt) |
Here is a snippet: <|code_start|>"""
Various configuration-related utility methods.
"""
def upload_settings(nomconf_module):
"""
Given a user-defined nomconf module (already imported), push said file
to the S3 conf bucket, as defined by settings.CONFIG_S3_BUCKET.
This is used by the nommers that requi... | logger.info("Uploading nomconf.py to S3.") |
Next line prediction: <|code_start|> )
def send_notification(job):
"""
Given an EncodingJob, see if it has a ``notify_url`` set, and dispatch
a notification to said URL (if set). Don't do any processing of the response.
:param EncodingJob job: The job whose state has changed.
"""
if not job... | body = StringProducer(urllib.urlencode(data)) if data else None |
Continue the code snippet: <|code_start|>"""
This module contains code that handles notifying external services of state
changes in EncodingJobs. For example, when the state changes from
PENDING to DOWNLOADING, or ENCODING to FINISHED.
"""
def cb_response_received(response, unique_id, req_url):
"""
This is a ... | logger.info( |
Predict the next line after this snippet: <|code_start|>
def __init__(self, extension: Optional[str] = None) -> None:
Namer.__init__(self, extension)
self.set_for_stack(inspect.stack(1))
self.config: Dict[str, str] = {}
self.config_loaded = False
def set_for_stack(self, caller: ... | raise FrameNotFound(message) |
Using the snippet: <|code_start|> self.assertEqual("test_method", n.get_method_name())
def test_name_works_from_inside_an_other_method(self):
self.an_other_method()
def an_other_method(self):
n = StackFrameNamer()
self.assertEqual(
"test_name_works_from_inside_an_oth... | n = Namer(extension=".html") |
Next line prediction: <|code_start|>
class ScenarioNamer(Namer):
"""
For use with parameterized tests.
Use this namer when the same test case needs to verify more than one value, and produce more than one file.
"""
<|code_end|>
. Use current file imports:
(from typing import Optional
from approvalt... | def __init__(self, base_namer: StackFrameNamer, scenario_name: int) -> None: |
Given snippet: <|code_start|>
class ReportWithBeyondCompareWindows(GenericDiffReporter):
def __init__(self):
super().__init__(
config=GenericDiffReporterConfig(
name=self.__class__.__name__,
path="{ProgramFiles}/Beyond Compare 4/BCompare.exe",
)
... | class ReportWithBeyondCompare(FirstWorkingReporter): |
Given the following code snippet before the placeholder: <|code_start|>
class ReportWithBeyondCompareLinux(GenericDiffReporter):
def __init__(self):
super().__init__(
<|code_end|>
, predict the next line using imports from the current file:
from approvaltests.reporters.first_working_reporter import FirstW... | config=GenericDiffReporterConfig( |
Predict the next line for this snippet: <|code_start|>
class IntroductionReporter(Reporter):
def report(self, received_path: str, approved_path: str) -> bool:
print(self.get_text())
<|code_end|>
with the help of current file imports:
from approvaltests.core.reporter import Reporter
from approvaltests.re... | return PythonNativeReporter().report(received_path, approved_path) |
Using the snippet: <|code_start|>
class ReporterForTesting(Reporter):
def __init__(self, success: bool, additional: Optional[Callable] = None) -> None:
if additional is None:
additional = lambda: None
self.additional = additional
self.called = False
self.success = succe... | first = FirstWorkingReporter(r1, r2) |
Given the code snippet: <|code_start|>
class DiffReporter(FirstWorkingReporter):
"""
The DiffReporter class goes through a chain of possible diffing tools,
to find the first option installed on your system.
If none are found, it falls back to writing the diffs on
the console.
At present, the ... | factory = reporter_factory or GenericDiffReporterFactory() |
Based on the snippet: <|code_start|>
class DiffReporter(FirstWorkingReporter):
"""
The DiffReporter class goes through a chain of possible diffing tools,
to find the first option installed on your system.
If none are found, it falls back to writing the diffs on
the console.
At present, the de... | reporters.append(IntroductionReporter()) |
Given the code snippet: <|code_start|>
def exists(path: str) -> bool:
return os.path.isfile(path)
class ReporterNotWorkingException(Exception):
def __init__(self, reporter: Reporter):
super().__init__(f"Reporter {reporter} failed to work!")
<|code_end|>
, generate the next line using the imports i... | class FileComparator(Comparator): |
Continue the code snippet: <|code_start|>
def exists(path: str) -> bool:
return os.path.isfile(path)
class ReporterNotWorkingException(Exception):
def __init__(self, reporter: Reporter):
super().__init__(f"Reporter {reporter} failed to work!")
class FileComparator(Comparator):
def compare(self,... | namer: Namer, |
Next line prediction: <|code_start|>
def exists(path: str) -> bool:
return os.path.isfile(path)
class ReporterNotWorkingException(Exception):
<|code_end|>
. Use current file imports:
(import filecmp
import os
import pathlib
from abc import ABC, abstractproperty
from typing import Optional
from approvaltests.co... | def __init__(self, reporter: Reporter): |
Based on the snippet: <|code_start|>
def exists(path: str) -> bool:
return os.path.isfile(path)
class ReporterNotWorkingException(Exception):
def __init__(self, reporter: Reporter):
super().__init__(f"Reporter {reporter} failed to work!")
class FileComparator(Comparator):
def compare(self, recei... | writer: Writer, |
Predict the next line after this snippet: <|code_start|>
class EncryptionMixin(object):
@property
def encryption_backend(self):
if not hasattr(self, "_encryption"):
if hasattr(self, "bot") and hasattr(self.bot, "_encryption"):
self._encryption = self.bot._encryption
... | getattr(settings, 'ENCRYPTION_BACKEND', 'aes'), |
Given snippet: <|code_start|>
class RegexBackend(GenerationBackend):
def do_generate(self, event):
exclude_list = ["fn", ]
matches = []
message = event.data
for name, l in self.bot.message_listeners.items():
search_matches = l["regex"].search(message.content)
... | context = Bunch() |
Here is a snippet: <|code_start|> def do_generate(self, event):
exclude_list = ["fn", ]
matches = []
message = event.data
for name, l in self.bot.message_listeners.items():
search_matches = l["regex"].search(message.content)
if (
# The sear... | o = GeneratedOption(context=context, backend="regex", score=100) |
Given the following code snippet before the placeholder: <|code_start|>@pytest.fixture()
def message():
"""Mimic message abstraction"""
def _message(fields):
required_fields = {
"is_direct": False,
"is_private_chat": False,
"is_group_chat": True,
"will_is_... | return Event(**required_fields) |
Predict the next line for this snippet: <|code_start|> "source": "TBD",
"handle": "TBD",
"name": "TBD",
"first_name": "TDB"
}
required_fields.update(fields)
return Person(**required_fields)
return _person
@pytest.fixture()
def message():
... | return Message(**required_fields) |
Based on the snippet: <|code_start|>
@pytest.fixture(params=IO_BACKENDS)
def io_backend(request):
"""Parametrized fixture of available io backends"""
return request.param
@pytest.fixture(params=ANALYZE_BACKENDS)
def analysis(request):
"""Parametrized fixture of available analysis backends"""
return... | return Person(**required_fields) |
Given the following code snippet before the placeholder: <|code_start|> elif os.path.exists(expire_path):
os.unlink(expire_path)
def clear(self, key):
key_path, expire_path = self._key_paths(key)
if os.path.exists(key_path):
os.unlink(key_path)
if os.path.exis... | return sizeof_fmt(sum([ |
Next line prediction: <|code_start|>
class FileStorageException():
"""
A condition that should not occur happened in the FileStorage module
"""
pass
<|code_end|>
. Use current file imports:
(import logging
import os
import time
from will.utils import sizeof_fmt
from .base import BaseStorageBackend)... | class FileStorage(BaseStorageBackend): |
Given snippet: <|code_start|>
class SettingsMixin(object):
required_settings = []
def verify_setting_exists(self, setting_name, message=None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clint.textui import colored, puts, indent
from will import settings
from wil... | if not hasattr(settings, setting_name): |
Here is a snippet: <|code_start|>
def verify_setting_exists(self, setting_name, message=None):
if not hasattr(settings, setting_name):
self.say("%s not set." % setting_name, message=message)
return False
return True
def verify_settings(self, quiet=False):
passed... | show_valid(s["name"]) |
Predict the next line after this snippet: <|code_start|>
class SettingsMixin(object):
required_settings = []
def verify_setting_exists(self, setting_name, message=None):
if not hasattr(settings, setting_name):
self.say("%s not set." % setting_name, message=message)
return Fals... | error("%(name)s is missing. It's required by the %(friendly_name)s backend." % meta) |
Predict the next line after this snippet: <|code_start|>
def __init__(self, *args, **kwargs):
if "bot" in kwargs:
self.bot = kwargs["bot"]
del kwargs["bot"]
if "message" in kwargs:
self.message = kwargs["message"]
del kwargs["message"]
super()... | for b in settings.IO_BACKENDS: # pylint: disable=no-member |
Given the code snippet: <|code_start|>
if hasattr(message, "backend"):
backend = message.backend
elif message and hasattr(message, "data") and hasattr(message.data, "backend"):
backend = message.data.backend
else:
backend = settings.DEFAULT_BACKEND # pylint: ... | e = Event( |
Predict the next line after this snippet: <|code_start|> ScheduleMixin, SettingsMixin, PubSubMixin):
'Basic things needed by all plugins'
is_will_plugin = True
request = request
def __init__(self, *args, **kwargs):
if "bot" in kwargs:
self.bot = kwargs["bot"]
... | def get_backend(message: Message, service: str = None): |
Continue the code snippet: <|code_start|>'Encrypt stored data'
# pylint: disable=no-member
BS = 16
key = hashlib.sha256(settings.SECRET_KEY.encode("utf-8")).digest()
def pad(s: bytes) -> str:
'''Ensure the data to be encrypted has sufficient padding.
Arbitrarily adding ~ to the end, so your message bette... | class AESEncryption(WillBaseEncryptionBackend): |
Here is a snippet: <|code_start|>
class HistoryAnalysis(AnalysisBackend, StorageMixin):
def do_analyze(self, message):
# Load the last few messages, add it to the context under "history"
history = self.load("message_history", [])
if not history:
history = []
<|code_end|>
. Wri... | max_history_context = getattr(settings, "HISTORY_CONTEXT_LENGTH", 20) |
Predict the next line after this snippet: <|code_start|> return source
def __disable_service(service_name, source):
return source.replace('"will.backends.io_adapters.%s"' % cleaned(service_name),
'"# will.backends.io_adapters.%s"' % cleaned(service_name))
def enable_disable_service(... | print_head() |
Predict the next line after this snippet: <|code_start|>
SKIP_TYPES = ["psubscribe", "punsubscribe", ]
class PubSubPrivateBase(SettingsMixin, EncryptionMixin):
"""
The private bits of the base pubsub backend.
"""
def __init__(self, *args, **kwargs):
self.recent_hashes = []
def publish(se... | e = Event( |
Given the following code snippet before the placeholder: <|code_start|> if hasattr(obj, "sender"):
e.sender = obj.sender
if reference_message:
original_incoming_event_hash = None
if hasattr(reference_message, "original_incoming_event_hash"):
original_i... | if not t.startswith(settings.SECRET_KEY): |
Given the following code snippet before the placeholder: <|code_start|> def handle_execution(self, message, context):
raise NotImplementedError
def no_response(self, message):
self.bot.pubsub.publish(
"message.no_response",
message.data,
reference_message=mess... | allowed = verify_acl(message, acl) |
Based on the snippet: <|code_start|>
class ExecutionBackend(object):
is_will_execution_backend = True
def handle_execution(self, message, context):
raise NotImplementedError
def no_response(self, message):
self.bot.pubsub.publish(
"message.no_response",
message.dat... | Event( |
Next line prediction: <|code_start|>
class PubSubMixin(object):
def bootstrap_pubsub(self):
if not hasattr(self, "pubsub"):
if hasattr(self, "bot") and hasattr(self.bot, "pubsub"):
self.pubsub = self.bot.pubsub
else:
# The PUBSUB_BACKEND setting point... | getattr(settings, 'PUBSUB_BACKEND', 'redis'), |
Predict the next line for this snippet: <|code_start|> with indent(2):
try:
had_warning = False
try:
except ImportError:
# Missing config.py. Check for config.py.dist
if os.path.isfile("config.py.dist"):
confirm = input(... | show_valid("Valid.") |
Next line prediction: <|code_start|> else:
settings["HIPCHAT_SERVER"] = "api.hipchat.com"
# Import from config
if not quiet:
puts("Importing config.py... ")
with indent(2):
try:
had_warning = False
try:
except ImportError:
# Mis... | warn("%s is set in the environment as '%s', but overridden in" |
Given the code snippet: <|code_start|> # Migrate from 1.x
if "CHAT_BACKENDS" in settings and "IO_BACKENDS" not in settings:
IO_BACKENDS = []
for c in settings["CHAT_BACKENDS"]:
IO_BACKENDS.append("will.backends.io_adapters.%s" % c)
settings["IO_BACKENDS... | note("No ANALYZE_BACKENDS specified. Defaulting to history only.") |
Predict the next line for this snippet: <|code_start|>
# If HIPCHAT_SERVER is set, we need to change the USERNAME slightly
# for XMPP to work.
if "HIPCHAT_SERVER" in settings:
settings["USERNAME"] = "{user}@{host}".\
format(user=settings["USERNAME"].split("@")[0],
host... | error("I'm missing my config.py file. Usually one comes with the installation - maybe it got lost?") |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
def get_acl_members(acl):
acl_members = []
acl = acl.lower()
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from will import settings
and context (classes, functions, sometimes code) from other files:
# Pa... | if getattr(settings, "ACL", None): |
Predict the next line for this snippet: <|code_start|> "will_is_mentioned",
"will_said_it",
"sender",
"backend_supports_acl",
"content",
"backend",
"original_incoming_event",
]
def __init__(self, *args, **kwargs):
for f in self.REQUIRED_FIELDS:
... | self.metadata = Bunch() |
Continue the code snippet: <|code_start|> self.list_accelerator_types: gapic_v1.method.wrap_method(
self.list_accelerator_types,
default_timeout=None,
client_info=client_info,
),
self.get_accelerator_type: gapic_v1.method.wrap_method(
... | [cloud_tpu.ListNodesRequest], |
Given the code snippet: <|code_start|> client_info=client_info,
),
self.get_runtime_version: gapic_v1.method.wrap_method(
self.get_runtime_version, default_timeout=None, client_info=client_info,
),
self.get_guest_attributes: gapic_v1.method.... | [cloud_tpu.ListNodesRequest], |
Continue the code snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permission... | method: Callable[..., cloud_tpu.ListNodesResponse], |
Continue the code snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permission... | method: Callable[..., cloud_tpu.ListNodesResponse], |
Given snippet: <|code_start|>
def get_version(fname):
"grab __version__ variable from fname (assuming fname is a python file). parses without importing."
assign_stmts = [s for s in ast.parse(open(fname).read()).body if isinstance(s,ast.Assign)]
valid_targets = [s for s in assign_stmts if len(s.targets) == 1 a... | version=version.__version__,
|
Given the code snippet: <|code_start|>
@pytest.mark.xfail
def test_getterby(): raise NotImplementedError
def test_methonce():
class C:
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from pg13 import misc
and context (functions, classes, or occasionally code) from other files:
... | @misc.meth_once |
Here is a snippet: <|code_start|> linkingAgentIdentifierRole.text = 'implementer'
linkingAgentIdentifierType.text = i[0]
linkingAgentIdentifierValue.text = i[1]
def main():
print 'This is not a standalone script. It is a library of functions that other scripts can use... | append_csv(uuid_csv, (filmographic, source_accession, uuid) ) |
Here is a snippet: <|code_start|> linkingAgentIdentifierRole = create_unit(2,linkingAgentIdentifier,'linkingAgentRole')
linkingAgentIdentifierRole.text = 'implementer'
linkingAgentIdentifierType.text = i[0]
linkingAgentIdentifierValue.text = i[1]
def ... | create_csv(uuid_csv, ('reference number','source accession number' 'uuid')) |
Using the snippet: <|code_start|>#!/usr/bin/env python
'''
Generates sidecar MD5 or SHA512 checksum manifest.
'''
def remove_bad_files(root_dir, log_name_source):
'''
Removes unwanted files.
Verify if this is different than the same function in ififuncs.
'''
rm_these = ['.DS_Store', 'Thumbs.db', '... | generate_log( |
Using the snippet: <|code_start|> generate_log(
log_name_source,
'EVENT = Generating manifest: status=started, eventType=message digest calculation, module=%s, agent=OSX' % module
)
elif sys.platform == "linux2":
generate_log(
log_name_s... | count_in_manifest = manifest_file_count(manifest) |
Given the following code snippet before the placeholder: <|code_start|> if os.path.isfile(source):
print('\nFile checksum is not currently supported, only directories.\n')
generate_log(log_name_source, 'Error: Attempted to generate manifest for file. Only Directories/Folders are currently supported')... | hashlib_manifest(source, manifest, source) |
Predict the next line for this snippet: <|code_start|> action='store_true',
help='Generates sha512 checksums instead of md5'
)
args = parser.parse_args(args_)
source = args.source
source_parent_dir = os.path.dirname(source)
normpath = os.path.normpath(source)
relative_path = normp... | desktop_logs_dir = make_desktop_logs_dir() |
Given the following code snippet before the placeholder: <|code_start|> parser.add_argument(
'-sha512',
action='store_true',
help='Generates sha512 checksums instead of md5'
)
args = parser.parse_args(args_)
source = args.source
source_parent_dir = os.path.dirname(source)
... | desktop_manifest_dir = make_desktop_manifest_dir() |
Continue the code snippet: <|code_start|> logs_dir = os.path.join(sip_dir, 'logs')
logfile = os.path.join(logs_dir, logname)
if os.path.isfile(logfile):
with open(log, 'r') as fo:
validate_log = fo.readlines()
with open(logfile, 'a') as ba:
for lines in validate_log:
... | desktop_logs_dir = make_desktop_logs_dir() |
Given snippet: <|code_start|>#!/usr/bin/env python
'''
This script will ask mediainfo to get all durations with a folder
'''
def main():
'''
Recursively search for AV files and print duration in seconds
'''
all_files = sys.argv[1:]
duration = 0
for parent_directory in all_files:
for ro... | milliseconds = get_milliseconds( |
Given the following code snippet before the placeholder: <|code_start|> # make sure that the alternate log filename is more recent
if int(
os.path.basename(logs)[-12:-4].replace('_', '')) > int(os.path.basename(i)[-12:-4].replace('_', '')):
... | desktop_logs_dir = make_desktop_logs_dir() |
Continue the code snippet: <|code_start|> output = filename + "_h264.mov"
ffmpeg_args = [
'ffmpeg',
'-i', filename,
]
if args.logo:
ffmpeg_args.extend(['-i', args.logo])
ffmpeg_args += [
'-c:a', 'aac',
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
... | h264_md5 = hashlib_md5(filename) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
'''
This script will create a new UUID
via ififuncs.create_uuid and print to terminal
'''
def main():
'''
Prints a new UUID to the terminal
'''
<|code_end|>
. Use current file imports:
from ififuncs import create_uuid
and context (classes, f... | new_uuid = create_uuid() |
Given snippet: <|code_start|> if dirname == '':
rootpos = 'y'
'''
dirname = raw_input(
'What do you want your destination folder to be called?\n'
)
'''
relative_path = normpath.split(os.sep)[-1]
# or hardcode
destination_final_path = os.path.join(destin... | desktop_logs_dir = make_desktop_logs_dir() |
Here is a snippet: <|code_start|> if os.path.isdir(dircheck):
source = check_for_sip(args.source)
destination = os.path.join(args.destination, os.path.basename(args.source))
os.makedirs(destination)
else:
source = os.path.abspath(args.source)
destination = ... | desktop_manifest_dir = make_desktop_manifest_dir() |
Predict the next line after this snippet: <|code_start|> last_percent_done = 0
md5_object = hashlib.md5()
total_size = os.path.getsize(filename)
with open(str(filename), 'rb') as file_object:
while True:
buf = file_object.read(2**20)
if not buf:
break
... | generate_log( |
Continue the code snippet: <|code_start|> objects_dir = os.path.join(sip_path, 'objects')
uuid = os.path.basename(sip_path)
old_basename, ext = os.path.splitext(item)
new_path = os.path.join(objects_dir, uuid + ext)
os.rename(os.path.join(ob... | print(("%-*s : copyit job was a %s" % (50, os.path.basename(i)[:-24], analyze_log(i)))) |
Here is a snippet: <|code_start|> print('Exiting as you selected -dryrun')
sys.exit()
logs = []
if args.y:
proceed = 'Y'
else:
proceed = ififuncs.ask_yes_no(
'Do you want to proceed?'
)
if proceed == 'Y':
for sips in sorted(oe_dict):
... | print(("%-*s : copyit job was a %s" % (50, os.path.basename(i), analyze_log(i)))) |
Here is a snippet: <|code_start|> 'Accepts a parent folder as input and will generate manifest for each subfolder.'
' Designed for a specific IFI Irish Film Archive workflow. '
'Written by Kieran O\'Leary.'
)
parser.add_argument(
'input', help='file path of parent directory'
)... | hashlib_manifest(full_path, manifest_textfile, full_path) |
Predict the next line after this snippet: <|code_start|> '''
parser = argparse.ArgumentParser(
description='Batch MD5 checksum generator.'
'Accepts a parent folder as input and will generate manifest for each subfolder.'
' Designed for a specific IFI Irish Film Archive workflow. '
... | generate_log(log_name, 'batchfixity started') |
Next line prediction: <|code_start|> Remove a file or directory (including contents).
Ignore if it doesn't exist.
'''
try:
os.remove(path)
except OSError as e:
if e.errno == errno.ENOENT:
pass
elif e.errno in (errno.EISDIR,
# Windows gives EACCES when you try to unlink a directory,
# because ERROR_DI... | if IS_WINDOWS: |
Given snippet: <|code_start|> self.checksum = None
self.clobbers = False
self.runid = None
if file is None:
self.rules.append(NeverBuilt())
else:
version_line = file.readline().strip()
_log.trace("version_line: %s" % (version_line,))
if not version_line.startswith('version:'): raise ValueError("In... | assert isinstance(builder, Builder) |
Continue the code snippet: <|code_start|> def __init__(self, p):
self.path = p
def __repr__(self):
return 'TargetState(%r)' % (self.path,)
@staticmethod
def built_targets(dir):
'''
Returns the target names which have metadata stored in `dir`
'''
for f in os.listdir(dir):
_log.trace("checking file ... | self._dep_lock = Lock(self._ensure_meta_path('deps-lock')) |
Predict the next line after this snippet: <|code_start|> return getattr(cls, 'deserialize', cls)(*fields)
def append_to(self, file):
line = self.tag + ' ' + ' '.join(self.fields)
assert "\n" not in line
file.write(line + "\n")
def __repr__(self):
return '%s(%s)' % (type(self).__name__, ', '.join(map(repr,... | rel_path = os.path.relpath(resolve_base(path), rel_root) |
Next line prediction: <|code_start|>
@classmethod
def deserialize(cls, mtime):
return cls(int(mtime))
def is_dirty(self, args):
path = args.deps.path
mtime = get_mtime(path)
assert mtime is not None
_log.debug("comparing stored mtime %s to %s", self.value, mtime)
if mtime != self.value:
log_method ... | return cls(RUN_ID) |
Based on the snippet: <|code_start|> except IOError as e:
if e.errno != errno.ENOENT: raise
else:
try:
with f:
rv = Dependencies(self.path, f)
except VersionMismatch as e:
_log.debug("Ignoring stored dependencies from incompatible version: %s", deps_path)
except Exception as e:
... | raise SafeError("Build script not found: %s" % (exe)) |
Continue the code snippet: <|code_start|>
# By default, no output colouring.
RED = ""
GREEN = ""
YELLOW = ""
BOLD = ""
PLAIN = ""
_want_color = os.environ.get('GUP_COLOR', 'auto')
if _want_color == '1' or (
_want_color == 'auto' and
<|code_end|>
. Use current file imports:
import os, sys
import logging
from... | not IS_WINDOWS and |
Based on the snippet: <|code_start|> _log.trace("build_basedir: %s" % (build_basedir,))
if not self.indirect:
if target_is_builder():
_log.debug("ignoring direct builder for target %s", path)
# gupfiles & scripts can only be built by Gupfile targets, not .gup scripts
return None
return Builder(pat... | script_path = which(script) |
Given the following code snippet before the placeholder: <|code_start|>
def get_builder(self):
path = self.guppath
if not os.path.exists(path):
return None
if os.path.isdir(path):
_log.trace("skipping directory: %s", path)
return None
_log.trace("candidate exists: %s" % (path,))
def target_is_buil... | raise SafeError("Invalid %s: %s%s" % (GUPFILE, path, reason)) |
Predict the next line after this snippet: <|code_start|> if not self.indirect:
if target_is_builder():
_log.debug("ignoring direct builder for target %s", path)
# gupfiles & scripts can only be built by Gupfile targets, not .gup scripts
return None
return Builder(path, self.target, build_basedir, par... | raise SafeError("Build command not found on PATH: %s\n %s(specified in %s)" % (script, INDENT, path)) |
Given the following code snippet before the placeholder: <|code_start|>
# _log = getLogger(__name__)
def resolve_base(p):
return os.path.join(
os.path.realpath(os.path.dirname(p)),
os.path.basename(p)
)
def traverse_from(base, rel, resolve_final=False):
<|code_end|>
, predict the next line using imports from th... | if IS_WINDOWS: |
Given the following code snippet before the placeholder: <|code_start|> signal.alarm(0)
signal.signal(signal.SIGALRM, oldh)
return b and b or None # None means EOF
def _running(self):
"Tell if jobs are running"
return len(self.waitfds)
def start_job(self, jobfunc, donefunc):
"""
Start a job
jobfunc... | except SafeError as e: |
Given the following code snippet before the placeholder: <|code_start|>
def start_job(self, jobfunc, donefunc):
"""
Start a job
jobfunc: executed in the child process
doncfunc: executed in the parent process during a wait or wait_all call
"""
reason = 'build'
assert(self.tokens <= 1)
self._get_token(r... | rv = UNKNOWN_ERROR_CODE |
Given the following code snippet before the placeholder: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either expre... | 4 * BUFSIZE + BUFSIZE // 2, printable=False |
Given snippet: <|code_start|># BEGIN_COPYRIGHT
#
# Copyright 2009-2021 CRS4.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | wd = tempfile.mkdtemp(suffix='_%s' % UNI_CHR) |
Using the snippet: <|code_start|># of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See... | self.data = make_random_data( |
Based on the snippet: <|code_start|>
def lsl(self):
self.__ls(hdfs.lsl, lambda x: x["name"])
def ls(self):
self.__ls(hdfs.ls, lambda x: x)
def mkdir(self):
for wd in self.local_wd, self.hdfs_wd:
d1 = "%s/d1" % wd
d2 = "%s/d2" % d1
hdfs.mkdir(d2)
... | t1 = FSTree(d1) |
Based on the snippet: <|code_start|>
def test_string_as_string(self):
with sercore.FileOutStream(self.fname) as s:
s.write_string(self.STRING)
with sercore.FileInStream(self.fname) as s:
self.assertEqual(s.read_string(), self.STRING)
def test_string_as_bytes(self):
... | self.assertEqual(s.read_vint(), OUTPUT) |
Next line prediction: <|code_start|> def test_string_as_bytes(self):
with sercore.FileOutStream(self.fname) as s:
s.write_string(self.STRING)
with sercore.FileInStream(self.fname) as s:
self.assertEqual(s.read_bytes(), self.STRING.encode("utf8"))
def test_bytes_as_string(... | self.assertEqual(s.read_vint(), PARTITIONED_OUTPUT) |
Given snippet: <|code_start|># BEGIN_COPYRIGHT
#
# Copyright 2009-2021 CRS4.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | suites.append(get_module(module, path).suite()) |
Given the following code snippet before the placeholder: <|code_start|>#
# Copyright 2009-2021 CRS4.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICEN... | ('hdfs://localhost/a/b', ('localhost', DEFAULT_PORT, '/a/b')), |
Predict the next line after this snippet: <|code_start|>def uni_last(tup):
return tup[:-1] + (tup[-1] + UNI_CHR,)
class TestSplit(unittest.TestCase):
def good(self):
cases = [
('hdfs://localhost:9000/', ('localhost', 9000, '/')),
('hdfs://localhost:9000/a/b', ('localhost', 900... | ('a/b', ('default', 0, '/user/%s/a/b' % DEFAULT_USER)), |
Here is a snippet: <|code_start|>#
# Copyright 2009-2021 CRS4.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | suites.append(get_module(module, path).suite()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.