_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q255800
_add_active_assets
validation
def _add_active_assets(specs): """ This function adds an assets key to the specs, which is filled in with a dictionary of all assets defined by apps and libs in the specs """ specs['assets'] = {} for spec in specs.get_apps_and_libs(): for asset in spec['assets']: if not specs...
python
{ "resource": "" }
q255801
_get_expanded_active_specs
validation
def _get_expanded_active_specs(specs): """ This function removes any unnecessary bundles, apps, libs, and services that aren't needed by the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed indirectly by each app """ _filter_active(constants.CONFIG_BUND...
python
{ "resource": "" }
q255802
get_repo_of_app_or_library
validation
def get_repo_of_app_or_library(app_or_library_name): """ This function takes an app or library name and will return the corresponding repo for that app or library""" specs = get_specs() repo_name = specs.get_app_or_lib(app_or_library_name)['repo'] if not repo_name: return None return Rep...
python
{ "resource": "" }
q255803
get_same_container_repos_from_spec
validation
def get_same_container_repos_from_spec(app_or_library_spec): """Given the spec of an app or library, returns all repos that are guaranteed to live in the same container""" repos = set() app_or_lib_repo = get_repo_of_app_or_library(app_or_library_spec.name) if app_or_lib_repo is not None: rep...
python
{ "resource": "" }
q255804
get_same_container_repos
validation
def get_same_container_repos(app_or_library_name): """Given the name of an app or library, returns all repos that are guaranteed to live in the same container""" specs = get_expanded_libs_specs() spec = specs.get_app_or_lib(app_or_library_name) return get_same_container_repos_from_spec(spec)
python
{ "resource": "" }
q255805
_dusty_hosts_config
validation
def _dusty_hosts_config(hosts_specs): """Return a string of all host rules required to match the given spec. This string is wrapped in the Dusty hosts header and footer so it can be easily removed later.""" rules = ''.join(['{} {}\n'.format(spec['forwarded_ip'], spec['host_address']) for spec in hosts_...
python
{ "resource": "" }
q255806
update_hosts_file_from_port_spec
validation
def update_hosts_file_from_port_spec(port_spec): """Given a port spec, update the hosts file specified at constants.HOST_PATH to contain the port mappings specified in the spec. Any existing Dusty configurations are replaced.""" logging.info('Updating hosts file to match port spec') hosts_specs = po...
python
{ "resource": "" }
q255807
_move_temp_binary_to_path
validation
def _move_temp_binary_to_path(tmp_binary_path): """Moves the temporary binary to the location of the binary that's currently being run. Preserves owner, group, and permissions of original binary""" # pylint: disable=E1101 binary_path = _get_binary_location() if not binary_path.endswith(constants.DUS...
python
{ "resource": "" }
q255808
parallel_task_queue
validation
def parallel_task_queue(pool_size=multiprocessing.cpu_count()): """Context manager for setting up a TaskQueue. Upon leaving the context manager, all tasks that were enqueued will be executed in parallel subject to `pool_size` concurrency constraints.""" task_queue = TaskQueue(pool_size) yield task_q...
python
{ "resource": "" }
q255809
_nginx_location_spec
validation
def _nginx_location_spec(port_spec, bridge_ip): """This will output the nginx location config string for specific port spec """ location_string_spec = "\t \t location / { \n" for location_setting in ['proxy_http_version 1.1;', 'proxy_set_header Upgrade $http_upgrade;', ...
python
{ "resource": "" }
q255810
_nginx_http_spec
validation
def _nginx_http_spec(port_spec, bridge_ip): """This will output the nginx HTTP config string for specific port spec """ server_string_spec = "\t server {\n" server_string_spec += "\t \t {}\n".format(_nginx_max_file_size_string()) server_string_spec += "\t \t {}\n".format(_nginx_listen_string(port_spec))...
python
{ "resource": "" }
q255811
_nginx_stream_spec
validation
def _nginx_stream_spec(port_spec, bridge_ip): """This will output the nginx stream config string for specific port spec """ server_string_spec = "\t server {\n" server_string_spec += "\t \t {}\n".format(_nginx_listen_string(port_spec)) server_string_spec += "\t \t {}\n".format(_nginx_proxy_string(port_s...
python
{ "resource": "" }
q255812
get_nginx_configuration_spec
validation
def get_nginx_configuration_spec(port_spec_dict, docker_bridge_ip): """This function will take in a port spec as specified by the port_spec compiler and will output an nginx web proxy config string. This string can then be written to a file and used running nginx """ nginx_http_config, nginx_stream_conf...
python
{ "resource": "" }
q255813
_load_ssh_auth_post_yosemite
validation
def _load_ssh_auth_post_yosemite(mac_username): """Starting with Yosemite, launchd was rearchitected and now only one launchd process runs for all users. This allows us to much more easily impersonate a user through launchd and extract the environment variables from their running processes.""" user_...
python
{ "resource": "" }
q255814
_load_ssh_auth_pre_yosemite
validation
def _load_ssh_auth_pre_yosemite(): """For OS X versions before Yosemite, many launchd processes run simultaneously under different users and different permission models. The simpler `asuser` trick we use in Yosemite doesn't work, since it gets routed to the wrong launchd. We instead need to find the run...
python
{ "resource": "" }
q255815
check_and_load_ssh_auth
validation
def check_and_load_ssh_auth(): """ Will check the mac_username config value; if it is present, will load that user's SSH_AUTH_SOCK environment variable to the current environment. This allows git clones to behave the same for the daemon as they do for the user """ mac_username = get_config_val...
python
{ "resource": "" }
q255816
_cleanup_path
validation
def _cleanup_path(path): """Recursively delete a path upon exiting this context manager. Supports targets that are files or directories.""" try: yield finally: if os.path.exists(path): if os.path.isdir(path): shutil.rmtree(path) else: ...
python
{ "resource": "" }
q255817
copy_between_containers
validation
def copy_between_containers(source_name, source_path, dest_name, dest_path): """Copy a file from the source container to an intermediate staging area on the local filesystem, then from that staging area to the destination container. These moves take place without demotion for two reasons: 1. Ther...
python
{ "resource": "" }
q255818
copy_from_local
validation
def copy_from_local(local_path, remote_name, remote_path, demote=True): """Copy a path from the local filesystem to a path inside a Dusty container. The files on the local filesystem must be accessible by the user specified in mac_username.""" if not os.path.exists(local_path): raise RuntimeErro...
python
{ "resource": "" }
q255819
copy_to_local
validation
def copy_to_local(local_path, remote_name, remote_path, demote=True): """Copy a path from inside a Dusty container to a path on the local filesystem. The path on the local filesystem must be wrist-accessible by the user specified in mac_username.""" if not container_path_exists(remote_name, remote_path)...
python
{ "resource": "" }
q255820
_mount_repo
validation
def _mount_repo(repo, wait_for_server=False): """ This function will create the VM directory where a repo will be mounted, if it doesn't exist. If wait_for_server is set, it will wait up to 10 seconds for the nfs server to start, by retrying mounts that fail with 'Connection Refused'. If wait_for_...
python
{ "resource": "" }
q255821
get_port_spec_document
validation
def get_port_spec_document(expanded_active_specs, docker_vm_ip): """ Given a dictionary containing the expanded dusty DAG specs this function will return a dictionary containing the port mappings needed by downstream methods. Currently this includes docker_compose, virtualbox, nginx and hosts_file.""" ...
python
{ "resource": "" }
q255822
init_yaml_constructor
validation
def init_yaml_constructor(): """ This dark magic is used to make yaml.safe_load encode all strings as utf-8, where otherwise python unicode strings would be returned for non-ascii chars """ def utf_encoding_string_constructor(loader, node): return loader.construct_scalar(node).encode('utf-8'...
python
{ "resource": "" }
q255823
registry_from_image
validation
def registry_from_image(image_name): """Returns the Docker registry host associated with a given image name.""" if '/' not in image_name: # official image return constants.PUBLIC_DOCKER_REGISTRY prefix = image_name.split('/')[0] if '.' not in prefix: # user image on official repository, e.g....
python
{ "resource": "" }
q255824
get_authed_registries
validation
def get_authed_registries(): """Reads the local Docker client config for the current user and returns all registries to which the user may be logged in. This is intended to be run client-side, not by the daemon.""" result = set() if not os.path.exists(constants.DOCKER_CONFIG_PATH): return re...
python
{ "resource": "" }
q255825
streaming_to_client
validation
def streaming_to_client(): """Puts the client logger into streaming mode, which sends unbuffered input through to the socket one character at a time. We also disable propagation so the root logger does not receive many one-byte emissions. This context handler was originally created for streaming Com...
python
{ "resource": "" }
q255826
pty_fork
validation
def pty_fork(*args): """Runs a subprocess with a PTY attached via fork and exec. The output from the PTY is streamed through log_to_client. This should not be necessary for most subprocesses, we built this to handle Compose up which only streams pull progress if it is attached to a TTY.""" upda...
python
{ "resource": "" }
q255827
_compile_docker_commands
validation
def _compile_docker_commands(app_name, assembled_specs, port_spec): """ This is used to compile the command that will be run when the docker container starts up. This command has to install any libs that the app uses, run the `always` command, and run the `once` command if the container is being launched fo...
python
{ "resource": "" }
q255828
_increase_file_handle_limit
validation
def _increase_file_handle_limit(): """Raise the open file handles permitted by the Dusty daemon process and its child processes. The number we choose here needs to be within the OS X default kernel hard limit, which is 10240.""" logging.info('Increasing file handle limit to {}'.format(constants.FILE_HAN...
python
{ "resource": "" }
q255829
_start_http_server
validation
def _start_http_server(): """Start the daemon's HTTP server on a separate thread. This server is only used for servicing container status requests from Dusty's custom 502 page.""" logging.info('Starting HTTP server at {}:{}'.format(constants.DAEMON_HTTP_BIND_IP, ...
python
{ "resource": "" }
q255830
get_docker_client
validation
def get_docker_client(): """Ripped off and slightly modified based on docker-py's kwargs_from_env utility function.""" env = get_docker_env() host, cert_path, tls_verify = env['DOCKER_HOST'], env['DOCKER_CERT_PATH'], env['DOCKER_TLS_VERIFY'] params = {'base_url': host.replace('tcp://', 'https://'),...
python
{ "resource": "" }
q255831
get_dusty_containers
validation
def get_dusty_containers(services, include_exited=False): """Get a list of containers associated with the list of services. If no services are provided, attempts to return all containers associated with Dusty.""" client = get_docker_client() if services: containers = [get_container_for_app_o...
python
{ "resource": "" }
q255832
configure_nfs_server
validation
def configure_nfs_server(): """ This function is used with `dusty up`. It will check all active repos to see if they are exported. If any are missing, it will replace current dusty exports with exports that are needed for currently active repos, and restart the nfs server """ repos_for_exp...
python
{ "resource": "" }
q255833
_ensure_managed_repos_dir_exists
validation
def _ensure_managed_repos_dir_exists(): """ Our exports file will be invalid if this folder doesn't exist, and the NFS server will not run correctly. """ if not os.path.exists(constants.REPOS_DIR): os.makedirs(constants.REPOS_DIR)
python
{ "resource": "" }
q255834
register_consumer
validation
def register_consumer(): """Given a hostname and port attempting to be accessed, return a unique consumer ID for accessing logs from the referenced container.""" global _consumers hostname, port = request.form['hostname'], request.form['port'] app_name = _app_name_from_forwarding_info(hostname,...
python
{ "resource": "" }
q255835
consume
validation
def consume(consumer_id): """Given an existing consumer ID, return any new lines from the log since the last time the consumer was consumed.""" global _consumers consumer = _consumers[consumer_id] client = get_docker_client() try: status = client.inspect_container(consumer.container_id)...
python
{ "resource": "" }
q255836
get_app_volume_mounts
validation
def get_app_volume_mounts(app_name, assembled_specs, test=False): """ This returns a list of formatted volume specs for an app. These mounts declared in the apps' spec and mounts declared in all lib specs the app depends on""" app_spec = assembled_specs['apps'][app_name] volumes = [get_command_files_vol...
python
{ "resource": "" }
q255837
get_lib_volume_mounts
validation
def get_lib_volume_mounts(base_lib_name, assembled_specs): """ Returns a list of the formatted volume specs for a lib""" volumes = [_get_lib_repo_volume_mount(assembled_specs['libs'][base_lib_name])] volumes.append(get_command_files_volume_mount(base_lib_name, test=True)) for lib_name in assembled_specs...
python
{ "resource": "" }
q255838
_get_app_libs_volume_mounts
validation
def _get_app_libs_volume_mounts(app_name, assembled_specs): """ Returns a list of the formatted volume mounts for all libs that an app uses """ volumes = [] for lib_name in assembled_specs['apps'][app_name]['depends']['libs']: lib_spec = assembled_specs['libs'][lib_name] volumes.append("{}:{...
python
{ "resource": "" }
q255839
_dusty_vm_exists
validation
def _dusty_vm_exists(): """We use VBox directly instead of Docker Machine because it shaves about 0.5 seconds off the runtime of this check.""" existing_vms = check_output_demoted(['VBoxManage', 'list', 'vms']) for line in existing_vms.splitlines(): if '"{}"'.format(constants.VM_MACHINE_NAME) in...
python
{ "resource": "" }
q255840
_init_docker_vm
validation
def _init_docker_vm(): """Initialize the Dusty VM if it does not already exist.""" if not _dusty_vm_exists(): log_to_client('Initializing new Dusty VM with Docker Machine') machine_options = ['--driver', 'virtualbox', '--virtualbox-cpu-count', '-1', ...
python
{ "resource": "" }
q255841
_start_docker_vm
validation
def _start_docker_vm(): """Start the Dusty VM if it is not already running.""" is_running = docker_vm_is_running() if not is_running: log_to_client('Starting docker-machine VM {}'.format(constants.VM_MACHINE_NAME)) _apply_nat_dns_host_resolver() _apply_nat_net_less_greedy_subnet() ...
python
{ "resource": "" }
q255842
docker_vm_is_running
validation
def docker_vm_is_running(): """Using VBoxManage is 0.5 seconds or so faster than Machine.""" running_vms = check_output_demoted(['VBoxManage', 'list', 'runningvms']) for line in running_vms.splitlines(): if '"{}"'.format(constants.VM_MACHINE_NAME) in line: return True return False
python
{ "resource": "" }
q255843
_get_localhost_ssh_port
validation
def _get_localhost_ssh_port(): """Something in the VM chain, either VirtualBox or Machine, helpfully sets up localhost-to-VM forwarding on port 22. We can inspect this rule to determine the port on localhost which gets forwarded to 22 in the VM.""" for line in _get_vm_config(): if line.start...
python
{ "resource": "" }
q255844
_get_host_only_mac_address
validation
def _get_host_only_mac_address(): """Returns the MAC address assigned to the host-only adapter, using output from VBoxManage. Returned MAC address has no colons and is lower-cased.""" # Get the number of the host-only adapter vm_config = _get_vm_config() for line in vm_config: if line.st...
python
{ "resource": "" }
q255845
_ip_for_mac_from_ip_addr_show
validation
def _ip_for_mac_from_ip_addr_show(ip_addr_show, target_mac): """Given the rather-complex output from an 'ip addr show' command on the VM, parse the output to determine the IP address assigned to the interface with the given MAC.""" return_next_ip = False for line in ip_addr_show.splitlines(): ...
python
{ "resource": "" }
q255846
_get_host_only_ip
validation
def _get_host_only_ip(): """Determine the host-only IP of the Dusty VM through Virtualbox and SSH directly, bypassing Docker Machine. We do this because Docker Machine is much slower, taking about 600ms total. We are basically doing the same flow Docker Machine does in its own code.""" mac = _get_ho...
python
{ "resource": "" }
q255847
create_local_copy
validation
def create_local_copy(cookie_file): """Make a local copy of the sqlite cookie database and return the new filename. This is necessary in case this database is still being written to while the user browses to avoid sqlite locking errors. """ # if type of cookie_file is a list, use the first element i...
python
{ "resource": "" }
q255848
create_cookie
validation
def create_cookie(host, path, secure, expires, name, value): """Shortcut function to create a cookie """ return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path, True, secure, expires, False, None, None, {})
python
{ "resource": "" }
q255849
load
validation
def load(domain_name=""): """Try to load cookies from all supported browsers and return combined cookiejar Optionally pass in a domain name to only load cookies from the specified domain """ cj = http.cookiejar.CookieJar() for cookie_fn in [chrome, firefox]: try: for cookie in co...
python
{ "resource": "" }
q255850
Chrome.load
validation
def load(self): """Load sqlite cookies into a cookiejar """ con = sqlite3.connect(self.tmp_cookie_file) cur = con.cursor() try: # chrome <=55 cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value ' 'F...
python
{ "resource": "" }
q255851
Chrome._decrypt
validation
def _decrypt(self, value, encrypted_value): """Decrypt encoded cookies """ if sys.platform == 'win32': return self._decrypt_windows_chrome(value, encrypted_value) if value or (encrypted_value[:3] != b'v10'): return value # Encrypted cookies should be pr...
python
{ "resource": "" }
q255852
_randone
validation
def _randone(d, limit=20, grouprefs=None): if grouprefs is None: grouprefs = {} """docstring for _randone""" ret = '' for i in d: if i[0] == sre_parse.IN: ret += choice(_in(i[1])) elif i[0] == sre_parse.LITERAL: ret += unichr(i[1]) elif i[0] == sre...
python
{ "resource": "" }
q255853
parse
validation
def parse(s): """Regular expression parser :param s: Regular expression :type s: str :rtype: list """ if IS_PY3: r = sre_parse.parse(s, flags=U) else: r = sre_parse.parse(s.decode('utf-8'), flags=U) return list(r)
python
{ "resource": "" }
q255854
ib64_patched
validation
def ib64_patched(self, attrsD, contentparams): """ Patch isBase64 to prevent Base64 encoding of JSON content """ if attrsD.get("mode", "") == "base64": return 0 if self.contentparams["type"].startswith("text/"): return 0 if self.contentparams["type"].endswith("+xml"): return ...
python
{ "resource": "" }
q255855
cleanwrap
validation
def cleanwrap(func): """ Wrapper for Zotero._cleanup """ def enc(self, *args, **kwargs): """ Send each item to _cleanup() """ return (func(self, item, **kwargs) for item in args) return enc
python
{ "resource": "" }
q255856
ss_wrap
validation
def ss_wrap(func): """ ensure that a SavedSearch object exists """ def wrapper(self, *args, **kwargs): if not self.savedsearch: self.savedsearch = SavedSearch(self) return func(self, *args, **kwargs) return wrapper
python
{ "resource": "" }
q255857
error_handler
validation
def error_handler(req): """ Error handler for HTTP requests """ error_codes = { 400: ze.UnsupportedParams, 401: ze.UserNotAuthorised, 403: ze.UserNotAuthorised, 404: ze.ResourceNotFound, 409: ze.Conflict, 412: ze.PreConditionFailed, 413: ze.RequestEnti...
python
{ "resource": "" }
q255858
Zotero.default_headers
validation
def default_headers(self): """ It's always OK to include these headers """ _headers = { "User-Agent": "Pyzotero/%s" % __version__, "Zotero-API-Version": "%s" % __api_version__, } if self.api_key: _headers["Authorization"] = "Bearer %s" ...
python
{ "resource": "" }
q255859
Zotero._cache
validation
def _cache(self, response, key): """ Add a retrieved template to the cache for 304 checking accepts a dict and key name, adds the retrieval time, and adds both to self.templates as a new dict using the specified key """ # cache template and retrieval time for subsequent c...
python
{ "resource": "" }
q255860
Zotero._cleanup
validation
def _cleanup(self, to_clean, allow=()): """ Remove keys we added for internal use """ # this item's been retrieved from the API, we only need the 'data' # entry if to_clean.keys() == ["links", "library", "version", "meta", "key", "data"]: to_clean = to_clean["data"] ...
python
{ "resource": "" }
q255861
Zotero._retrieve_data
validation
def _retrieve_data(self, request=None): """ Retrieve Zotero items via the API Combine endpoint and request to access the specific resource Returns a JSON document """ full_url = "%s%s" % (self.endpoint, request) # The API doesn't return this any more, so we have t...
python
{ "resource": "" }
q255862
Zotero._extract_links
validation
def _extract_links(self): """ Extract self, first, next, last links from a request response """ extracted = dict() try: for key, value in self.request.links.items(): parsed = urlparse(value["url"]) fragment = "{path}?{query}".format(pat...
python
{ "resource": "" }
q255863
Zotero._build_query
validation
def _build_query(self, query_string, no_params=False): """ Set request parameters. Will always add the user ID if it hasn't been specifically set by an API method """ try: query = quote(query_string.format(u=self.library_id, t=self.library_type)) except KeyErr...
python
{ "resource": "" }
q255864
Zotero.publications
validation
def publications(self): """ Return the contents of My Publications """ if self.library_type != "users": raise ze.CallDoesNotExist( "This API call does not exist for group libraries" ) query_string = "/{t}/{u}/publications/items" return self...
python
{ "resource": "" }
q255865
Zotero.num_collectionitems
validation
def num_collectionitems(self, collection): """ Return the total number of items in the specified collection """ query = "/{t}/{u}/collections/{c}/items".format( u=self.library_id, t=self.library_type, c=collection.upper() ) return self._totals(query)
python
{ "resource": "" }
q255866
Zotero.num_tagitems
validation
def num_tagitems(self, tag): """ Return the total number of items for the specified tag """ query = "/{t}/{u}/tags/{ta}/items".format( u=self.library_id, t=self.library_type, ta=tag ) return self._totals(query)
python
{ "resource": "" }
q255867
Zotero._totals
validation
def _totals(self, query): """ General method for returning total counts """ self.add_parameters(limit=1) query = self._build_query(query) self._retrieve_data(query) self.url_params = None # extract the 'total items' figure return int(self.request.headers["...
python
{ "resource": "" }
q255868
Zotero.key_info
validation
def key_info(self, **kwargs): """ Retrieve info about the permissions associated with the key associated to the given Zotero instance """ query_string = "/keys/{k}".format(k=self.api_key) return self._build_query(query_string)
python
{ "resource": "" }
q255869
Zotero.fulltext_item
validation
def fulltext_item(self, itemkey, **kwargs): """ Get full-text content for an item""" query_string = "/{t}/{u}/items/{itemkey}/fulltext".format( t=self.library_type, u=self.library_id, itemkey=itemkey ) return self._build_query(query_string)
python
{ "resource": "" }
q255870
Zotero.last_modified_version
validation
def last_modified_version(self, **kwargs): """ Get the last modified version """ self.items(**kwargs) return int(self.request.headers.get("last-modified-version", 0))
python
{ "resource": "" }
q255871
Zotero.file
validation
def file(self, item, **kwargs): """ Get the file from an specific item """ query_string = "/{t}/{u}/items/{i}/file".format( u=self.library_id, t=self.library_type, i=item.upper() ) return self._build_query(query_string, no_params=True)
python
{ "resource": "" }
q255872
Zotero.dump
validation
def dump(self, itemkey, filename=None, path=None): """ Dump a file attachment to disk, with optional filename and path """ if not filename: filename = self.item(itemkey)["data"]["filename"] if path: pth = os.path.join(path, filename) else: ...
python
{ "resource": "" }
q255873
Zotero.all_collections
validation
def all_collections(self, collid=None): """ Retrieve all collections and subcollections. Works for top-level collections or for a specific collection. Works at all collection depths. """ all_collections = [] def subcoll(clct): """ recursively add collections ...
python
{ "resource": "" }
q255874
Zotero.collections_sub
validation
def collections_sub(self, collection, **kwargs): """ Get subcollections for a specific collection """ query_string = "/{t}/{u}/collections/{c}/collections".format( u=self.library_id, t=self.library_type, c=collection.upper() ) return self._build_query(query_string)
python
{ "resource": "" }
q255875
Zotero.everything
validation
def everything(self, query): """ Retrieve all items in the library for a particular query This method will override the 'limit' parameter if it's been set """ try: items = [] items.extend(query) while self.links.get("next"): ite...
python
{ "resource": "" }
q255876
Zotero._json_processor
validation
def _json_processor(self, retrieved): """ Format and return data from API calls which return Items """ json_kwargs = {} if self.preserve_json_order: json_kwargs["object_pairs_hook"] = OrderedDict # send entries to _tags_data if there's no JSON try: ...
python
{ "resource": "" }
q255877
Zotero._csljson_processor
validation
def _csljson_processor(self, retrieved): """ Return a list of dicts which are dumped CSL JSON """ items = [] json_kwargs = {} if self.preserve_json_order: json_kwargs["object_pairs_hook"] = OrderedDict for csl in retrieved.entries: items.append(jso...
python
{ "resource": "" }
q255878
Zotero._bib_processor
validation
def _bib_processor(self, retrieved): """ Return a list of strings formatted as HTML bibliography entries """ items = [] for bib in retrieved.entries: items.append(bib["content"][0]["value"]) self.url_params = None return items
python
{ "resource": "" }
q255879
Zotero._citation_processor
validation
def _citation_processor(self, retrieved): """ Return a list of strings formatted as HTML citation entries """ items = [] for cit in retrieved.entries: items.append(cit["content"][0]["value"]) self.url_params = None return items
python
{ "resource": "" }
q255880
Zotero.item_template
validation
def item_template(self, itemtype): """ Get a template for a new item """ # if we have a template and it hasn't been updated since we stored it template_name = "item_template_" + itemtype query_string = "/items/new?itemType={i}".format(i=itemtype) if self.templates.get(tem...
python
{ "resource": "" }
q255881
Zotero._attachment
validation
def _attachment(self, payload, parentid=None): """ Create attachments accepts a list of one or more attachment template dicts and an optional parent Item ID. If this is specified, attachments are created under this ID """ attachment = Zupload(self, payload, parent...
python
{ "resource": "" }
q255882
Zotero.show_condition_operators
validation
def show_condition_operators(self, condition): """ Show available operators for a given saved search condition """ # dict keys of allowed operators for the current condition permitted_operators = self.savedsearch.conditions_operators.get(condition) # transform these into values p...
python
{ "resource": "" }
q255883
Zotero.delete_saved_search
validation
def delete_saved_search(self, keys): """ Delete one or more saved searches by passing a list of one or more unique search keys """ headers = {"Zotero-Write-Token": token()} headers.update(self.default_headers()) req = requests.delete( url=self.endpoint ...
python
{ "resource": "" }
q255884
Zotero.add_tags
validation
def add_tags(self, item, *tags): """ Add one or more tags to a retrieved item, then update it on the server Accepts a dict, and one or more tags to add to it Returns the updated item from the server """ # Make sure there's a tags field, or add one try: ...
python
{ "resource": "" }
q255885
Zotero.fields_types
validation
def fields_types(self, tname, qstring, itemtype): """ Retrieve item fields or creator types """ # check for a valid cached version template_name = tname + itemtype query_string = qstring.format(i=itemtype) if self.templates.get(template_name) and not self._updated( ...
python
{ "resource": "" }
q255886
Zotero.item_fields
validation
def item_fields(self): """ Get all available item fields """ # Check for a valid cached version if self.templates.get("item_fields") and not self._updated( "/itemFields", self.templates["item_fields"], "item_fields" ): return self.templates["item_fields"][...
python
{ "resource": "" }
q255887
Zotero.update_item
validation
def update_item(self, payload, last_modified=None): """ Update an existing item Accepts one argument, a dict containing Item data """ to_send = self.check_items([payload])[0] if last_modified is None: modified = payload["version"] else: mod...
python
{ "resource": "" }
q255888
Zotero.update_items
validation
def update_items(self, payload): """ Update existing items Accepts one argument, a list of dicts containing Item data """ to_send = [self.check_items([p])[0] for p in payload] headers = {} headers.update(self.default_headers()) # the API only accepts 50 it...
python
{ "resource": "" }
q255889
SavedSearch._validate
validation
def _validate(self, conditions): """ Validate saved search conditions, raising an error if any contain invalid operators """ allowed_keys = set(self.searchkeys) operators_set = set(self.operators.keys()) for condition in conditions: if set(condition.keys()) != allowed_keys: ...
python
{ "resource": "" }
q255890
Zupload.upload
validation
def upload(self): """ File upload functionality Goes through upload steps 0 - 3 (private class methods), and returns a dict noting success, failure, or unchanged (returning the payload entries with that property as a list for each status) """ result = {"success":...
python
{ "resource": "" }
q255891
split_multiline
validation
def split_multiline(value): """Split a multiline string into a list, excluding blank lines.""" return [element for element in (line.strip() for line in value.split('\n')) if element]
python
{ "resource": "" }
q255892
split_elements
validation
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" items = [v.strip() for v in value.split(',')] if len(items) == 1: items = value.split() return items
python
{ "resource": "" }
q255893
eval_environ
validation
def eval_environ(value): """Evaluate environment markers.""" def eval_environ_str(value): parts = value.split(';') if len(parts) < 2: return value expr = parts[1].lstrip() if not re.match("^((\\w+(\\.\\w+)?|'.*?'|\".*?\")\\s+" '(in|==|!=|not in...
python
{ "resource": "" }
q255894
get_cfg_value
validation
def get_cfg_value(config, section, option): """Get configuration value.""" try: value = config[section][option] except KeyError: if (section, option) in MULTI_OPTIONS: return [] else: return '' if (section, option) in MULTI_OPTIONS: value = split_m...
python
{ "resource": "" }
q255895
set_cfg_value
validation
def set_cfg_value(config, section, option, value): """Set configuration value.""" if isinstance(value, list): value = '\n'.join(value) config[section][option] = value
python
{ "resource": "" }
q255896
cfg_to_args
validation
def cfg_to_args(config): """Compatibility helper to use setup.cfg in setup.py.""" kwargs = {} opts_to_args = { 'metadata': [ ('name', 'name'), ('author', 'author'), ('author-email', 'author_email'), ('maintainer', 'maintainer'), ('maintaine...
python
{ "resource": "" }
q255897
run_3to2
validation
def run_3to2(args=None): """Convert Python files using lib3to2.""" args = BASE_ARGS_3TO2 if args is None else BASE_ARGS_3TO2 + args try: proc = subprocess.Popen(['3to2'] + args, stderr=subprocess.PIPE) except OSError: for path in glob.glob('*.egg'): if os.path.isdir(path) and...
python
{ "resource": "" }
q255898
write_py2k_header
validation
def write_py2k_header(file_list): """Write Python 2 shebang and add encoding cookie if needed.""" if not isinstance(file_list, list): file_list = [file_list] python_re = re.compile(br"^(#!.*\bpython)(.*)([\r\n]+)$") coding_re = re.compile(br"coding[:=]\s*([-\w.]+)") new_line_re = re.compile...
python
{ "resource": "" }
q255899
get_version
validation
def get_version(): """Get LanguageTool version.""" version = _get_attrib().get('version') if not version: match = re.search(r"LanguageTool-?.*?(\S+)$", get_directory()) if match: version = match.group(1) return version
python
{ "resource": "" }