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 _umask(self):
"""Return the current umask.""" |
if self.filesystem.is_windows_fs:
# windows always returns 0 - it has no real notion of umask
return 0
if sys.platform == 'win32':
# if we are testing Unix under Windows we assume a default mask
return 0o002
else:
# under Unix, we return the real umask;
# as there is no pure getter for umask, so we have to first
# set a mode to get the previous one and then re-set that
mask = os.umask(0)
os.umask(mask)
return mask |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self, file_path, flags, mode=None, dir_fd=None):
"""Return the file descriptor for a FakeFile. Args: file_path: the path to the file flags: low-level bits to indicate io operation mode: bits to define default permissions Note: only basic modes are supported, OS-specific modes are ignored dir_fd: If not `None`, the file descriptor of a directory, with `file_path` being relative to this directory. New in Python 3.3. Returns: A file descriptor. Raises: IOError: if the path cannot be found ValueError: if invalid mode is given NotImplementedError: if `os.O_EXCL` is used without `os.O_CREAT` """ |
file_path = self._path_with_dir_fd(file_path, self.open, dir_fd)
if mode is None:
if self.filesystem.is_windows_fs:
mode = 0o666
else:
mode = 0o777 & ~self._umask()
open_modes = _OpenModes(
must_exist=not flags & os.O_CREAT,
can_read=not flags & os.O_WRONLY,
can_write=flags & (os.O_RDWR | os.O_WRONLY),
truncate=flags & os.O_TRUNC,
append=flags & os.O_APPEND,
must_not_exist=flags & os.O_EXCL
)
if open_modes.must_not_exist and open_modes.must_exist:
raise NotImplementedError(
'O_EXCL without O_CREAT mode is not supported')
if (not self.filesystem.is_windows_fs and
self.filesystem.exists(file_path)):
# handle opening directory - only allowed under Posix
# with read-only mode
obj = self.filesystem.resolve(file_path)
if isinstance(obj, FakeDirectory):
if ((not open_modes.must_exist and
not self.filesystem.is_macos)
or open_modes.can_write):
self.filesystem.raise_os_error(errno.EISDIR, file_path)
dir_wrapper = FakeDirWrapper(obj, file_path, self.filesystem)
file_des = self.filesystem._add_open_file(dir_wrapper)
dir_wrapper.filedes = file_des
return file_des
# low level open is always binary
str_flags = 'b'
delete_on_close = False
if hasattr(os, 'O_TEMPORARY'):
delete_on_close = flags & os.O_TEMPORARY == os.O_TEMPORARY
fake_file = FakeFileOpen(
self.filesystem, delete_on_close=delete_on_close, raw_io=True)(
file_path, str_flags, open_modes=open_modes)
if fake_file.file_object != self.filesystem.dev_null:
self.chmod(file_path, mode)
return fake_file.fileno() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self, file_des):
"""Close a file descriptor. Args: file_des: An integer file descriptor for the file object requested. Raises: OSError: bad file descriptor. TypeError: if file descriptor is not an integer. """ |
file_handle = self.filesystem.get_open_file(file_des)
file_handle.close() |
<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(self, file_des, num_bytes):
"""Read number of bytes from a file descriptor, returns bytes read. Args: file_des: An integer file descriptor for the file object requested. num_bytes: Number of bytes to read from file. Returns: Bytes read from file. Raises: OSError: bad file descriptor. TypeError: if file descriptor is not an integer. """ |
file_handle = self.filesystem.get_open_file(file_des)
file_handle.raw_io = True
return file_handle.read(num_bytes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, file_des, contents):
"""Write string to file descriptor, returns number of bytes written. Args: file_des: An integer file descriptor for the file object requested. contents: String of bytes to write to file. Returns: Number of bytes written. Raises: OSError: bad file descriptor. TypeError: if file descriptor is not an integer. """ |
file_handle = self.filesystem.get_open_file(file_des)
if isinstance(file_handle, FakeDirWrapper):
self.filesystem.raise_os_error(errno.EBADF, file_handle.file_path)
if isinstance(file_handle, FakePipeWrapper):
return file_handle.write(contents)
file_handle.raw_io = True
file_handle._sync_io()
file_handle.update_flush_pos()
file_handle.write(contents)
file_handle.flush()
return len(contents) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fstat(self, file_des):
"""Return the os.stat-like tuple for the FakeFile object of file_des. Args: file_des: The file descriptor of filesystem object to retrieve. Returns: The FakeStatResult object corresponding to entry_path. Raises: OSError: if the filesystem object doesn't exist. """ |
# stat should return the tuple representing return value of os.stat
file_object = self.filesystem.get_open_file(file_des).get_object()
return file_object.stat_result.copy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def umask(self, new_mask):
"""Change the current umask. Args: new_mask: (int) The new umask value. Returns: The old umask. Raises: TypeError: if new_mask is of an invalid type. """ |
if not is_int_type(new_mask):
raise TypeError('an integer is required')
old_umask = self.filesystem.umask
self.filesystem.umask = new_mask
return old_umask |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chdir(self, target_directory):
"""Change current working directory to target directory. Args: target_directory: The path to new current working directory. Raises: OSError: if user lacks permission to enter the argument directory or if the target is not a directory. """ |
target_directory = self.filesystem.resolve_path(
target_directory, allow_fd=True)
self.filesystem.confirmdir(target_directory)
directory = self.filesystem.resolve(target_directory)
# A full implementation would check permissions all the way
# up the tree.
if not is_root() and not directory.st_mode | PERM_EXE:
self.filesystem.raise_os_error(errno.EACCES, directory)
self.filesystem.cwd = target_directory |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lstat(self, entry_path, dir_fd=None):
"""Return the os.stat-like tuple for entry_path, not following symlinks. Args: entry_path: path to filesystem object to retrieve. dir_fd: If not `None`, the file descriptor of a directory, with `entry_path` being relative to this directory. New in Python 3.3. Returns: the FakeStatResult object corresponding to `entry_path`. Raises: OSError: if the filesystem object doesn't exist. """ |
# stat should return the tuple representing return value of os.stat
entry_path = self._path_with_dir_fd(entry_path, self.lstat, dir_fd)
return self.filesystem.stat(entry_path, follow_symlinks=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 removedirs(self, target_directory):
"""Remove a leaf fake directory and all empty intermediate ones. Args: target_directory: the directory to be removed. Raises: OSError: if target_directory does not exist or is not a directory. OSError: if target_directory is not empty. """ |
target_directory = self.filesystem.absnormpath(target_directory)
directory = self.filesystem.confirmdir(target_directory)
if directory.contents:
self.filesystem.raise_os_error(
errno.ENOTEMPTY, self.path.basename(target_directory))
else:
self.rmdir(target_directory)
head, tail = self.path.split(target_directory)
if not tail:
head, tail = self.path.split(head)
while head and tail:
head_dir = self.filesystem.confirmdir(head)
if head_dir.contents:
break
# only the top-level dir may not be a symlink
self.filesystem.rmdir(head, allow_symlink=True)
head, tail = self.path.split(head) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=None):
"""Create a leaf Fake directory + create any non-existent parent dirs. Args: dir_name: (str) Name of directory to create. mode: (int) Mode to create directory (and any necessary parent directories) with. This argument defaults to 0o777. The umask is applied to this mode. exist_ok: (boolean) If exist_ok is False (the default), an OSError is raised if the target directory already exists. New in Python 3.2. Raises: OSError: if the directory already exists and exist_ok=False, or as per :py:meth:`FakeFilesystem.create_dir`. """ |
if exist_ok is None:
exist_ok = False
elif sys.version_info < (3, 2):
raise TypeError("makedir() got an unexpected "
"keyword argument 'exist_ok'")
self.filesystem.makedirs(dir_name, mode, exist_ok) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _path_with_dir_fd(self, path, fct, dir_fd):
"""Return the path considering dir_fd. Raise on nmvalid parameters.""" |
if dir_fd is not None:
if sys.version_info < (3, 3):
raise TypeError("%s() got an unexpected keyword "
"argument 'dir_fd'" % fct.__name__)
# check if fd is supported for the built-in real function
real_fct = getattr(os, fct.__name__)
if real_fct not in self.supports_dir_fd:
raise NotImplementedError(
'dir_fd unavailable on this platform')
if isinstance(path, int):
raise ValueError("%s: Can't specify dir_fd without "
"matching path" % fct.__name__)
if not self.path.isabs(path):
return self.path.join(
self.filesystem.get_open_file(
dir_fd).get_object().path, path)
return 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 access(self, path, mode, dir_fd=None, follow_symlinks=None):
"""Check if a file exists and has the specified permissions. Args: path: (str) Path to the file. mode: (int) Permissions represented as a bitwise-OR combination of os.F_OK, os.R_OK, os.W_OK, and os.X_OK. dir_fd: If not `None`, the file descriptor of a directory, with `path` being relative to this directory. New in Python 3.3. follow_symlinks: (bool) If `False` and `path` points to a symlink, the link itself is queried instead of the linked object. New in Python 3.3. Returns: bool, `True` if file is accessible, `False` otherwise. """ |
if follow_symlinks is not None and sys.version_info < (3, 3):
raise TypeError("access() got an unexpected "
"keyword argument 'follow_symlinks'")
path = self._path_with_dir_fd(path, self.access, dir_fd)
try:
stat_result = self.stat(path, follow_symlinks=follow_symlinks)
except OSError as os_error:
if os_error.errno == errno.ENOENT:
return False
raise
if is_root():
mode &= ~os.W_OK
return (mode & ((stat_result.st_mode >> 6) & 7)) == mode |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lchmod(self, path, mode):
"""Change the permissions of a file as encoded in integer mode. If the file is a link, the permissions of the link are changed. Args: path: (str) Path to the file. mode: (int) Permissions. """ |
if self.filesystem.is_windows_fs:
raise (NameError, "name 'lchmod' is not defined")
self.filesystem.chmod(path, mode, follow_symlinks=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 chown(self, path, uid, gid, dir_fd=None, follow_symlinks=None):
"""Set ownership of a faked file. Args: path: (str) Path to the file or directory. uid: (int) Numeric uid to set the file or directory to. gid: (int) Numeric gid to set the file or directory to. dir_fd: (int) If not `None`, the file descriptor of a directory, with `path` being relative to this directory. New in Python 3.3. follow_symlinks: (bool) If `False` and path points to a symlink, the link itself is changed instead of the linked object. New in Python 3.3. Raises: OSError: if path does not exist. `None` is also allowed for `uid` and `gid`. This permits `os.rename` to use `os.chown` even when the source file `uid` and `gid` are `None` (unset). """ |
if follow_symlinks is None:
follow_symlinks = True
elif sys.version_info < (3, 3):
raise TypeError(
"chown() got an unexpected keyword argument 'follow_symlinks'")
path = self._path_with_dir_fd(path, self.chown, dir_fd)
try:
file_object = self.filesystem.resolve(
path, follow_symlinks, allow_fd=True)
except IOError as io_error:
if io_error.errno == errno.ENOENT:
self.filesystem.raise_os_error(errno.ENOENT, path)
raise
if not ((is_int_type(uid) or uid is None) and
(is_int_type(gid) or gid is None)):
raise TypeError("An integer is required")
if uid != -1:
file_object.st_uid = uid
if gid != -1:
file_object.st_gid = gid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mknod(self, filename, mode=None, device=None, dir_fd=None):
"""Create a filesystem node named 'filename'. Does not support device special files or named pipes as the real os module does. Args: filename: (str) Name of the file to create mode: (int) Permissions to use and type of file to be created. Default permissions are 0o666. Only the stat.S_IFREG file type is supported by the fake implementation. The umask is applied to this mode. device: not supported in fake implementation dir_fd: If not `None`, the file descriptor of a directory, with `filename` being relative to this directory. New in Python 3.3. Raises: OSError: if called with unsupported options or the file can not be created. """ |
if self.filesystem.is_windows_fs:
raise(AttributeError, "module 'os' has no attribute 'mknode'")
if mode is None:
# note that a default value of 0o600 without a device type is
# documented - this is not how it seems to work
mode = S_IFREG | 0o600
if device or not mode & S_IFREG and not is_root():
self.filesystem.raise_os_error(errno.EPERM)
filename = self._path_with_dir_fd(filename, self.mknod, dir_fd)
head, tail = self.path.split(filename)
if not tail:
if self.filesystem.exists(head, check_link=True):
self.filesystem.raise_os_error(errno.EEXIST, filename)
self.filesystem.raise_os_error(errno.ENOENT, filename)
if tail in (b'.', u'.', b'..', u'..'):
self.filesystem.raise_os_error(errno.ENOENT, filename)
if self.filesystem.exists(filename, check_link=True):
self.filesystem.raise_os_error(errno.EEXIST, filename)
try:
self.filesystem.add_object(head, FakeFile(
tail, mode & ~self.filesystem.umask,
filesystem=self.filesystem))
except IOError as e:
self.filesystem.raise_os_error(e.errno, 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 symlink(self, link_target, path, dir_fd=None):
"""Creates the specified symlink, pointed at the specified link target. Args: link_target: The target of the symlink. path: Path to the symlink to create. dir_fd: If not `None`, the file descriptor of a directory, with `link_target` being relative to this directory. New in Python 3.3. Raises: OSError: if the file already exists. """ |
link_target = self._path_with_dir_fd(link_target, self.symlink, dir_fd)
self.filesystem.create_symlink(
path, link_target, create_missing_dirs=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 flush(self):
"""Flush file contents to 'disk'.""" |
self._check_open_file()
if self.allow_update and not self.is_stream:
contents = self._io.getvalue()
if self._append:
self._sync_io()
old_contents = (self.file_object.byte_contents
if is_byte_string(contents) else
self.file_object.contents)
contents = old_contents + contents[self._flush_pos:]
self._set_stream_contents(contents)
self.update_flush_pos()
else:
self._io.flush()
if self.file_object.set_contents(contents, self._encoding):
if self._filesystem.is_windows_fs:
self._changed = True
else:
current_time = time.time()
self.file_object.st_ctime = current_time
self.file_object.st_mtime = current_time
self._file_epoch = self.file_object.epoch
if not self.is_stream:
self._flush_related_files() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tell(self):
"""Return the file's current position. Returns: int, file's current position in bytes. """ |
self._check_open_file()
if self._flushes_after_tell():
self.flush()
if not self._append:
return self._io.tell()
if self._read_whence:
write_seek = self._io.tell()
self._io.seek(self._read_seek, self._read_whence)
self._read_seek = self._io.tell()
self._read_whence = 0
self._io.seek(write_seek)
return self._read_seek |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sync_io(self):
"""Update the stream with changes to the file object contents.""" |
if self._file_epoch == self.file_object.epoch:
return
if self._io.binary:
contents = self.file_object.byte_contents
else:
contents = self.file_object.contents
self._set_stream_contents(contents)
self._file_epoch = self.file_object.epoch |
<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_wrappers(self, name):
"""Wrap a stream attribute in a read wrapper. Returns a read_wrapper which tracks our own read pointer since the stream object has no concept of a different read and write pointer. Args: name: The name of the attribute to wrap. Should be a read call. Returns: The read_wrapper function. """ |
io_attr = getattr(self._io, name)
def read_wrapper(*args, **kwargs):
"""Wrap all read calls to the stream object.
We do this to track the read pointer separate from the write
pointer. Anything that wants to read from the stream object
while we're in append mode goes through this.
Args:
*args: pass through args
**kwargs: pass through kwargs
Returns:
Wrapped stream object method
"""
self._io.seek(self._read_seek, self._read_whence)
ret_value = io_attr(*args, **kwargs)
self._read_seek = self._io.tell()
self._read_whence = 0
self._io.seek(0, 2)
return ret_value
return read_wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _other_wrapper(self, name, writing):
"""Wrap a stream attribute in an other_wrapper. Args: name: the name of the stream attribute to wrap. Returns: other_wrapper which is described below. """ |
io_attr = getattr(self._io, name)
def other_wrapper(*args, **kwargs):
"""Wrap all other calls to the stream Object.
We do this to track changes to the write pointer. Anything that
moves the write pointer in a file open for appending should move
the read pointer as well.
Args:
*args: Pass through args.
**kwargs: Pass through kwargs.
Returns:
Wrapped stream object method.
"""
write_seek = self._io.tell()
ret_value = io_attr(*args, **kwargs)
if write_seek != self._io.tell():
self._read_seek = self._io.tell()
self._read_whence = 0
if not writing or not IS_PY2:
return ret_value
return other_wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Close the pipe descriptor.""" |
self._filesystem.open_files[self.filedes].remove(self)
os.close(self.fd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, file_, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, open_modes=None):
"""Return a file-like object with the contents of the target file object. Args: file_: Path to target file or a file descriptor. mode: Additional file modes (all modes in `open()` are supported). buffering: ignored. (Used for signature compliance with __builtin__.open) encoding: The encoding used to encode unicode strings / decode bytes. errors: (str) Defines how encoding errors are handled. newline: Controls universal newlines, passed to stream object. closefd: If a file descriptor rather than file name is passed, and this is set to `False`, then the file descriptor is kept open when file is closed. opener: not supported. open_modes: Modes for opening files if called from low-level API. Returns: A file-like object containing the contents of the target file. Raises: IOError, OSError depending on Python version / call mode: - if the target object is a directory - on an invalid path - if the file does not exist when it should - if the file exists but should not - if permission is denied ValueError: for an invalid mode or mode combination """ |
binary = 'b' in mode
newline, open_modes = self._handle_file_mode(mode, newline, open_modes)
file_object, file_path, filedes, real_path = self._handle_file_arg(
file_)
if not filedes:
closefd = True
error_fct = (self.filesystem.raise_os_error if self.raw_io
else self.filesystem.raise_io_error)
if (open_modes.must_not_exist and
(file_object or self.filesystem.islink(file_path) and
not self.filesystem.is_windows_fs)):
error_fct(errno.EEXIST, file_path)
if file_object:
if (not is_root() and
((open_modes.can_read and
not file_object.st_mode & PERM_READ)
or (open_modes.can_write and
not file_object.st_mode & PERM_WRITE))):
error_fct(errno.EACCES, file_path)
if open_modes.can_write:
if open_modes.truncate:
file_object.set_contents('')
else:
if open_modes.must_exist:
error_fct(errno.ENOENT, file_path)
if self.filesystem.islink(file_path):
link_object = self.filesystem.resolve(file_path,
follow_symlinks=False)
target_path = link_object.contents
else:
target_path = file_path
if self.filesystem.ends_with_path_separator(target_path):
error = (errno.EINVAL if self.filesystem.is_windows_fs
else errno.ENOENT if self.filesystem.is_macos
else errno.EISDIR)
error_fct(error, file_path)
file_object = self.filesystem.create_file_internally(
real_path, create_missing_dirs=False,
apply_umask=True, raw_io=self.raw_io)
if S_ISDIR(file_object.st_mode):
if self.filesystem.is_windows_fs:
error_fct(errno.EACCES, file_path)
else:
error_fct(errno.EISDIR, file_path)
# If you print obj.name, the argument to open() must be printed.
# Not the abspath, not the filename, but the actual argument.
file_object.opened_as = file_path
if open_modes.truncate:
current_time = time.time()
file_object.st_mtime = current_time
if not self.filesystem.is_windows_fs:
file_object.st_ctime = current_time
fakefile = FakeFileWrapper(file_object,
file_path,
update=open_modes.can_write,
read=open_modes.can_read,
append=open_modes.append,
delete_on_close=self._delete_on_close,
filesystem=self.filesystem,
newline=newline,
binary=binary,
closefd=closefd,
encoding=encoding,
errors=errors,
raw_io=self.raw_io,
use_io=self._use_io)
if filedes is not None:
fakefile.filedes = filedes
# replace the file wrapper
self.filesystem.open_files[filedes].append(fakefile)
else:
fakefile.filedes = self.filesystem._add_open_file(fakefile)
return fakefile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_int_type(val):
"""Return True if `val` is of integer type.""" |
try: # Python 2
return isinstance(val, (int, long))
except NameError: # Python 3
return isinstance(val, int) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Return a copy where the float usage is hard-coded to mimic the behavior of the real os.stat_result. """ |
stat_result = copy(self)
stat_result.use_float = self.use_float
return stat_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 stat_float_times(cls, newvalue=None):
"""Determine whether a file's time stamps are reported as floats or ints. Calling without arguments returns the current value. The value is shared by all instances of FakeOsModule. Args: newvalue: If `True`, mtime, ctime, atime are reported as floats. Otherwise, they are returned as ints (rounding down). """ |
if newvalue is not None:
cls._stat_float_times = bool(newvalue)
return cls._stat_float_times |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def st_ctime(self):
"""Return the creation time in seconds.""" |
ctime = self._st_ctime_ns / 1e9
return ctime if self.use_float else int(ctime) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def st_atime(self):
"""Return the access time in seconds.""" |
atime = self._st_atime_ns / 1e9
return atime if self.use_float else int(atime) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def st_mtime(self):
"""Return the modification time in seconds.""" |
mtime = self._st_mtime_ns / 1e9
return mtime if self.use_float else int(mtime) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_id_type(sid):
"""Method that tries to infer the type of abstract ID. Parameters sid : str The ID of an abstract on Scopus. Raises ------ ValueError If the ID type cannot be inferred. Notes ----- PII usually has 17 chars, but in Scopus there are valid cases with only 16 for old converted articles. Scopus ID contains only digits, but it can have leading zeros. If ID with leading zeros is treated as a number, SyntaxError can occur, or the ID will be rendered invalid and the type will be misinterpreted. """ |
sid = str(sid)
if not sid.isnumeric():
if sid.startswith('2-s2.0-'):
id_type = 'eid'
elif '/' in sid:
id_type = 'doi'
elif 16 <= len(sid) <= 17:
id_type = 'pii'
elif sid.isnumeric():
if len(sid) < 10:
id_type = 'pubmed_id'
else:
id_type = 'scopus_id'
else:
raise ValueError('ID type detection failed for \'{}\'.'.format(sid))
return 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 download(url, params=None, accept="xml", **kwds):
"""Helper function to download a file and return its content. Parameters url : string The URL to be parsed. params : dict (optional) Dictionary containing query parameters. For required keys and accepted values see e.g. https://api.elsevier.com/documentation/AuthorRetrievalAPI.wadl accept : str (optional, default=xml) mime type of the file to be downloaded. Accepted values are json, atom+xml, xml. kwds : key-value parings, optional Keywords passed on to as query parameters. Must contain fields and values specified in the respective API specification. Raises ------ ScopusHtmlError If the status of the response is not ok. ValueError If the accept parameter is not one of the accepted values. Returns ------- resp : byte-like object The content of the file, which needs to be serialized. """ |
# Value check
accepted = ("json", "xml", "atom+xml")
if accept.lower() not in accepted:
raise ValueError('accept parameter must be one of ' +
', '.join(accepted))
# Get credentials
key = config.get('Authentication', 'APIKey')
header = {'X-ELS-APIKey': key}
if config.has_option('Authentication', 'InstToken'):
token = config.get('Authentication', 'InstToken')
header.update({'X-ELS-APIKey': key, 'X-ELS-Insttoken': token})
header.update({'Accept': 'application/{}'.format(accept)})
# Perform request
params.update(**kwds)
resp = requests.get(url, headers=header, params=params)
# Raise error if necessary
try:
reason = resp.reason.upper() + " for url: " + url
raise errors[resp.status_code](reason)
except KeyError: # Exception not specified in scopus
resp.raise_for_status() # Will pass when everything is ok
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name_variants(self):
"""A list of namedtuples representing variants of the affiliation name with number of documents referring to this variant. """ |
out = []
variant = namedtuple('Variant', 'name doc_count')
for var in chained_get(self._json, ['name-variants', 'name-variant'], []):
new = variant(name=var['$'], doc_count=var.get('@doc-count'))
out.append(new)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self):
"""URL to the affiliation's profile page.""" |
url = self.xml.find('coredata/link[@rel="scopus-affiliation"]')
if url is not None:
url = url.get('href')
return url |
<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_date_created(dct):
"""Helper function to parse date-created from profile.""" |
date = dct['date-created']
if date:
return (int(date['@year']), int(date['@month']), int(date['@day']))
else:
return (None, None, 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 affiliation_history(self):
"""Unordered list of IDs of all affiliations the author was affiliated with acccording to Scopus. """ |
affs = self._json.get('affiliation-history', {}).get('affiliation')
try:
return [d['@id'] for d in affs]
except TypeError: # No affiliation history
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 historical_identifier(self):
"""Scopus IDs of previous profiles now compromising this profile.""" |
hist = chained_get(self._json, ["coredata", 'historical-identifier'], [])
return [d['$'].split(":")[-1] for d in hist] or 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 identifier(self):
"""The author's ID. Might differ from the one provided.""" |
ident = self._json['coredata']['dc:identifier'].split(":")[-1]
if ident != self._id:
text = "Profile with ID {} has been merged and the new ID is "\
"{}. Please update your records manually. Files have "\
"been cached with the old ID.".format(self._id, ident)
warn(text, UserWarning)
return ident |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name_variants(self):
"""List of named tuples containing variants of the author name with number of documents published with that variant. """ |
fields = 'indexed_name initials surname given_name doc_count'
variant = namedtuple('Variant', fields)
path = ['author-profile', 'name-variant']
out = [variant(indexed_name=var['indexed-name'], surname=var['surname'],
doc_count=var.get('@doc-count'), initials=var['initials'],
given_name=var.get('given-name'))
for var in listify(chained_get(self._json, path, []))]
return out or 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 publication_range(self):
"""Tuple containing years of first and last publication.""" |
r = self._json['author-profile']['publication-range']
return (r['@start'], r['@end'])
return self._json['coredata'].get('orcid') |
<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_documents(self, subtypes=None, refresh=False):
"""Return list of author's publications using ScopusSearch, which fit a specified set of document subtypes. """ |
search = ScopusSearch('au-id({})'.format(self.identifier), refresh)
if subtypes:
return [p for p in search.results if p.subtype in subtypes]
else:
return search.results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deduplicate(lst):
"""Auxiliary function to deduplicate lst.""" |
out = []
for i in lst:
if i not in out:
out.append(i)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _join(lst, key, sep=";"):
"""Auxiliary function to join same elements of a list of dictionaries if the elements are not None. """ |
return sep.join([d[key] for d in lst if d[key]]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authors(self):
"""A list of scopus_api._ScopusAuthor objects.""" |
authors = self.xml.find('authors', ns)
try:
return [_ScopusAuthor(author) for author in authors]
except TypeError:
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 citedby_url(self):
"""URL to Scopus page listing citing papers.""" |
cite_link = self.coredata.find('link[@rel="scopus-citedby"]', ns)
try:
return cite_link.get('href')
except AttributeError: # cite_link is None
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 scopus_url(self):
"""URL to the abstract page on Scopus.""" |
scopus_url = self.coredata.find('link[@rel="scopus"]', ns)
try:
return scopus_url.get('href')
except AttributeError: # scopus_url is None
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 get_corresponding_author_info(self):
"""Try to get corresponding author information. Returns (scopus-id, name, email). """ |
resp = requests.get(self.scopus_url)
from lxml import html
parsed_doc = html.fromstring(resp.content)
for div in parsed_doc.body.xpath('.//div'):
for a in div.xpath('a'):
if '/cdn-cgi/l/email-protection' not in a.get('href', ''):
continue
encoded_text = a.attrib['href'].replace('/cdn-cgi/l/email-protection#', '')
key = int(encoded_text[0:2], 16)
email = ''.join([chr(int('0x{}'.format(x), 16) ^ key)
for x in
map(''.join, zip(*[iter(encoded_text[2:])]*2))])
for aa in div.xpath('a'):
if 'http://www.scopus.com/authid/detail.url' in aa.get('href', ''):
scopus_url = aa.attrib['href']
name = aa.text
else:
scopus_url, name = None, None
return (scopus_url, name, email) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def latex(self):
"""Return LaTeX representation of the abstract.""" |
s = ('{authors}, \\textit{{{title}}}, {journal}, {volissue}, '
'{pages}, ({date}). {doi}, {scopus_url}.')
if len(self.authors) > 1:
authors = ', '.join([str(a.given_name) +
' ' + str(a.surname)
for a in self.authors[0:-1]])
authors += (' and ' +
str(self.authors[-1].given_name) +
' ' + str(self.authors[-1].surname))
else:
a = self.authors[0]
authors = str(a.given_name) + ' ' + str(a.surname)
title = self.title
journal = self.publicationName
volume = self.volume
issue = self.issueIdentifier
if volume and issue:
volissue = '\\textbf{{{0}({1})}}'.format(volume, issue)
elif volume:
volissue = '\\textbf{{0}}'.format(volume)
else:
volissue = 'no volume'
date = self.coverDate
if self.pageRange:
pages = 'p. {0}'.format(self.pageRange)
elif self.startingPage:
pages = 'p. {self.startingPage}'.format(self)
elif self.article_number:
pages = 'Art. No. {self.article_number}, '.format(self)
else:
pages = '(no pages found)'
doi = '\\href{{https://doi.org/{0}}}{{doi:{0}}}'.format(self.doi)
scopus_url = '\\href{{{0}}}{{scopus:{1}}}'.format(self.scopus_url,
self.eid)
return s.format(**locals()) |
<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):
"""Returns an HTML citation.""" |
s = (u'{authors}, {title}, {journal}, {volissue}, {pages}, '
'({date}). {doi}.')
au_link = ('<a href="https://www.scopus.com/authid/detail.url'
'?origin=AuthorProfile&authorId={0}">{1}</a>')
if len(self.authors) > 1:
authors = u', '.join([au_link.format(a.auid,
(str(a.given_name) +
' ' + str(a.surname)))
for a in self.authors[0:-1]])
authors += (u' and ' +
au_link.format(self.authors[-1].auid,
(str(self.authors[-1].given_name) +
' ' +
str(self.authors[-1].surname))))
else:
a = self.authors[0]
authors = au_link.format(a.auid,
str(a.given_name) + ' ' + str(a.surname))
title = u'<a href="{link}">{title}</a>'.format(link=self.scopus_url,
title=self.title)
jname = self.publicationName
sid = self.source_id
jlink = ('<a href="https://www.scopus.com/source/sourceInfo.url'
'?sourceId={sid}">{journal}</a>')
journal = jlink.format(sid=sid, journal=jname)
volume = self.volume
issue = self.issueIdentifier
if volume and issue:
volissue = u'<b>{0}({1})</b>'.format(volume, issue)
elif volume:
volissue = u'<b>{0}</b>'.format(volume)
else:
volissue = 'no volume'
date = self.coverDate
if self.pageRange:
pages = u'p. {0}'.format(self.pageRange)
elif self.startingPage:
pages = u'p. {self.startingPage}'.format(self=self)
elif self.article_number:
pages = u'Art. No. {self.article_number}, '.format(self=self)
else:
pages = '(no pages found)'
doi = '<a href="https://doi.org/{0}">doi:{0}</a>'.format(self.doi)
html = s.format(**locals())
return html.replace('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 cc(self):
"""List of tuples of yearly number of citations for specified years.""" |
_years = range(self._start, self._end+1)
try:
return list(zip(_years, [d.get('$') for d in self._citeInfoMatrix['cc']]))
except AttributeError: # No citations
return list(zip(_years, [0]*len(_years))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def affiliation_history(self):
"""List of ScopusAffiliation objects representing former affiliations of the author. Only affiliations with more than one publication are considered. """ |
aff_ids = [e.attrib.get('affiliation-id') for e in
self.xml.findall('author-profile/affiliation-history/affiliation')
if e is not None and len(list(e.find("ip-doc").iter())) > 1]
return [ScopusAffiliation(aff_id) for aff_id in aff_ids] |
<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_coauthors(self):
"""Return list of coauthors, their scopus-id and research areas.""" |
url = self.xml.find('coredata/link[@rel="coauthor-search"]').get('href')
xml = download(url=url).text.encode('utf-8')
xml = ET.fromstring(xml)
coauthors = []
N = int(get_encoded_text(xml, 'opensearch:totalResults') or 0)
AUTHOR = namedtuple('Author',
['name', 'scopus_id', 'affiliation', 'categories'])
count = 0
while count < N:
params = {'start': count, 'count': 25}
xml = download(url=url, params=params).text.encode('utf-8')
xml = ET.fromstring(xml)
for entry in xml.findall('atom:entry', ns):
given_name = get_encoded_text(entry,
'atom:preferred-name/atom:given-name')
surname = get_encoded_text(entry,
'atom:preferred-name/atom:surname')
coauthor_name = u'{0} {1}'.format(given_name, surname)
scopus_id = get_encoded_text(entry,
'dc:identifier').replace('AUTHOR_ID:', '')
affiliation = get_encoded_text(entry,
'atom:affiliation-current/atom:affiliation-name')
# get categories for this author
s = u', '.join(['{0} ({1})'.format(subject.text,
subject.attrib['frequency'])
for subject in
entry.findall('atom:subject-area', ns)])
coauthors += [AUTHOR(coauthor_name, scopus_id, affiliation, s)]
count += 25
return coauthors |
<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_document_eids(self, *args, **kwds):
"""Return list of EIDs for the author using ScopusSearch.""" |
search = ScopusSearch('au-id({})'.format(self.author_id),
*args, **kwds)
return search.get_eids() |
<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_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch.""" |
return [ScopusAbstract(eid, refresh=refresh)
for eid in self.get_document_eids(refresh=refresh)] |
<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_journal_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch, but only if belonging to a Journal.""" |
return [abstract for abstract in self.get_abstracts(refresh=refresh) if
abstract.aggregationType == 'Journal'] |
<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_document_summary(self, N=None, cite_sort=True, refresh=True):
"""Return a summary string of documents. Parameters N : int or None (optional, default=None) Maximum number of documents to include in the summary. If None, return all documents. cite_sort : bool (optional, default=True) Whether to sort xml by number of citations, in decreasing order, or not. refresh : bool (optional, default=True) Whether to refresh the cached abstract file (if it exists) or not. Returns ------- s : str Text summarizing an author's documents. """ |
abstracts = self.get_abstracts(refresh=refresh)
if cite_sort:
counts = [(a, int(a.citedby_count)) for a in abstracts]
counts.sort(reverse=True, key=itemgetter(1))
abstracts = [a[0] for a in counts]
if N is None:
N = len(abstracts)
s = [u'{0} of {1} documents'.format(N, len(abstracts))]
for i in range(N):
s += ['{0:2d}. {1}\n'.format(i + 1, str(abstracts[i]))]
return '\n'.join(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 author_impact_factor(self, year=2014, refresh=True):
"""Get author_impact_factor for the . Parameters year : int (optional, default=2014) The year based for which the impact factor is to be calculated. refresh : bool (optional, default=True) Whether to refresh the cached search file (if it exists) or not. Returns ------- (ncites, npapers, aif) : tuple of integers The citations count, publication count, and author impact factor. """ |
scopus_abstracts = self.get_journal_abstracts(refresh=refresh)
cites = [int(ab.citedby_count) for ab in scopus_abstracts]
years = [int(ab.coverDate.split('-')[0]) for ab in scopus_abstracts]
data = zip(years, cites, scopus_abstracts)
data = sorted(data, key=itemgetter(1), reverse=True)
# now get aif papers for year-1 and year-2
aif_data = [tup for tup in data if tup[0] in (year - 1, year - 2)]
Ncites = sum([tup[1] for tup in aif_data])
if len(aif_data) > 0:
return (Ncites, len(aif_data), Ncites / float(len(aif_data)))
else:
return (Ncites, len(aif_data), 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 n_first_author_papers(self, refresh=True):
"""Return number of papers with author as the first author.""" |
first_authors = [1 for ab in self.get_journal_abstracts(refresh=refresh)
if ab.authors[0].scopusid == self.author_id]
return sum(first_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 n_yearly_publications(self, refresh=True):
"""Number of journal publications in a given year.""" |
pub_years = [int(ab.coverDate.split('-')[0])
for ab in self.get_journal_abstracts(refresh=refresh)]
return Counter(pub_years) |
<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_org(aff):
"""Auxiliary function to extract org information from affiliation for authorgroup. """ |
try:
org = aff['organization']
if not isinstance(org, str):
try:
org = org['$']
except TypeError: # Multiple names given
org = ', '.join([d['$'] for d in org if d])
except KeyError: # Author group w/o affiliation
org = None
return org |
<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_pages(self, unicode=False):
"""Auxiliary function to parse and format page range of a document.""" |
if self.pageRange:
pages = 'pp. {}'.format(self.pageRange)
elif self.startingPage:
pages = 'pp. {}-{}'.format(self.startingPage, self.endingPage)
else:
pages = '(no pages found)'
if unicode:
pages = u'{}'.format(pages)
return pages |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authkeywords(self):
"""List of author-provided keywords of the abstract.""" |
keywords = self._json['authkeywords']
if keywords is None:
return None
else:
try:
return [d['$'] for d in keywords['author-keyword']]
except TypeError: # Singleton keyword
return [keywords['author-keyword']['$']] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def idxterms(self):
"""List of index terms.""" |
try:
terms = listify(self._json.get("idxterms", {}).get('mainterm', []))
except AttributeError: # idxterms is empty
return None
try:
return [d['$'] for d in terms]
except AttributeError:
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 get_html(self):
"""Bibliographic entry in html format.""" |
# Author links
au_link = ('<a href="https://www.scopus.com/authid/detail.url'
'?origin=AuthorProfile&authorId={0}">{1}</a>')
if len(self.authors) > 1:
authors = u', '.join([au_link.format(a.auid, a.given_name +
' ' + a.surname)
for a in self.authors[0:-1]])
authors += (u' and ' +
au_link.format(self.authors[-1].auid,
(str(self.authors[-1].given_name) +
' ' +
str(self.authors[-1].surname))))
else:
a = self.authors[0]
authors = au_link.format(a.auid, a.given_name + ' ' + a.surname)
title = u'<a href="{}">{}</a>'.format(self.scopus_link, self.title)
if self.volume and self.issueIdentifier:
volissue = u'<b>{}({})</b>'.format(self.volume, self.issueIdentifier)
elif self.volume:
volissue = u'<b>{}</b>'.format(self.volume)
else:
volissue = 'no volume'
jlink = '<a href="https://www.scopus.com/source/sourceInfo.url'\
'?sourceId={}">{}</a>'.format(
self.source_id, self.publicationName)
pages = _parse_pages(self, unicode=True)
s = "{auth}, {title}, {jour}, {volissue}, {pages}, ({year}).".format(
auth=authors, title=title, jour=jlink, volissue=volissue,
pages=pages, year=self.coverDate[:4])
if self.doi:
s += ' <a href="https://doi.org/{0}">doi:{0}</a>.'.format(self.doi)
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_latex(self):
"""Bibliographic entry in LaTeX format.""" |
if len(self.authors) > 1:
authors = _list_authors(self.authors)
else:
a = self.authors
authors = ' '.join([a.given_name, a.surname])
if self.volume and self.issueIdentifier:
volissue = '\\textbf{{{}({})}}'.format(self.volume, self.issueIdentifier)
elif self.volume:
volissue = '\\textbf{{{}}}'.format(self.volume)
else:
volissue = 'no volume'
pages = _parse_pages(self)
s = '{auth}, \\textit{{{title}}}, {jour}, {vol}, {pages} ({year}).'.format(
auth=authors, title=self.title, jour=self.publicationName,
vol=volissue, pages=pages, year=self.coverDate[:4])
if self.doi is not None:
s += ' \\href{{https://doi.org/{0}}}{{doi:{0}}}, '.format(self.doi)
s += '\\href{{{0}}}{{scopus:{1}}}.'.format(self.scopus_link, self.eid)
return 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 _parse(res, params, n, api, **kwds):
"""Auxiliary function to download results and parse json.""" |
cursor = "cursor" in params
if not cursor:
start = params["start"]
if n == 0:
return ""
_json = res.get('search-results', {}).get('entry', [])
# Download the remaining information in chunks
while n > 0:
n -= params["count"]
if cursor:
pointer = res['search-results']['cursor'].get('@next')
params.update({'cursor': pointer})
else:
start += params["count"]
params.update({'start': start})
res = download(url=URL[api], params=params, accept="json", **kwds).json()
_json.extend(res.get('search-results', {}).get('entry', []))
return _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 create_config():
"""Initiates process to generate configuration file.""" |
file_exists = exists(CONFIG_FILE)
if not file_exists:
# Set directories
config.add_section('Directories')
defaults = [
('AbstractRetrieval', expanduser('~/.scopus/abstract_retrieval')),
('AffiliationSearch', expanduser('~/.scopus/affiliation_search')),
('AuthorRetrieval', expanduser('~/.scopus/author_retrieval')),
('AuthorSearch', expanduser('~/.scopus/author_search')),
('CitationOverview', expanduser('~/.scopus/citation_overview')),
('ContentAffiliationRetrieval', expanduser('~/.scopus/affiliation_retrieval')),
('ScopusSearch', expanduser('~/.scopus/scopus_search'))
]
for key, value in defaults:
config.set('Directories', key, value)
if not exists(value):
makedirs(value)
# Set authentication
config.add_section('Authentication')
prompt_key = "Please enter your API Key, obtained from "\
"http://dev.elsevier.com/myapikey.html: \n"
if py3:
key = input(prompt_key)
else:
key = raw_input(prompt_key)
config.set('Authentication', 'APIKey', key)
prompt_token = "API Keys are sufficient for most users. If you "\
"have to use Authtoken authentication, please enter "\
"the token, otherwise press Enter: \n"
if py3:
token = input(prompt_token)
else:
token = raw_input(prompt_token)
if len(token) > 0:
config.set('Authentication', 'InstToken', token)
# Write out
with open(CONFIG_FILE, 'w') as f:
config.write(f)
else:
text = "Configuration file already exists at {}; process to create "\
"the file aborted. Please open the file and edit the "\
"entries manually.".format(CONFIG_FILE)
raise FileExistsError(text) |
<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_encoded_text(container, xpath):
"""Return text for element at xpath in the container xml if it is there. Parameters container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result : str """ |
try:
return "".join(container.find(xpath, ns).itertext())
except AttributeError:
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 main(argv=None):
""" Invoke the cosmic ray evaluation. :param argv: the command line arguments """ |
signal.signal(
signal.SIGINT,
lambda *args: sys.exit(_SIGNAL_EXIT_CODE_BASE + signal.SIGINT))
if hasattr(signal, 'SIGINFO'):
signal.signal(
getattr(signal, 'SIGINFO'),
lambda *args: report_progress(sys.stderr))
try:
return docopt_subcommands.main(
commands=dsc,
argv=argv,
doc_template=DOC_TEMPLATE,
exit_at_end=False)
except docopt.DocoptExit as exc:
print(exc, file=sys.stderr)
return ExitCode.USAGE
except FileNotFoundError as exc:
print(exc, file=sys.stderr)
return ExitCode.NO_INPUT
except PermissionError as exc:
print(exc, file=sys.stderr)
return ExitCode.NO_PERM
except cosmic_ray.config.ConfigError as exc:
print(repr(exc), file=sys.stderr)
if exc.__cause__ is not None:
print(exc.__cause__, file=sys.stderr)
return ExitCode.CONFIG
except subprocess.CalledProcessError as exc:
print('Error in subprocess', file=sys.stderr)
print(exc, file=sys.stderr)
return exc.returncode |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extend_name(suffix):
"""A factory for class decorators that modify the class name by appending some text to it. Example: @extend_name('_Foo') class Class: pass assert Class.__name__ == 'Class_Foo' """ |
def dec(cls):
name = '{}{}'.format(cls.__name__, suffix)
setattr(cls, '__name__', name)
return cls
return dec |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutate(self, node, index):
"""Modify the numeric value on `node`.""" |
assert index < len(OFFSETS), 'received count with no associated offset'
assert isinstance(node, parso.python.tree.Number)
val = eval(node.value) + OFFSETS[index] # pylint: disable=W0123
return parso.python.tree.Number(' ' + str(val), node.start_pos) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _prohibited(from_op, to_op):
"Determines if from_op is allowed to be mutated to to_op."
# 'not' can only be removed but not replaced with
# '+', '-' or '~' b/c that may lead to strange results
if from_op is UnaryOperators.Not:
if to_op is not UnaryOperators.Nothing:
return True
# '+1' => '1' yields equivalent mutations
if from_op is UnaryOperators.UAdd:
if to_op is UnaryOperators.Nothing:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_config(filename=None):
"""Load a configuration from a file or stdin. If `filename` is `None` or "-", then configuration gets read from stdin. Returns: A `ConfigDict`. Raises: ConfigError: If there is an error loading the config. """ |
try:
with _config_stream(filename) as handle:
filename = handle.name
return deserialize_config(handle.read())
except (OSError, toml.TomlDecodeError, UnicodeDecodeError) as exc:
raise ConfigError(
'Error loading configuration from {}'.format(filename)) from exc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _config_stream(filename):
"""Given a configuration's filename, this returns a stream from which a configuration can be read. If `filename` is `None` or '-' then stream will be `sys.stdin`. Otherwise, it's the open file handle for the filename. """ |
if filename is None or filename == '-':
log.info('Reading config from stdin')
yield sys.stdin
else:
with open(filename, mode='rt') as handle:
log.info('Reading config from %r', filename)
yield handle |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sub(self, *segments):
"Get a sub-configuration."
d = self
for segment in segments:
try:
d = d[segment]
except KeyError:
return ConfigDict({})
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def python_version(self):
"""Get the configured Python version. If this is not set in the config, then it defaults to the version of the current runtime. Returns: A string of the form "MAJOR.MINOR", e.g. "3.6". """ |
v = self.get('python-version', '')
if v == '':
v = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
return v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutate(self, node, index):
"""Modify the For loop to evaluate to None""" |
assert index == 0
assert isinstance(node, ForStmt)
empty_list = parso.parse(' []')
node.children[3] = empty_list
return node |
<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_operator(name):
"""Get an operator class from a provider plugin. Attrs: name: The name of the operator class. Returns: The operator *class object* (i.e. not an instance). """ |
sep = name.index('/')
provider_name = name[:sep]
operator_name = name[sep + 1:]
provider = OPERATOR_PROVIDERS[provider_name]
return provider[operator_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 operator_names():
"""Get all operator names. Returns: A sequence of operator names. """ |
return tuple('{}/{}'.format(provider_name, operator_name)
for provider_name, provider in OPERATOR_PROVIDERS.items()
for operator_name in provider) |
<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_execution_engine(name):
"""Get the execution engine by name.""" |
manager = driver.DriverManager(
namespace='cosmic_ray.execution_engines',
name=name,
invoke_on_load=True,
on_load_failure_callback=_log_extension_loading_failure,
)
return manager.driver |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_db(path, mode=WorkDB.Mode.create):
""" Open a DB in file `path` in mode `mode` as a context manager. On exiting the context the DB will be automatically closed. Args: path: The path to the DB file. mode: The mode in which to open the DB. See the `Mode` enum for details. Raises: FileNotFoundError: If `mode` is `Mode.open` and `path` does not exist. """ |
database = WorkDB(path, mode)
try:
yield database
finally:
database.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def work_items(self):
"""An iterable of all of WorkItems in the db. This includes both WorkItems with and without results. """ |
cur = self._conn.cursor()
rows = cur.execute("SELECT * FROM work_items")
for row in rows:
yield _row_to_work_item(row) |
<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):
"""Clear all work items from the session. This removes any associated results as well. """ |
with self._conn:
self._conn.execute('DELETE FROM results')
self._conn.execute('DELETE FROM work_items') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pending_work_items(self):
"Iterable of all pending work items."
pending = self._conn.execute(
"SELECT * FROM work_items WHERE job_id NOT IN (SELECT job_id FROM results)"
)
return (_row_to_work_item(p) for p in pending) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report_xml():
"""cr-xml Usage: cr-xml <session-file> Print an XML formatted report of test results for continuos integration systems """ |
arguments = docopt.docopt(report_xml.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
xml_elem = _create_xml_report(db)
xml_elem.write(
sys.stdout.buffer, encoding='utf-8', xml_declaration=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(db_name):
"""Execute any pending work in the database stored in `db_name`, recording the results. This looks for any work in `db_name` which has no results, schedules it to be executed, and records any results that arrive. """ |
try:
with use_db(db_name, mode=WorkDB.Mode.open) as work_db:
_update_progress(work_db)
config = work_db.get_config()
engine = get_execution_engine(config.execution_engine_name)
def on_task_complete(job_id, work_result):
work_db.set_result(job_id, work_result)
_update_progress(work_db)
log.info("Job %s complete", job_id)
log.info("Beginning execution")
engine(
work_db.pending_work_items,
config,
on_task_complete=on_task_complete)
log.info("Execution finished")
except FileNotFoundError as exc:
raise FileNotFoundError(
str(exc).replace('Requested file', 'Corresponding database',
1)) from exc |
<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_ast(module_path, python_version):
"""Get the AST for the code in a file. Args: module_path: pathlib.Path to the file containing the code. python_version: Python version as a "MAJ.MIN" string. Returns: The parso parse tree for the code in `module_path`. """ |
with module_path.open(mode='rt', encoding='utf-8') as handle:
source = handle.read()
return parso.parse(source, version=python_version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_none(node):
"Determine if a node is the `None` keyword."
return isinstance(node, parso.python.tree.Keyword) and node.value == '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 walk(self, node):
"Walk a parse tree, calling visit for each node."
node = self.visit(node)
if node is None:
return None
if isinstance(node, parso.tree.BaseNode):
walked = map(self.walk, node.children)
node.children = [child for child in walked if child is not None]
return node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_survival_rate():
"""cr-rate Usage: cr-rate <session-file> Calculate the survival rate of a session. """ |
arguments = docopt.docopt(
format_survival_rate.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
rate = survival_rate(db)
print('{:.2f}'.format(rate)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def survival_rate(work_db):
"""Calcuate the survival rate for the results in a WorkDB. """ |
kills = sum(r.is_killed for _, r in work_db.results)
num_results = work_db.num_results
if not num_results:
return 0
return (1 - kills / num_results) * 100 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report_html():
"""cr-html Usage: cr-html <session-file> Print an HTML formatted report of test results. """ |
arguments = docopt.docopt(report_html.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
doc = _generate_html_report(db)
print(doc.getvalue()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report():
"""cr-report Usage: cr-report [--show-output] [--show-diff] [--show-pending] <session-file> Print a nicely formatted report of test results and some basic statistics. options: --show-output Display output of test executions --show-diff Display diff of mutants --show-pending Display results for incomplete tasks """ |
arguments = docopt.docopt(report.__doc__, version='cr-format 0.1')
show_pending = arguments['--show-pending']
show_output = arguments['--show-output']
show_diff = arguments['--show-diff']
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
for work_item, result in db.completed_work_items:
print('{} {} {} {}'.format(work_item.job_id, work_item.module_path,
work_item.operator_name,
work_item.occurrence))
print('worker outcome: {}, test outcome: {}'.format(
result.worker_outcome, result.test_outcome))
if show_output:
print('=== OUTPUT ===')
print(result.output)
print('==============')
if show_diff:
print('=== DIFF ===')
print(result.diff)
print('============')
if show_pending:
for work_item in db.pending_work_items:
print('{} {} {} {}'.format(
work_item.job_id, work_item.module_path,
work_item.operator_name, work_item.occurrence))
num_items = db.num_work_items
num_complete = db.num_results
print('total jobs: {}'.format(num_items))
if num_complete > 0:
print('complete: {} ({:.2f}%)'.format(
num_complete, num_complete / num_items * 100))
print('survival rate: {:.2f}%'.format(survival_rate(db)))
else:
print('no jobs completed') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_config():
"""Prompt user for config variables and generate new config. Returns: A new ConfigDict. """ |
config = ConfigDict()
config["module-path"] = qprompt.ask_str(
"Top-level module path",
blk=False,
vld=os.path.exists,
hlp=MODULE_PATH_HELP)
python_version = qprompt.ask_str(
'Python version (blank for auto detection)',
vld=_validate_python_version,
hlp=PYTHON_VERSION_HELP)
config['python-version'] = python_version
timeout = qprompt.ask_str(
'Test execution timeout (seconds)',
vld=float,
blk=False,
hlp="The number of seconds to let a test run before terminating it.")
config['timeout'] = float(timeout)
config['excluded-modules'] = []
config["test-command"] = qprompt.ask_str(
"Test command",
blk=False,
hlp=TEST_COMMAND_HELP)
menu = qprompt.Menu()
for at_pos, engine_name in enumerate(execution_engine_names()):
menu.add(str(at_pos), engine_name)
config["execution-engine"] = ConfigDict()
config['execution-engine']['name'] = menu.show(header="Execution engine", returns="desc")
config["cloning"] = ConfigDict()
config['cloning']['method'] = 'copy'
config['cloning']['commands'] = []
return 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 init(module_paths, work_db, config):
"""Clear and initialize a work-db with work items. Any existing data in the work-db will be cleared and replaced with entirely new work orders. In particular, this means that any results in the db are removed. Args: module_paths: iterable of pathlib.Paths of modules to mutate. work_db: A `WorkDB` instance into which the work orders will be saved. config: The configuration for the new session. """ |
operator_names = cosmic_ray.plugins.operator_names()
work_db.set_config(config=config)
work_db.clear()
for module_path in module_paths:
module_ast = get_ast(
module_path, python_version=config.python_version)
for op_name in operator_names:
operator = get_operator(op_name)(config.python_version)
visitor = WorkDBInitVisitor(module_path, op_name, work_db,
operator)
visitor.walk(module_ast)
apply_interceptors(work_db, config.sub('interceptors').get('enabled', ())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_interceptors(work_db, enabled_interceptors):
"""Apply each registered interceptor to the WorkDB.""" |
names = (name for name in interceptor_names() if name in enabled_interceptors)
for name in names:
interceptor = get_interceptor(name)
interceptor(work_db) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _allowed(to_op, from_op, rhs):
"Determine if a mutation from `from_op` to `to_op` is allowed given a particular `rhs` node."
if is_none(rhs):
return to_op in _RHS_IS_NONE_OPS.get(from_op, ())
if is_number(rhs):
return to_op in _RHS_IS_INTEGER_OPS
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def worker(module_path, python_version, operator_name, occurrence, test_command, timeout):
"""Mutate the OCCURRENCE-th site for OPERATOR_NAME in MODULE_PATH, run the tests, and report the results. This is fundamentally the single-mutation-and-test-run process implementation. There are three high-level ways that a worker can finish. First, it could fail exceptionally, meaning that some uncaught exception made its way from some part of the operation to terminate the function. This function will intercept all exceptions and return it in a non-exceptional structure. Second, the mutation testing machinery may determine that there is no OCCURENCE-th instance for OPERATOR_NAME in the module under test. In this case there is no way to report a test result (i.e. killed, survived, or incompetent) so a special value is returned indicating that no mutation is possible. Finally, and hopefully normally, the worker will find that it can run a test. It will do so and report back the result - killed, survived, or incompetent - in a structured way. Args: module_name: The path to the module to mutate python_version: The version of Python to use when interpreting the code in `module_path`. A string of the form "MAJOR.MINOR", e.g. "3.6" for Python 3.6.x. operator_name: The name of the operator plugin to use occurrence: The occurrence of the operator to apply test_command: The command to execute to run the tests timeout: The maximum amount of time (seconds) to let the tests run Returns: A WorkResult Raises: This will generally not raise any exceptions. Rather, exceptions will be reported using the 'exception' result-type in the return value. """ |
try:
operator_class = cosmic_ray.plugins.get_operator(operator_name)
operator = operator_class(python_version)
with cosmic_ray.mutating.use_mutation(module_path, operator,
occurrence) as (original_code,
mutated_code):
if mutated_code is None:
return WorkResult(worker_outcome=WorkerOutcome.NO_TEST)
test_outcome, output = run_tests(test_command, timeout)
diff = _make_diff(original_code, mutated_code, module_path)
return WorkResult(
output=output,
diff='\n'.join(diff),
test_outcome=test_outcome,
worker_outcome=WorkerOutcome.NORMAL)
except Exception: # noqa # pylint: disable=broad-except
return WorkResult(
output=traceback.format_exc(),
test_outcome=TestOutcome.INCOMPETENT,
worker_outcome=WorkerOutcome.EXCEPTION) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report_progress(stream=None):
"""Report progress from any currently installed reporters. Args: stream: The text stream (default: sys.stderr) to which progress will be reported. """ |
if stream is None:
stream = sys.stderr
for reporter in _reporters:
reporter(stream) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reports_progress(reporter):
"""A decorator factory to mark functions which report progress. Args: reporter: A zero-argument callable to report progress. The callable provided should have the means to both retrieve and display current progress information. """ |
def decorator(func): # pylint: disable=missing-docstring
@wraps(func)
def wrapper(*args, **kwargs): # pylint: disable=missing-docstring
with progress_reporter(reporter):
return func(*args, **kwargs)
return wrapper
return decorator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.