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 get_packages(dname, pkgname=None, results=None, ignore=None, parent=None): """ Get all packages which are under dname. This is necessary for Python 2.2's distutils. Pretty similar arguments to getDataFiles, including 'parent'. """
parent = parent or "" prefix = [] if parent: prefix = [parent] bname = os.path.basename(dname) ignore = ignore or [] if bname in ignore: return [] if results is None: results = [] if pkgname is None: pkgname = [] subfiles = os.listdir(dname) abssubfiles = [os.path.join(dname, x) for x in subfiles] if '__init__.py' in subfiles: results.append(prefix + pkgname + [bname]) for subdir in filter(os.path.isdir, abssubfiles): get_packages(subdir, pkgname=pkgname + [bname], results=results, ignore=ignore, parent=parent) res = ['.'.join(result) for result in results] return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_data_files(dname, ignore=None, parent=None): """ Get all the data files that should be included in this distutils Project. 'dname' should be the path to the package that you're distributing. 'ignore' is a list of sub-packages to ignore. This facilitates disparate package hierarchies. That's a fancy way of saying that the 'twisted' package doesn't want to include the 'twisted.conch' package, so it will pass ['conch'] as the value. 'parent' is necessary if you're distributing a subpackage like twisted.conch. 'dname' should point to 'twisted/conch' and 'parent' should point to 'twisted'. This ensures that your data_files are generated correctly, only using relative paths for the first element of the tuple ('twisted/conch/*'). The default 'parent' is the current working directory. """
parent = parent or "." ignore = ignore or [] result = [] for directory, subdirectories, filenames in os.walk(dname): resultfiles = [] for exname in EXCLUDE_NAMES: if exname in subdirectories: subdirectories.remove(exname) for ig in ignore: if ig in subdirectories: subdirectories.remove(ig) for filename in _filter_names(filenames): resultfiles.append(filename) if resultfiles: for filename in resultfiles: file_path = os.path.join(directory, filename) if parent: file_path = file_path.replace(parent + os.sep, '') result.append(file_path) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acquire(self): """ Acquire thread and file locks. Re-opening log for 'degraded' mode. """
# handle thread lock if Handler: # under some tests Handler ends up being null due to instantiation # order Handler.acquire(self) # Issue a file lock. (This is inefficient for multiple active threads # within a single process. But if you're worried about high-performance, # you probably aren't using this log handler.) if self.stream_lock: # If stream_lock=None, then assume close() was called or something # else weird and ignore all file-level locks. if self.stream_lock.closed: # Daemonization can close all open file descriptors, see # https://bugzilla.redhat.com/show_bug.cgi?id=952929 # Try opening the lock file again. Should we warn() here?!? try: self._open_lockfile() except Exception: self.handleError(NullLogRecord()) # Don't try to open the stream lock again self.stream_lock = None return lock(self.stream_lock, LOCK_EX)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(self): """ Release file and thread locks. If in 'degraded' mode, close the stream to reduce contention until the log files can be rotated. """
try: if self._rotateFailed: self._close() except Exception: self.handleError(NullLogRecord()) finally: try: if self.stream_lock and not self.stream_lock.closed: unlock(self.stream_lock) except Exception: self.handleError(NullLogRecord()) finally: # release thread lock if Handler: Handler.release(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _degrade(self, degrade, msg, *args): """ Set degrade mode or not. Ignore msg. """
self._rotateFailed = degrade del msg, args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crossdomain(f): """This decorator sets the rules for the crossdomain request per http method. The settings are taken from the actual resource itself, and returned as per the CORS spec. All CORS requests are rejected if the resource's `allow_methods` doesn't include the 'OPTIONS' method. """
@wraps(f) def decorator(self, *args, **kwargs): # TODO: if a non-cors request has the origin header, this will fail if not self.cors_enabled and 'origin' in request.headers: return self._make_response(405, "CORS request rejected") resp = f(self, *args, **kwargs) h = resp.headers current_app.logger.debug("Request Headers: {}".format(request.headers)) allowed_methods = self.cors_config['methods'] + ["OPTIONS"] h['Access-Control-Allow-Methods'] = ", ".join(allowed_methods) h['Access-Control-Max-Age'] = self.cors_config.get('max_age', 21600) # Request Origin checks hostname = urlparse(request.headers['origin']).netloc \ if 'origin' in request.headers else request.headers['host'] if hostname in self.cors_config.get('blacklist', []): return self._make_response(405, "CORS request blacklisted") if self.cors_config.get('allowed', None) is not None and \ hostname not in self.cors_config.get('allowed', None): return self._make_response(405, "CORS request refused") if 'origin' in request.headers: h['Access-Control-Allow-Origin'] = request.headers['origin'] # Request header checks if 'access-control-request-headers' in request.headers: if self.cors_config.get('headers', None) is None: allowed_headers = \ request.headers.get('access-control-request-headers', "*") else: allowed_headers = [] for k in request.headers.get( 'access-control-request-headers', []): if k in self.cors_config.get('headers', []): allowed_headers.append(k) allowed_headers = " ,".join(allowed_headers) h['Access-Control-Allow-Headers'] = allowed_headers return resp return decorator
<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_backend_instance(self, backend: BackendDefinitionType) -> BaseBackend: """ Returns a backend instance, either from the argument or from the settings. :raise ArcaMisconfigured: If the instance is not a subclass of :class:`BaseBackend` """
if backend is NOT_SET: backend = self.get_setting("backend", "arca.CurrentEnvironmentBackend") if isinstance(backend, str): backend = load_class(backend) if callable(backend): backend = backend() if not issubclass(type(backend), BaseBackend): raise ArcaMisconfigured(f"{type(backend)} is not an subclass of BaseBackend") return backend
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_repo_url(self, repo: str): """ Validates repo URL - if it's a valid git URL and if Arca can handle that type of repo URL :raise ValueError: If the URL is not valid """
# that should match valid git repos if not isinstance(repo, str) or not re.match(r"^(https?|file)://[\w._\-/~]*[.git]?/?$", repo): raise ValueError(f"{repo} is not a valid http[s] or file:// git repository.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repo_id(self, repo: str) -> str: """ Returns an unique identifier from a repo URL for the folder the repo is gonna be pulled in. """
if repo.startswith("http"): repo_id = re.sub(r"https?://(.www)?", "", repo) repo_id = re.sub(r"\.git/?$", "", repo_id) else: repo_id = repo.replace("file://", "") repo_id = re.sub(r"\.git/?$", "", repo_id) if repo_id.startswith("~"): repo_id = str(Path(repo_id).resolve()) # replaces everything that isn't alphanumeric, a dot or an underscore # to make sure it's a valid folder name and to keep it readable # multiple consecutive invalid characters replaced with a single underscore repo_id = re.sub(r"[^a-zA-Z0-9._]+", "_", repo_id) # and add a hash of the original to make it absolutely unique return repo_id + hashlib.sha256(repo.encode("utf-8")).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pull_again(self, repo: Optional[str]=None, branch: Optional[str]=None) -> None: """ When ``single_pull`` is enables, tells Arca to pull again. If ``repo`` and ``branch`` are not specified, pull again everything. :param repo: (Optional) Pull again all branches from a specified repository. :param branch: (Optional) When ``repo`` is specified, pull again only this branch from that repository. :raise ValueError: If ``branch`` is specified and ``repo`` is not. """
if repo is None and branch is None: self._current_hashes = {} elif repo is None: raise ValueError("You can't define just the branch to pull again.") elif branch is None and repo is not None: self._current_hashes.pop(self.repo_id(repo), None) else: repo_id = self.repo_id(repo) try: self._current_hashes[repo_id].pop(branch) except KeyError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_key(self, repo: str, branch: str, task: Task, git_repo: Repo) -> str: """ Returns the key used for storing results in cache. """
return "{repo}_{branch}_{hash}_{task}".format(repo=self.repo_id(repo), branch=branch, hash=self.current_git_hash(repo, branch, git_repo), task=task.hash)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, repo: str, branch: str, task: Task, *, depth: DepthDefinitionType=1, reference: ReferenceDefinitionType=None ) -> Result: """ Runs the ``task`` using the configured backend. :param repo: Target git repository :param branch: Target git branch :param task: Task which will be run in the target repository :param depth: How many commits back should the repo be cloned in case the target repository isn't cloned yet. Defaults to 1, must be bigger than 0. No limit will be used if ``None`` is set. :param reference: A path to a repository from which the target repository is forked, to save bandwidth, `--dissociate` is used if set. :return: A :class:`Result` instance with the output of the task. :raise PullError: If the repository can't be cloned or pulled :raise BuildError: If the task fails. """
self.validate_repo_url(repo) depth = self.validate_depth(depth) reference = self.validate_reference(reference) logger.info("Running Arca task %r for repo '%s' in branch '%s'", task, repo, branch) git_repo, repo_path = self.get_files(repo, branch, depth=depth, reference=reference) def create_value(): logger.debug("Value not in cache, creating.") return self.backend.run(repo, branch, task, git_repo, repo_path) cache_key = self.cache_key(repo, branch, task, git_repo) logger.debug("Cache key is %s", cache_key) return self.region.get_or_create( cache_key, create_value, should_cache_fn=self.should_cache_fn )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def static_filename(self, repo: str, branch: str, relative_path: Union[str, Path], *, depth: DepthDefinitionType=1, reference: ReferenceDefinitionType=None ) -> Path: """ Returns an absolute path to where a file from the repo was cloned to. :param repo: Repo URL :param branch: Branch name :param relative_path: Relative path to the requested file :param depth: See :meth:`run` :param reference: See :meth:`run` :return: Absolute path to the file in the target repository :raise FileOutOfRangeError: If the relative path leads out of the repository path :raise FileNotFoundError: If the file doesn't exist in the repository. """
self.validate_repo_url(repo) depth = self.validate_depth(depth) reference = self.validate_reference(reference) if not isinstance(relative_path, Path): relative_path = Path(relative_path) _, repo_path = self.get_files(repo, branch, depth=depth, reference=reference) result = repo_path / relative_path result = result.resolve() if repo_path not in result.parents: raise FileOutOfRangeError(f"{relative_path} is not inside the repository.") if not result.exists(): raise FileNotFoundError(f"{relative_path} does not exist in the repository.") logger.info("Static path for %s is %s", relative_path, result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_depth(self, depth: DepthDefinitionType) -> Optional[int]: """ Converts the depth to int and validates that the value can be used. :raise ValueError: If the provided depth is not valid """
if depth is not None: try: depth = int(depth) except ValueError: raise ValueError(f"Depth '{depth}' can't be converted to int.") if depth < 1: raise ValueError(f"Depth '{depth}' isn't a positive number") return depth 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 validate(self, data): """ Runs all field validators. """
for v in self.validators: v(self, data) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_styles(style_name): """ Just list all different styles entries """
style = get_style_by_name(style_name) keys = list(style)[0][1] Styles = namedtuple("Style", keys) existing_styles = {} for ttype, ndef in style: s = Styles(**ndef) if s in existing_styles: existing_styles[s].append(ttype) else: existing_styles[s] = [ttype] for ndef, ttypes in existing_styles.items(): print(ndef) for ttype in sorted(ttypes): print("\t%s" % str(ttype).split("Token.",1)[1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorate(*reversed_views): """ provide a syntax decorating views without nested calls. instead of: json_api_call(etag(<hash_fn>)(<view_fn>))) you can write: decorate(json_api_call, etag(<hash_fn>), <view_fn>) """
fns = reversed_views[::-1] view = fns[0] for wrapper in fns[1:]: view = wrapper(view) return view
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_as_object(self, *args): """ Sets a new value to map element specified by its index. When the index is not defined, it resets the entire map value. This method has double purpose because method overrides are not supported in JavaScript. :param args: objects to set """
if len(args) == 1: self.set_as_map(args[0]) elif len(args) == 2: self.put(args[0], args[1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_string(line): """ Parses semicolon-separated key-value pairs and returns them as a StringValueMap. :param line: semicolon-separated key-value list to initialize StringValueMap. :return: a newly created StringValueMap. """
result = StringValueMap() if line == None or len(line) == 0: return result tokens = str(line).split(';') for token in tokens: if len(token) == 0: continue index = token.find('=') key = token[0:index] if index >= 0 else token value = token[index + 1:] if index >= 0 else None result.put(key, value) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, hard=False): """ Override the vanilla delete functionality to soft-delete instead. Soft-delete is accomplished by setting the status field to "deleted" Arguments: hard <bool=False> if true, do a hard delete instead, effectively removing the object from the database """
if hard: return models.Model.delete(self) self.status = "deleted" self.save() for key in self._handleref.delete_cascade: q = getattr(self, key).all() if not hard: # if we are soft deleting only trigger delete on # objects that are not already deleted, as to avoid # unnecessary re-saves and overriding of updated dates q = q.exclude(status="deleted") for child in q: child.delete(hard=hard)
<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_trainer_from_username(self, username, detail=False): """Returns a Trainer object from a Trainers username"""
params = { 'detail': '1' if detail is True else '0', 'q': username } r = requests.get(api_url+'trainers/', params=params, headers=self.headers) print(request_status(r)) try: r = r.json()[0] except IndexError: return None return Trainer(r) if r else 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 discord_to_users(self, memberlist): """ expects a list of discord.py user objects returns a list of TrainerDex.py user objects """
_memberlist = self.get_discord_user(x.id for x in memberlist) return list(set(x.owner() for x in _memberlist))
<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_trainer(self, username, team, start_date=None, has_cheated=None, last_cheated=None, currently_cheats=None, statistics=True, daily_goal=None, total_goal=None, prefered=True, account=None, verified=False): """Add a trainer to the database"""
args = locals() url = api_url+'trainers/' payload = { 'username': username, 'faction': team, 'statistics': statistics, 'prefered': prefered, 'last_modified': maya.now().iso8601(), 'owner': account, 'verified': verified } for i in args: if args[i] is not None and i not in ['self', 'username', 'team', 'account', 'start_date']: payload[i] = args[i] elif args[i] is not None and i=='start_date': payload[i] = args[i].date().isoformat() r = requests.post(url, data=json.dumps(payload), headers=self.headers) print(request_status(r)) r.raise_for_status() return Trainer(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_trainer(self, trainer, username=None, start_date=None, has_cheated=None, last_cheated=None, currently_cheats=None, statistics=None, daily_goal=None, total_goal=None, prefered=None): """Update parts of a trainer in a database"""
args = locals() if not isinstance(trainer, Trainer): raise ValueError url = api_url+'trainers/'+str(trainer.id)+'/' payload = { 'last_modified': maya.now().iso8601() } for i in args: if args[i] is not None and i not in ['self', 'trainer', 'start_date']: payload[i] = args[i] elif args[i] is not None and i=='start_date': payload[i] = args[i].date().isoformat() r = requests.patch(url, data=json.dumps(payload), headers=self.headers) print(request_status(r)) r.raise_for_status() return Trainer(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_discord_user(self, uid, user): """Add a discord user to the database if not already present, get if is present. """
url = api_url+'users/social/' payload = { 'user': int(user), 'provider': 'discord', 'uid': str(uid) } print(json.dumps(payload)) r = requests.put(url, data=json.dumps(payload), headers=self.headers) print(request_status(r)) r.raise_for_status() return DiscordUser(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_user(self, username, first_name=None, last_name=None): """ Creates a new user object on database Returns the User Object. Must be linked to a new trainer soon after """
url = api_url+'users/' payload = { 'username':username } if first_name: payload['first_name'] = first_name if last_name: payload['last_name'] = last_name r = requests.post(url, data=json.dumps(payload), headers=self.headers) print(request_status(r)) r.raise_for_status() return User(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_user(self, user, username=None, first_name=None, last_name=None): """Update user info"""
if not isinstance(user, User): raise ValueError args = locals() url = api_url+'users/'+str(user.id)+'/' payload = {} for i in args: if args[i] is not None and i not in ['self', 'user']: payload[i] = args[i] r = requests.patch(url, data=json.dumps(payload), headers=self.headers) print(request_status(r)) r.raise_for_status() return User(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_trainer(self, id_, respect_privacy=True, detail=True): """Returns the Trainer object for the ID"""
parameters = {} if respect_privacy is False: parameters['statistics'] = 'force' if detail is False: parameters['detail'] = 'low' r = requests.get(api_url+'trainers/'+str(id_)+'/', headers=self.headers) if respect_privacy is True else requests.get(api_url+'trainers/'+str(id_)+'/', params=parameters, headers=self.headers) print(request_status(r)) r.raise_for_status() return Trainer(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_detailed_update(self, uid, uuid): """Returns the update object for the ID"""
r = requests.get(api_url+'users/'+str(uid)+'/update/'+str(uuid)+'/', headers=self.headers) print(request_status(r)) r.raise_for_status() return Update(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user(self, uid): """Returns the User object for the ID"""
r = requests.get(api_url+'users/'+str(uid)+'/', headers=self.headers) print(request_status(r)) r.raise_for_status() return User(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_discord_user(self, uid=None, user=None, trainer=None): """Returns the DiscordUsers object for the ID Expects list of string representions discord IDs, trainer IDs or user IDs Returns DiscordUser objects """
uids = ','.join(uid) if uid else None users =','.join(user) if user else None trainers = ','.join(trainer) if trainer else None params = { 'provider': 'discord', 'uid': uids, 'user': users, 'trainer': trainers } r = requests.get(api_url+'users/social/', params=params, headers=self.headers) print(request_status(r)) r.raise_for_status() output = r.json() result = [] for x in output: result.append(DiscordUser(x)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_users(self): """Returns all the users"""
r = requests.get(api_url+'users/', headers=self.headers) print(request_status(r)) r.raise_for_status() output = r.json() result = [] for x in output: result.append(User(x)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine(self, path): """ Gives a combined `self.BASE_URL` with the given `path`. Used to build urls without modifying the current `self.path`. Handles conflicts of trailing or preceding slashes. :param str path: `path` to append :return: combined `self.base_url` and given `path`. :rtype: str """
url = self.base_url if url.endswith('/') and path.startswith('/'): url += path[1:] elif url.endswith('/') or path.startswith('/'): url += path else: url += '/' + path 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 update_DOM(self): """ Makes a request and updates `self._DOM`. Worth using only if you manually change `self.base_url` or `self.path`. :return: self :rtype: Url """
response = self.fetch() self._DOM = html.fromstring(response.text) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch(self): """ Makes a request to combined url with `self._params` as parameters. If the server at combined url responds with Client or Server error, raises an exception. :return: the response from combined url :rtype: requests.models.Response """
response = self._session.get(self.url, params=self.params) response.raise_for_status() return response
<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_environment(): """Set environment variables that are important for the pipeline. :returns: None :rtype: None :raises: None """
os.environ['DJANGO_SETTINGS_MODULE'] = 'jukeboxcore.djsettings' pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN_PATH', ''), constants.BUILTIN_PLUGIN_PATH)) os.environ['JUKEBOX_PLUGIN_PATH'] = pluginpath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unload_modules(): """ Unload all modules of the jukebox package and all plugin modules Python provides the ``reload`` command for reloading modules. The major drawback is, that if this module is loaded in any other module the source code will not be resourced! If you want to reload the code because you changed the source file, you have to get rid of it completely first. :returns: None :rtype: None :raises: None """
mods = set([]) for m in sys.modules: if m.startswith('jukebox'): mods.add(m) pm = PluginManager.get() for p in pm.get_all_plugins(): mods.add(p.__module__) for m in mods: del(sys.modules[m])
<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_LDAP_connection(): """ Return a LDAP connection """
server = ldap3.Server('ldap://' + get_optional_env('EPFL_LDAP_SERVER_FOR_SEARCH')) connection = ldap3.Connection(server) connection.open() return connection, get_optional_env('EPFL_LDAP_BASE_DN_FOR_SEARCH')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def LDAP_search(pattern_search, attribute): """ Do a LDAP search """
connection, ldap_base = _get_LDAP_connection() connection.search( search_base=ldap_base, search_filter=pattern_search, attributes=[attribute] ) return connection.response
<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_unit_exist(unit_id): """ Return True if the unit 'unid_id' exists. Otherwise return False """
attribute = 'objectClass' response = LDAP_search( pattern_search="(uniqueidentifier={})".format(unit_id), attribute=attribute ) try: unit_exist = 'EPFLorganizationalUnit' in response[0]['attributes'][attribute] except Exception: return False return unit_exist
<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_unit_name(unit_id): """ Return the unit name to the unit 'unit_id' """
attribute = 'cn' response = LDAP_search( pattern_search='(uniqueIdentifier={})'.format(unit_id), attribute=attribute ) try: unit_name = get_attribute(response, attribute) except Exception: raise EpflLdapException("The unit with id '{}' was not found".format(unit_id)) return unit_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_unit_id(unit_name): """ Return the unit id to the unit 'unit_name' """
unit_name = unit_name.lower() attribute = 'uniqueIdentifier' response = LDAP_search( pattern_search='(cn={})'.format(unit_name), attribute=attribute ) unit_id = "" try: for element in response: if 'dn' in element and element['dn'].startswith('ou={},'.format(unit_name)): unit_id = element['attributes'][attribute][0] except Exception: raise EpflLdapException("The unit named '{}' was not found".format(unit_name)) finally: if not unit_id: raise EpflLdapException("The unit named '{}' was not found".format(unit_name)) return unit_id
<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_units(username): """ Return all units of user 'username' """
connection, ldap_base = _get_LDAP_connection() # Search the user dn connection.search( search_base=ldap_base, search_filter='(uid={}@*)'.format(username), ) # For each user dn give me the unit dn_list = [connection.response[index]['dn'] for index in range(len(connection.response))] units = [] # For each unit search unit information and give me the unit id for dn in dn_list: unit = dn.split(",ou=")[1] connection.search(search_base=ldap_base, search_filter='(ou={})'.format(unit), attributes=['uniqueidentifier']) units.append(get_attribute(connection.response, 'uniqueIdentifier')) return units
<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_username(sciper): """ Return username of user """
attribute = 'uid' response = LDAP_search( pattern_search='(uniqueIdentifier={})'.format(sciper), attribute=attribute ) try: username = get_attribute(response, attribute) except Exception: raise EpflLdapException("No username corresponds to sciper {}".format(sciper)) return username
<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_email(sciper): """ Return email of user """
attribute = 'mail' response = LDAP_search( pattern_search='(uniqueIdentifier={})'.format(sciper), attribute=attribute ) try: email = get_attribute(response, attribute) except Exception: raise EpflLdapException("No email address corresponds to sciper {}".format(sciper)) return 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 with_code(self, code): """ Sets a unique error code. This method returns reference to this exception to implement Builder pattern to chain additional calls. :param code: a unique error code :return: this exception object """
self.code = code if code != None else 'UNKNOWN' self.name = code return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_details(self, key, value): """ Sets a parameter for additional error details. This details can be used to restore error description in other languages. This method returns reference to this exception to implement Builder pattern to chain additional calls. :param key: a details parameter name :param value: a details parameter name :return: this exception object """
self.details = self.details if self.details != None else {} self.details[key] = value return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap(self, cause): """ Wraps another exception into an application exception object. If original exception is of ApplicationException type it is returned without changes. Otherwise a new ApplicationException is created and original error is set as its cause. :param cause: an original error object :return: an original or newly created ApplicationException """
if isinstance(cause, ApplicationException): return cause self.with_cause(cause) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_exception(exception, cause): """ Wraps another exception into specified application exception object. If original exception is of ApplicationException type it is returned without changes. Otherwise the original error is set as a cause to specified ApplicationException object. :param exception: an ApplicationException object to wrap the cause :param cause: an original error object :return: an original or newly created ApplicationException """
if isinstance(cause, ApplicationException): return cause exception.with_cause(cause) return 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 value(self): """ Return the current value of a variable """
# Does the variable name have tags to parse? if len(self._element): var = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, self.trigger))) else: var = self._element.text or attribute(self._element, 'name') # Is there a default value defined? default = attribute(self._element, 'default') try: self._log.debug('Retrieving {type} variable {var}'.format(type=self.type, var=var)) if self.type == 'user': return self.trigger.user.get_var(var) else: return self.trigger.agentml.get_var(var) except VarNotDefinedError: # Do we have a default value? if default: self._log.info('{type} variable {var} not set, returning default: {default}' .format(type=self.type.capitalize(), var=var, default=default)) self._log.info('{type} variable {var} not set and no default value has been specified' .format(type=self.type.capitalize(), var=var)) return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reopen(self, file_obj): """Reopen the file-like object in a safe manner."""
file_obj.open('U') if sys.version_info[0] <= 2: return file_obj else: return codecs.getreader('utf-8')(file_obj)
<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(self): """wrapper for original parse function. will read pkl with bdf info, if available."""
if os.path.exists(self.pklname): # check for pkl with binary info logger.info('Found bdf pkl file %s. Loading...' % (self.pklname)) try: with open(self.pklname,'rb') as pkl: (self.mimemsg, self.headxml, self.sizeinfo, self.binarychunks, self.n_integrations, self.n_antennas, self.n_baselines, self.n_basebands, self.n_spws, self.n_channels, self.crosspols) = pickle.load(pkl) except: logger.warning('Something went wrong. Parsing bdf directly...') self._parse() else: if self.pklname: logger.info('Could not find bdf pkl file %s.' % (self.pklname)) self._parse() self.headsize, self.intsize = self.calc_intsize() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toString(self): """ Returns almost original string. If you want prettified string, try :meth:`.prettify`. Returns: str: Complete representation of the element with childs, endtag \ and so on. """
output = "" if self.childs or self.isOpeningTag(): output += self.tagToString() for c in self.childs: output += c.toString() if self.endtag is not None: output += self.endtag.tagToString() elif not self.isEndTag(): output += self.tagToString() return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replaceWith(self, el): """ Replace value in this element with values from `el`. This useful when you don't want change all references to object. Args: el (obj): :class:`HTMLElement` instance. """
self.childs = el.childs self.params = el.params self.endtag = el.endtag self.openertag = el.openertag self._tagname = el.getTagName() self._element = el.tagToString() self._istag = el.isTag() self._isendtag = el.isEndTag() self._iscomment = el.isComment() self._isnonpairtag = el.isNonPairTag()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_previous(self, command): """ Method to generate item from a ItemForm. The form must be exposed on form attribute @param command: a command tha expose data through form attributte """
self.result = command.items self._to_commit = self.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 get_dates(raw_table) -> "list of dates": """ Goes through the first column of input table and returns the first sequence of dates it finds. """
dates = [] found_first = False for i, dstr in enumerate([raw_table[i][0] for i in range(0, len(raw_table))]): if dstr: if len(dstr.split("/")) == 3: d = datetime.datetime.strptime(dstr, '%m/%d/%Y') elif len(dstr.split("-")) == 3: d = datetime.datetime.strptime(dstr, '%Y-%m-%d') else: # Not necessarily an error, could just be a non-date cell logging.debug("unknown date-format: {}".format(dstr)) continue dates.append(d) if not found_first: found_first = True logging.debug("Found first date: '{}' at i: {}".format(d.isoformat(), i)) elif found_first: logging.debug("Last date: {}".format(d)) break return dates
<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_main(self) -> 'table[category: str][label: str][date: date]': """ Returns a table with the above typesignature """
raw_table = self.get_raw_table("M") categories = raw_table[0] labels = raw_table[1] dates = self.get_dates(raw_table) def next_cat_col(i): n = 1 while True: if i+n > len(categories)-1: return i if categories[i+n]: return i+n n += 1 def get_category_labels(i): end_col = next_cat_col(i) return zip(range(i, end_col), labels[i:end_col]) def get_label_cells(category, label): ci = categories.index(category) i = labels.index(label, ci) cells = {} for j, d in enumerate(dates): cell = raw_table[j+2][i] if cell and cell != "#VALUE!": cells[d] = cell return cells table = {} for i, cat in enumerate(categories): if not cat: continue table[cat] = {} for i, label in get_category_labels(i): table[cat][label] = get_label_cells(cat, label) return table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def build_headers(self): ''' Return the list of headers as two-tuples ''' if not 'Content-Type' in self.headers: content_type = self.content_type if self.encoding != DEFAULT_ENCODING: content_type += '; charset=%s' % self.encoding self.headers['Content-Type'] = content_type headers = list(self.headers.items()) # Append cookies headers += [ ('Set-Cookie', cookie.OutputString()) for cookie in self.cookies.values() ] return headers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_cookie(self, key, value, **attrs): ''' Finer control over cookies. Allow specifying an Morsel arguments. ''' if attrs: c = Morsel() c.set(key, value, **attrs) self.cookies[key] = c else: self.cookies[key] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def status(self): '''Allow custom status messages''' message = self.status_message if message is None: message = STATUS[self.status_code] return '%s %s' % (self.status_code, message)
<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_git_changeset(): """Get git identifier; taken from Django project."""
git_log = Popen( 'git log --pretty=format:%ct --quiet -1 HEAD', stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True) timestamp = git_log.communicate()[0] try: timestamp = datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%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_version(version_tuple): """Convert 4-tuple into a PEP 440 compliant string."""
if version_tuple[3] == FINAL and version_tuple[4] != 0: raise Exception( 'Project version number misconfigured:\n' ' version may not be final and have segment number.') if version_tuple[3] not in (DEV, FINAL) and version_tuple[4] == 0: raise Exception( 'Project version number misconfigured:\n' ' version must have segment number.') if version_tuple[3] == DEV: segment_num = get_git_changeset() else: segment_num = str(abs(version_tuple[4])) # X.X.X sem_ver = ".".join([ str(abs(int(number))) for number in version_tuple[:3] ]) if version_tuple[3] != FINAL: if version_tuple[3] in (ALPHA, BETA, RC): sem_ver = "%s%s%s" % (sem_ver, version_tuple[3], segment_num) elif version_tuple[3] in (DEV, POST): sem_ver = "%s%s%s%s" % ( sem_ver, SEPARATOR, version_tuple[3], segment_num) else: raise Exception( 'Project version number misconfigured:\n' ' Unrecognized release type') return sem_ver
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, name): """If name is not in the map, append it with an empty id range set."""
if not isinstance(name, str): raise TypeError( "argument 'name' must be a string, not {}".format( name.__class__.__name__ ) ) if not name: raise ValueError("argument 'name' cannot be empty") if not name in self.__map: self.__map[name] = IdRangeSet()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def who_has(self, subid): """Return a list of names who own subid in their id range set."""
answer = [] for name in self.__map: if subid in self.__map[name] and not name in answer: answer.append(name) return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_path_for_url(url): """Return the path where the URL might be cached."""
m = hashlib.md5() m.update(url) digest = m.hexdigest() return os.path.join(CACHE_DIRECTORY, '%s.html' % digest)
<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_url(url, data=None, cached=True, cache_key=None, crawler='urllib'): """Retrieves the HTML code for a given URL. If a cached version is not available, uses phantom_retrieve to fetch the page. data - Additional data that gets passed onto the crawler. cached - If True, retrieves the URL from the cache if it is available. If False, will still store the page in cache. cache_key - If set, will be used instead of the URL to lookup the cached version of the page. crawler - A string referencing one of the builtin crawlers. Returns the HTML as a unicode string. Raises a HttpNotFound exception if the page could not be found. """
if cache_key is None: cache_key = url cache_path = cache_path_for_url(cache_key) if cached and os.path.exists(cache_path): with open(cache_path) as f: html = f.read().decode('utf-8') else: if FAIL_IF_NOT_CACHED: raise BaseException("URL is not in cache and FAIL_IF_NOT_CACHED is True: %s" % url) crawler_fn = CRAWLERS[crawler] status, html = crawler_fn(url, data) if status != 200: raise HttpNotFound(url) _ensure_directory(CACHE_DIRECTORY) with open(cache_path, 'w') as f: f.write(html.encode('utf-8')) return html
<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_intercom_data(self): """Specify the data sent to Intercom API according to event type"""
data = { "event_name": self.get_type_display(), # event type "created_at": calendar.timegm(self.created.utctimetuple()), # date "metadata": self.metadata } if self.user: data["user_id"] = self.user.intercom_id return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_lab_text(lab_slug, language): """Gets text description in English or Italian from a single lab from makeinitaly.foundation."""
if language == "English" or language == "english" or language == "EN" or language == "En": language = "en" elif language == "Italian" or language == "italian" or language == "IT" or language == "It" or language == "it": language = "it" else: language = "en" wiki = MediaWiki(makeinitaly__foundation_api_url) wiki_response = wiki.call( {'action': 'query', 'titles': lab_slug + "/" + language, 'prop': 'revisions', 'rvprop': 'content'}) # If we don't know the pageid... for i in wiki_response["query"]["pages"]: if "revisions" in wiki_response["query"]["pages"][i]: content = wiki_response["query"]["pages"][i]["revisions"][0]["*"] else: content = "" # Clean the resulting string/list newstr01 = content.replace("}}", "") newstr02 = newstr01.replace("{{", "") result = newstr02.rstrip("\n|").split("\n|") return result[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 get_single_lab(lab_slug): """Gets data from a single lab from makeinitaly.foundation."""
wiki = MediaWiki(makeinitaly__foundation_api_url) wiki_response = wiki.call( {'action': 'query', 'titles': lab_slug, 'prop': 'revisions', 'rvprop': 'content'}) # If we don't know the pageid... for i in wiki_response["query"]["pages"]: content = wiki_response["query"]["pages"][i]["revisions"][0]["*"] # Clean the resulting string/list newstr01 = content.replace("}}", "") newstr02 = newstr01.replace("{{", "") result = newstr02.rstrip("\n|").split("\n|") # result.remove(u'FabLab') # Transform the data into a Lab object current_lab = MILab() # Add existing data for i in result: if "coordinates=" in i: value = i.replace("coordinates=", "") current_lab.coordinates = value latlong = [] if ", " in value: latlong = value.rstrip(", ").split(", ") elif " , " in value: latlong = value.rstrip(" , ").split(" , ") else: latlong = ["", ""] current_lab.latitude = latlong[0] current_lab.longitude = latlong[1] elif "province=" in i: value = i.replace("province=", "") current_lab.province = value.upper() elif "region=" in i: value = i.replace("region=", "") current_lab.region = value elif "address=" in i: value = i.replace("address=", "") current_lab.address = value elif "city=" in i: value = i.replace("city=", "") current_lab.city = value elif "fablabsio=" in i: value = i.replace("fablabsio=", "") current_lab.fablabsio = value elif "website=" in i: value = i.replace("website=", "") current_lab.website = value elif "facebook=" in i: value = i.replace("facebook=", "") current_lab.facebook = value elif "twitter=" in i: value = i.replace("twitter=", "") current_lab.twitter = value elif "email=" in i: value = i.replace("email=", "") current_lab.email = value elif "manager=" in i: value = i.replace("manager=", "") current_lab.manager = value elif "birthyear=" in i: value = i.replace("birthyear=", "") current_lab.birthyear = value current_lab.text_en = get_lab_text(lab_slug=lab_slug, language="en") current_lab.text_it = get_lab_text(lab_slug=lab_slug, language="it") return current_lab
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_labs(format): """Gets data from all labs from makeinitaly.foundation."""
labs = [] # Get the first page of data wiki = MediaWiki(makeinitaly__foundation_api_url) wiki_response = wiki.call( {'action': 'query', 'list': 'categorymembers', 'cmtitle': 'Category:Italian_FabLabs', 'cmlimit': '500'}) if "query-continue" in wiki_response: nextpage = wiki_response[ "query-continue"]["categorymembers"]["cmcontinue"] urls = [] for i in wiki_response["query"]["categorymembers"]: urls.append(i["title"].replace(" ", "_")) # Load all the Labs in the first page for i in urls: current_lab = get_single_lab(i) labs.append(current_lab) # Load all the Labs from the other pages while "query-continue" in wiki_response: wiki = MediaWiki(makeinitaly__foundation_api_url) wiki_response = wiki.call({'action': 'query', 'list': 'categorymembers', 'cmtitle': 'Category:Hackerspace', 'cmlimit': '500', "cmcontinue": nextpage}) urls = [] for i in wiki_response["query"]["categorymembers"]: urls.append(i["title"].replace(" ", "_")) # Load all the Labs for i in urls: current_lab = get_single_lab(i, data_format) labs.append(current_lab) if "query-continue" in wiki_response: nextpage = wiki_response[ "query-continue"]["categorymembers"]["cmcontinue"] else: break # Transform the list into a dictionary labs_dict = {} for j, k in enumerate(labs): labs_dict[j] = k.__dict__ # Return a dictiornary / json if format.lower() == "dict" or format.lower() == "json": output = labs_dict # Return a geojson elif format.lower() == "geojson" or format.lower() == "geo": labs_list = [] for l in labs_dict: single = labs_dict[l].__dict__ single_lab = Feature( type="Feature", geometry=Point((single["latitude"], single["longitude"])), properties=single) labs_list.append(single_lab) output = dumps(FeatureCollection(labs_list)) # Return a Pandas DataFrame elif format.lower() == "pandas" or format.lower() == "dataframe": output = {} for j in labs_dict: output[j] = labs_dict[j].__dict__ # Transform the dict into a Pandas DataFrame output = pd.DataFrame.from_dict(output) output = output.transpose() # Return an object elif format.lower() == "object" or format.lower() == "obj": output = labs # Default: return an object else: output = labs # Return a proper json if format.lower() == "json": output = json.dumps(labs_dict) return output
<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_eval(self, obj, keypath): '''Given an object and a mongo-style dotted key path, return the object value referenced by that key path. ''' segs = keypath.split('.') this = obj for seg in segs: if isinstance(this, dict): try: this = this[seg] except KeyError: raise self.InvalidPath() elif isinstance(this, (list, tuple)): if seg.isdigit(): this = this[int(seg)] else: try: this = getattr(this, seg) except AttributeError: raise self.InvalidPath() return this
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check(self, spec, data): '''Given a mongo-style spec and some data or python object, check whether the object complies with the spec. Fails eagerly. ''' path_eval = self.path_eval for keypath, specvalue in spec.items(): if keypath.startswith('$'): optext = keypath checkable = data args = (optext, specvalue, checkable) generator = self.dispatch_operator(*args) else: try: checkable = path_eval(data, keypath) except self.InvalidPath: # The spec referenced an item or attribute that # doesn't exist. Fail! return False generator = self.dispatch_literal(specvalue, checkable) for result in generator: if not result: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def handle_literal(self, val, checkable): '''This one's tricky...check for equality, then for contains. ''' # I.e., spec: {'x': 1}, data: {'x': 1} if val == checkable: yield True return # I.e., spec: {'x': 1}, data: {'x': [1, 2, 3]} else: try: yield val in checkable return except TypeError: pass yield 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 normalize(X, norm): '''Applies the given norm to the input data set Parameters: X (numpy.ndarray): A 3D numpy ndarray in which the rows represent examples while the columns, features of the data set you want to normalize. Every depth corresponds to data for a particular class norm (tuple): A tuple containing two 1D numpy ndarrays corresponding to the normalization parameters extracted with :py:func:`estimated_norm` above. Returns: numpy.ndarray: A 3D numpy ndarray with the same dimensions as the input array ``X``, but with its values normalized according to the norm input. ''' return numpy.array([(k - norm[0]) / norm[1] for k in X])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auto_register_search_models(): """Auto register all search models"""
for config in models_config.get_all_configs(): if config.disable_search_index: continue search.register( config.model.objects.get_queryset(), ModelSearchAdapter, fields=config.search_fields, exclude=config.search_exclude_fields, )
<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_title(self, obj): """Set search entry title for object"""
search_title = self.get_model_config_value(obj, 'search_title') if not search_title: return super().get_title(obj) return search_title.format(**obj.__dict__)
<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_description(self, obj): """Set search entry description for object"""
search_description = self.get_model_config_value(obj, 'search_description') if not search_description: return super().get_description(obj) return search_description.format(**obj.__dict__)
<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_model_config_value(self, obj, name): """Get config value for given model"""
config = models_config.get_config(obj) return getattr(config, 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 disconnect(self, callback): """ Disconnects a callback from this signal. :param callback: The callback to disconnect. :param weak: A flag that must have the same value than the one specified during the call to `connect`. .. warning:: If the callback is not connected at the time of call, a :class:`ValueError` exception is thrown. .. note:: You may call `disconnect` from a connected callback. """
try: self._callbacks.remove(callback) except ValueError: self._callbacks.remove(ref(callback))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_channel_names(client, e): """Add a new channel to self.channels and initialize its user list. Called as event handler for RPL_NAMES events. Do not call directly. """
chan = IRCstr(e.channel) names = set([IRCstr(n) for n in e.name_list]) client.channels[chan] = SeshetChannel(chan, names)
<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(self, channel): """Add this user to the channel's user list and add the channel to this user's list of joined channels. """
if channel not in self.channels: channel.users.add(self.nick) self.channels.append(channel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def part(self, channel): """Remove this user from the channel's user list and remove the channel from this user's list of joined channels. """
if channel in self.channels: channel.users.remove(self.nick) self.channels.remove(channel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quit(self): """Remove this user from all channels and reinitialize the user's list of joined channels. """
for c in self.channels: c.users.remove(self.nick) self.channels = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_nick(self, nick): """Update this user's nick in all joined channels."""
old_nick = self.nick self.nick = IRCstr(nick) for c in self.channels: c.users.remove(old_nick) c.users.add(self.nick)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_message(self, user, message): """Log a channel message. This log acts as a sort of cache so that recent activity can be searched by the bot and command modules without querying the database. """
if isinstance(user, SeshetUser): user = user.nick elif not isinstance(user, IRCstr): user = IRCstr(user) time = datetime.utcnow() self.message_log.append((time, user, message)) while len(self.message_log) > self._log_size: del self.message_log[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 register_dependency(self, data_src, data_sink): """ registers a dependency of data_src -> data_sink by placing appropriate entries in provides_for and depends_on """
pdebug("registering dependency %s -> %s" % (data_src, data_sink)) if (data_src not in self._gettask(data_sink).depends_on): self._gettask(data_sink).depends_on.append(data_src) if (data_sink not in self._gettask(data_src).provides_for): self._gettask(data_src).provides_for.append(data_sink)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_task(self, name): """ Builds a task by name, resolving any dependencies on the way """
try: self._gettask(name).value = ( self._gettask(name).task.resolve_and_build()) except TaskExecutionException as e: perror(e.header, indent="+0") perror(e.message, indent="+4") self._gettask(name).value = e.payload except Exception as e: perror("error evaluating target '%s' %s" % (name, type(self._gettask(name).task))) perror(traceback.format_exc(e), indent='+4') self._gettask(name).value = None self._gettask(name).last_build_time = time.time()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_build_needed(self, data_sink, data_src): """ returns true if data_src needs to be rebuilt, given that data_sink has had a rebuild requested. """
return (self._gettask(data_src).last_build_time == 0 or self._gettask(data_src).last_build_time < self._gettask(data_sink).last_build_time)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deep_dependendants(self, target): """ Recursively finds the dependents of a given build target. Assumes the dependency graph is noncyclic """
direct_dependents = self._gettask(target).provides_for return (direct_dependents + reduce( lambda a, b: a + b, [self.deep_dependendants(x) for x in direct_dependents], []))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_dependency_graph(self, target): """ resolves the build order for interdependent build targets Assumes no cyclic dependencies """
targets = self.deep_dependendants(target) # print "deep dependants:", targets return sorted(targets, cmp=lambda a, b: 1 if b in self.deep_dependendants(a) else -1 if a in self.deep_dependendants(b) else 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve(self): """Builds all targets of this dependency and returns the result of self.function on the resulting values """
values = {} for target_name in self.target_names: if self.context.is_build_needed(self.parent, target_name): self.context.build_task(target_name) if len(self.keyword_chain) == 0: values[target_name] = self.context.tasks[target_name].value else: values[target_name] = reduce( lambda task, name: getattr(task, name), self.keyword_chain, self.context.tasks[target_name].task) return self.function(**values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateAllKeys(self): """Update times for all keys in the layout."""
for kf, key in zip(self.kf_list, self.sorted_key_list()): kf.update(key, self.dct[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 print_with_header(header, message, color, indent=0): """ Use one of the functions below for printing, not this one. """
print() padding = ' ' * indent print(padding + color + BOLD + header + ENDC + color + message + ENDC)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Perform phantomas run """
self._logger.info("running for <{url}>".format(url=self._url)) args = format_args(self._options) self._logger.debug("command: `{cmd}` / args: {args}". format(cmd=self._cmd, args=args)) # run the process try: process = Popen( args=[self._cmd] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE ) pid = process.pid self._logger.debug("running as PID #{pid}".format(pid=pid)) except OSError as ex: raise PhantomasRunError( "Failed to run phantomas: {0}".format(ex), ex.errno) # wait to complete try: stdout, stderr = process.communicate() returncode = process.returncode except Exception: raise PhantomasRunError("Failed to complete the run") # for Python 3.x - decode bytes to string stdout = stdout.decode('utf8') stderr = stderr.decode('utf8') # check the response code self._logger.debug("completed with return code #{returncode}". format(returncode=returncode)) if stderr != '': self._logger.debug("stderr: {stderr}".format(stderr=stderr)) raise PhantomasFailedError(stderr.strip(), returncode) # try parsing the response try: results = json.loads(stdout) except Exception: raise PhantomasResponseParsingError("Unable to parse the response") if self._options.get("runs", 0) > 1: return Runs(self._url, results) else: return Results(self._url, 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 extract(fileobj, keywords, comment_tags, options): """Extracts translation messages from underscore template files. This method does also extract django templates. If a template does not contain any django translation tags we always fallback to underscore extraction. This is a plugin to Babel, written according to http://babel.pocoo.org/docs/messages/#writing-extraction-methods :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples :rtype: ``iterator`` """
encoding = options.get('encoding', 'utf-8') original_position = fileobj.tell() text = fileobj.read().decode(encoding) if django.VERSION[:2] >= (1, 9): tokens = Lexer(text).tokenize() else: tokens = Lexer(text, None).tokenize() vars = [token.token_type != TOKEN_TEXT for token in tokens] could_be_django = any(list(vars)) if could_be_django: fileobj.seek(original_position) iterator = extract_django(fileobj, keywords, comment_tags, options) for lineno, funcname, message, comments in iterator: yield lineno, funcname, message, comments else: # Underscore template extraction comments = [] fileobj.seek(original_position) for lineno, line in enumerate(fileobj, 1): funcname = None stream = TokenStream.from_tuple_iter(tokenize(line, underscore.rules)) while not stream.eof: if stream.current.type == 'gettext_begin': stream.expect('gettext_begin') funcname = stream.expect('func_name').value args, kwargs = parse_arguments(stream, 'gettext_end') strings = [] for arg, argtype in args: if argtype == 'func_string_arg': strings.append(force_text(arg)) else: strings.append(None) for arg in kwargs: strings.append(None) if len(strings) == 1: strings = strings[0] else: strings = tuple(strings) yield lineno, funcname, strings, [] stream.next()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_radians(cls, lat_radians, long_radians): ''' Return a new instance of Point from a pair of coordinates in radians. ''' return cls(math.degrees(lat_radians), math.degrees(long_radians))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def distance_to(self, point): ''' Return the distance between this point and another point in meters. :param point: Point to measure distance to :type point: Point :returns: The distance to the other point :rtype: float ''' angle = math.acos( sin(self.lat_radians) * sin(point.lat_radians) + cos(self.lat_radians) * cos(point.lat_radians) * cos(self.long_radians - point.long_radians) ) return angle * EARTH_RADIUS
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bearing_to(self, point): ''' Return the bearing to another point. :param point: Point to measure bearing to :type point: Point :returns: The bearing to the other point :rtype: Bearing ''' delta_long = point.long_radians - self.long_radians y = sin(delta_long) * cos(point.lat_radians) x = ( cos(self.lat_radians) * sin(point.lat_radians) - sin(self.lat_radians) * cos(point.lat_radians) * cos(delta_long) ) radians = math.atan2(y, x) return Bearing.from_radians(radians)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def relative_point(self, bearing_to_point, distance): ''' Return a waypoint at a location described relative to the current point :param bearing_to_point: Relative bearing from the current waypoint :type bearing_to_point: Bearing :param distance: Distance from the current waypoint :type distance: float :return: The point described by the parameters ''' bearing = math.radians(360 - bearing_to_point) rad_distance = (distance / EARTH_RADIUS) lat1 = (self.lat_radians) lon1 = (self.long_radians) lat3 = math.asin(math.sin(lat1) * math.cos(rad_distance) + math.cos(lat1) * math.sin(rad_distance) * math.cos(bearing)) lon3 = lon1 + math.atan2(math.sin(bearing) * math.sin(rad_distance) * math.cos(lat1) , math.cos(rad_distance) - math.sin(lat1) * math.sin(lat3)) return Point(math.degrees(lat3), math.degrees(lon3))
<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_app(settings): """Create a new Flask application"""
app = Flask(__name__) # Import settings from file for name in dir(settings): value = getattr(settings, name) if not (name.startswith('_') or isinstance(value, ModuleType) or isinstance(value, FunctionType)): app.config[name] = value # Bootstrapping if 'INSTALLED_APPS' in app.config: app.installed_apps = app.config.get('INSTALLED_APPS', []) # Extensions Funnel(app) Mobility(app) # Register blueprints for app_path in app.installed_apps: app.register_blueprint( getattr(__import__('{0}.views'.format(app_path), fromlist=['blueprint']), 'blueprint')) # Register error handlers register_error_handlers(app) @app.context_processor def context_processor(): return dict(config=app.config) @app.teardown_request def teardown_request(exception=None): # Remove the database session if it exists if hasattr(app, 'db_session'): app.db_session.close() return app