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 text_embedding_column(key, module_spec, trainable=False): """Uses a Module to construct a dense representation from a text feature. This feature column can b...
module_spec = module.as_module_spec(module_spec) _check_module_is_text_embedding(module_spec) return _TextEmbeddingColumn(key=key, module_spec=module_spec, trainable=trainable)
<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_module_is_text_embedding(module_spec): """Raises ValueError if `module_spec` is not a text-embedding module. Args: module_spec: A `ModuleSpec` to test...
issues = [] # Find issues with signature inputs. input_info_dict = module_spec.get_input_info_dict() if len(input_info_dict) != 1: issues.append("Module default signature must require only one input") else: input_info, = input_info_dict.values() input_shape = input_info.get_shape() if not (i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_embedding_column(key, module_spec): """Uses a Module to get a dense 1-D representation from the pixels of images. This feature column can be used on im...
module_spec = module.as_module_spec(module_spec) _check_module_is_image_embedding(module_spec) return _ImageEmbeddingColumn(key=key, module_spec=module_spec)
<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_module_is_image_embedding(module_spec): """Raises ValueError if `module_spec` is not usable as image embedding. Args: module_spec: A `_ModuleSpec` to ...
issues = [] # Find issues with "default" signature inputs. The common signatures for # image models prescribe a specific name; we trust it if we find it # and if we can do the necessary inference of input shapes from it. input_info_dict = module_spec.get_input_info_dict() if (list(input_info_dict.keys()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self): """Returns string. Used for variable_scope and naming."""
if not hasattr(self, "_name"): self._name = "{}_hub_module_embedding".format(self.key) return self._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_dense_tensor(self, inputs, weight_collections=None, trainable=None): """Returns a `Tensor`."""
del weight_collections text_batch = tf.reshape(inputs.get(self), shape=[-1]) m = module.Module(self.module_spec, trainable=self.trainable and trainable) return m(text_batch)
<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_example_spec(self): """Returns a `tf.Example` parsing spec as dict."""
height, width = image_util.get_expected_image_size(self.module_spec) input_shape = [height, width, 3] return {self.key: tf_v1.FixedLenFeature(input_shape, tf.float32)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tfhub_cache_dir(default_cache_dir=None, use_temp=False): """Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable...
# Note: We are using FLAGS["tfhub_cache_dir"] (and not FLAGS.tfhub_cache_dir) # to access the flag value in order to avoid parsing argv list. The flags # should have been parsed by now in main() by tf.app.run(). If that was not # the case (say in Colab env) we skip flag parsing because argv may contain # un...
<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_local_module_dir(cache_dir, module_name): """Creates and returns the name of directory where to cache a module."""
tf_v1.gfile.MakeDirs(cache_dir) return os.path.join(cache_dir, module_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 _write_module_descriptor_file(handle, module_dir): """Writes a descriptor file about the directory containing a module. Args: handle: Module name/handle. mod...
readme = _module_descriptor_file(module_dir) readme_content = ( "Module: %s\nDownload Time: %s\nDownloader Hostname: %s (PID:%d)" % (handle, str(datetime.datetime.today()), socket.gethostname(), os.getpid())) # The descriptor file has no semantic meaning so we allow 'overwrite' since # there...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _locked_tmp_dir_size(lock_filename): """Returns the size of the temp dir pointed to by the given lock file."""
task_uid = _task_uid_from_lock_file(lock_filename) try: return _dir_size( _temp_download_dir(_module_dir(lock_filename), task_uid)) except tf.errors.NotFoundError: return 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 _wait_for_lock_to_disappear(handle, lock_file, lock_file_timeout_sec): """Waits for the lock file to disappear. The lock file was created by another process ...
locked_tmp_dir_size = 0 locked_tmp_dir_size_check_time = time.time() lock_file_content = None while tf_v1.gfile.Exists(lock_file): try: logging.log_every_n( logging.INFO, "Module '%s' already being downloaded by '%s'. Waiting.", 10, handle, tf_utils.read_file_to_string(l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def atomic_download(handle, download_fn, module_dir, lock_file_timeout_sec=10 * 60): """Returns the path to a Module directory for a given TF-Hub Module handle. ...
lock_file = _lock_filename(module_dir) task_uid = uuid.uuid4().hex lock_contents = _lock_file_contents(task_uid) tmp_dir = _temp_download_dir(module_dir, task_uid) # Attempt to protect against cases of processes being cancelled with # KeyboardInterrupt by using a try/finally clause to remove the lock # ...
<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_download_progress_msg(self, msg, flush=False): """Prints a message about download progress either to the console or TF log. Args: msg: Message to prin...
if self._interactive_mode(): # Print progress message to console overwriting previous progress # message. self._max_prog_str = max(self._max_prog_str, len(msg)) sys.stdout.write("\r%-{}s".format(self._max_prog_str) % msg) sys.stdout.flush() if flush: print("\n") else...
<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_progress(self, bytes_downloaded): """Logs progress information about ongoing module download. Args: bytes_downloaded: Number of bytes downloaded. """
self._total_bytes_downloaded += bytes_downloaded now = time.time() if (self._interactive_mode() or now - self._last_progress_msg_print_time > 15): # Print progress message every 15 secs or if interactive progress # tracking is enabled. self._print_download_progress_msg( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_file(self, tgz, tarinfo, dst_path, buffer_size=10<<20): """Extracts 'tarinfo' from 'tgz' and writes to 'dst_path'."""
src = tgz.extractfile(tarinfo) dst = tf_v1.gfile.GFile(dst_path, "wb") while 1: buf = src.read(buffer_size) if not buf: break dst.write(buf) self._log_progress(len(buf)) dst.close() src.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_and_uncompress(self, fileobj, dst_path): """Streams the content for the 'fileobj' and stores the result in dst_path. Args: fileobj: File handle poin...
try: with tarfile.open(mode="r|*", fileobj=fileobj) as tgz: for tarinfo in tgz: abs_target_path = _merge_relative_path(dst_path, tarinfo.name) if tarinfo.isfile(): self._extract_file(tgz, tarinfo, abs_target_path) elif tarinfo.isdir(): tf_v1.gfil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepend_name_scope(name, import_scope): """Prepends name scope to a name."""
# Based on tensorflow/python/framework/ops.py implementation. if import_scope: try: str_to_replace = r"([\^]|loc:@|^)(.*)" return re.sub(str_to_replace, r"\1" + import_scope + r"/\2", tf.compat.as_str_any(name)) except TypeError as e: # If the name is not of a type we ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prefix_shared_name_attributes(meta_graph, absolute_import_scope): """In-place prefixes shared_name attributes of nodes."""
shared_name_attr = "shared_name" for node in meta_graph.graph_def.node: shared_name_value = node.attr.get(shared_name_attr, None) if shared_name_value and shared_name_value.HasField("s"): if shared_name_value.s: node.attr[shared_name_attr].s = tf.compat.as_bytes( prepend_name_scop...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark_backward(output_tensor, used_node_names): """Function to propagate backwards in the graph and mark nodes as used. Traverses recursively through the grap...
op = output_tensor.op if op.name in used_node_names: return used_node_names.add(op.name) for input_tensor in op.inputs: mark_backward(input_tensor, used_node_names) for control_input_op in op.control_inputs: used_node_names.add(control_input_op.name) for input_tensor in control_input_op.input...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prune_unused_nodes(meta_graph, signature_def): """Function to prune unused ops given a signature def. This function does a graph traversal through from all o...
# Instantiate a temporary empty graph so that we have access to Graph API # and import the meta_graph. graph = tf_v1.Graph() with graph.as_default(): tf_v1.train.import_meta_graph(meta_graph, input_map={}, import_scope="") # Traverse from all outputs and mark all nodes. used_node_names = set() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prune_feed_map(meta_graph, feed_map): """Function to prune the feedmap of nodes which no longer exist."""
node_names = [x.name + ":0" for x in meta_graph.graph_def.node] keys_to_delete = [] for k, _ in feed_map.items(): if k not in node_names: keys_to_delete.append(k) for k in keys_to_delete: del feed_map[k]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def atomic_write_string_to_file(filename, contents, overwrite): """Writes to `filename` atomically. This means that when `filename` appears in the filesystem, it...
temp_pathname = (tf.compat.as_bytes(filename) + tf.compat.as_bytes(".tmp") + tf.compat.as_bytes(uuid.uuid4().hex)) with tf_v1.gfile.GFile(temp_pathname, mode="w") as f: f.write(contents) try: tf_v1.gfile.Rename(temp_pathname, filename, overwrite) except tf.errors.O...
<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_timestamped_export_dir(export_dir_base): """Builds a path to a new subdirectory within the base directory. Each export is written into a new subdirectory...
attempts = 0 while attempts < MAX_DIRECTORY_CREATION_ATTEMPTS: export_timestamp = int(time.time()) export_dir = os.path.join( tf.compat.as_bytes(export_dir_base), tf.compat.as_bytes(str(export_timestamp))) if not tf_v1.gfile.Exists(export_dir): # Collisions are still possible (th...
<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_temp_export_dir(timestamped_export_dir): """Builds a directory name based on the argument but starting with 'temp-'. This relies on the fact that TensorF...
(dirname, basename) = os.path.split(timestamped_export_dir) temp_export_dir = os.path.join( tf.compat.as_bytes(dirname), tf.compat.as_bytes("temp-{}".format(basename))) return temp_export_dir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def garbage_collect_exports(export_dir_base, exports_to_keep): """Deletes older exports, retaining only a given number of the most recent. Export subdirectories ...
if exports_to_keep is None: return version_paths = [] # List of tuples (version, path) for filename in tf_v1.gfile.ListDirectory(export_dir_base): path = os.path.join( tf.compat.as_bytes(export_dir_base), tf.compat.as_bytes(filename)) if len(filename) == 10 and filename.isdigit(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bytes_to_readable_str(num_bytes, include_b=False): """Generate a human-readable string representing number of bytes. The units B, kB, MB and GB are used. Arg...
if num_bytes is None: return str(num_bytes) if num_bytes < 1024: result = "%d" % num_bytes elif num_bytes < 1048576: result = "%.2fk" % (num_bytes / float(1 << 10)) elif num_bytes < 1073741824: result = "%.2fM" % (num_bytes / float(1 << 20)) else: result = "%.2fG" % (num_bytes / float(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 announce(version): """Generates a new release announcement entry in the docs."""
# Get our list of authors stdout = check_output(["git", "describe", "--abbrev=0", "--tags"]) stdout = stdout.decode("utf-8") last_version = stdout.strip() stdout = check_output( ["git", "log", "{}..HEAD".format(last_version), "--format=%aN"] ) stdout = stdout.decode("utf-8") c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ca_bundle(self, ca_bundle): """ Sets the ca_bundle of this V1alpha1WebhookClientConfig. `caBundle` is a PEM encoded CA bundle which will be used to validate ...
if ca_bundle is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', ca_bundle): raise ValueError("Invalid value for `ca_bundle`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") 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 raw(self, raw): """ Sets the raw of this RuntimeRawExtension. Raw is the underlying serialization of this object. :param raw: The raw of this RuntimeRawExten...
if raw is None: raise ValueError("Invalid value for `raw`, must not be `None`") if raw is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', raw): raise ValueError("Invalid value for `raw`, must be a follow pattern or equal to `/^(?...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pool(self): """Create thread pool on first request avoids instantiating unused threadpool for blocking clients. """
if self._pool is None: self._pool = ThreadPool(self.pool_threads) return self._pool
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def debug(self, value): """ Sets the debug status. :param value: The debug status, True or False. :type: bool """
self.__debug = value if self.__debug: # if debug status is True, turn on debug logging for _, logger in iteritems(self.logger): logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logger_format(self, value): """ Sets the logger_format. The logger_formatter will be updated when sets logger_format. :param value: The format string. :type:...
self.__logger_format = value self.logger_formatter = logging.Formatter(self.__logger_format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certificate(self, certificate): """ Sets the certificate of this V1beta1CertificateSigningRequestStatus. If request was approved, the controller will place t...
if certificate is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', certificate): raise ValueError("Invalid value for `certificate`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def notify_owner(func): ''' A decorator for mutating methods of property container classes that notifies owners of the property container about mutating changes. Args: func (callable) : the container method to wrap in a notification Returns: wrapped method Examples: A ``_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _stream(self, doc, source, new_data, rollover=None, setter=None): ''' Internal implementation to handle special-casing stream events on ``ColumnDataSource`` columns. Normally any changes to the ``.data`` dict attribute on a ``ColumnDataSource`` triggers a notification, causing all o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _patch(self, doc, source, patches, setter=None): ''' Internal implementation to handle special-casing patch events on ``ColumnDataSource`` columns. Normally any changes to the ``.data`` dict attribute on a ``ColumnDataSource`` triggers a notification, causing all of the 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 license(): ''' Print the Bokeh license to the console. Returns: None ''' from os.path import join with open(join(__path__[0], 'LICENSE.txt')) as lic: print(lic.read())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _copy_default(cls, default): ''' Return a copy of the default, or a new value if the default is specified by a function. ''' if not isinstance(default, types.FunctionType): return copy(default) else: return default()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def matches(self, new, old): ''' Whether two parameters match values. If either ``new`` or ``old`` is a NumPy array or Pandas Series or Index, then the result of ``np.array_equal`` will determine if the values match. Otherwise, the result of standard Python equality will be returned. ...
<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_valid(self, value): ''' Whether the value passes validation Args: value (obj) : the value to validate against this property type Returns: True if valid, False otherwise ''' try: if validation_on(): self.validate(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 accepts(self, tp, converter): ''' Declare that other types may be converted to this property type. Args: tp (Property) : A type that may be converted automatically to this property type. converter (callable) : A function accep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def asserts(self, fn, msg_or_fn): ''' Assert that prepared values satisfy given conditions. Assertions are intended in enforce conditions beyond simple value type validation. For instance, this method can be use to assert that the columns of a ``ColumnDataSource`` all collectively have ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def url_path(self): ''' The last path component for the basename of the configured filename. ''' if self.failed: return None else: # TODO should fix invalid URL characters return '/' + os.path.splitext(os.path.basename(self._runner.path))[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 make_descriptors(self, base_name): ''' Return a list of ``PropertyDescriptor`` instances to install on a class, in order to delegate attribute access to this property. Unlike simpler property types, ``UnitsSpec`` returns multiple descriptors to install. In particular, descriptors fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def isconst(cls, val): ''' Whether the value is a string color literal. Checks for a well-formed hexadecimal color value or a named color. Args: val (str) : the value to check Returns: True, if the value is a string color literal ''' return isi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_object(filename, obj): """Compresses and pickles given object to the given filename."""
logging.info('saving {}...'.format(filename)) try: with gzip.GzipFile(filename, 'wb') as f: f.write(pickle.dumps(obj, 1)) except Exception as e: logging.error('save failure: {}'.format(e)) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_object(filename): """Unpickles and decompresses the given filename and returns the created object."""
logging.info('loading {}...'.format(filename)) try: with gzip.GzipFile(filename, 'rb') as f: buf = '' while True: data = f.read() if data == '': break buf += data return pickle.loads(buf) except ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def issue_section(issue): """Returns the section heading for the issue, or None if this issue should be ignored."""
labels = issue.get('labels', []) for label in labels: if not label['name'].startswith('type: '): continue if label['name'] in LOG_SECTION: return LOG_SECTION[label['name']] elif label['name'] in IGNORE_ISSUE_TYPE: return None else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def issue_tags(issue): """Returns list of tags for this issue."""
labels = issue.get('labels', []) return [label['name'].replace('tag: ', '') for label in labels if label['name'].startswith('tag: ')]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def closed_issue(issue, after=None): """Returns True iff this issue was closed after given date. If after not given, only checks if issue is closed."""
if issue['state'] == 'closed': if after is None or parse_timestamp(issue['closed_at']) > after: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relevent_issue(issue, after): """Returns True iff this issue is something we should show in the changelog."""
return (closed_issue(issue, after) and issue_completed(issue) and issue_section(issue))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_issues(issues): """Yields unique set of issues given a list of issues."""
logging.info('finding issues...') seen = set() for issue in issues: if issue['title'] not in seen: seen.add(issue['title']) yield issue
<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_issues_url(page, after): """Returns github API URL for querying tags."""
template = '{base_url}/{owner}/{repo}/issues?state=closed&per_page=100&page={page}&since={after}' return template.format(page=page, after=after.isoformat(), **API_PARAMS)
<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_timestamp(timestamp): """Parse ISO8601 timestamps given by github API."""
dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_url(url): """Reads given URL as JSON and returns data as loaded python object."""
logging.debug('reading {url} ...'.format(url=url)) token = os.environ.get("BOKEH_GITHUB_API_TOKEN") headers = {} if token: headers['Authorization'] = 'token %s' % token request = Request(url, headers=headers) response = urlopen(request).read() return json.loads(response.decode("UTF-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_all_issues(after): """Hits the github API for all closed issues after the given date, returns the data."""
page = count(1) data = [] while True: page_data = query_issues(next(page), after) if not page_data: break data.extend(page_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 dateof(tag_name, tags): """Given a list of tags, returns the datetime of the tag with the given name; Otherwise None."""
for tag in tags: if tag['name'] == tag_name: commit = read_url(tag['commit']['url']) return parse_timestamp(commit['commit']['committer']['date']) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_data(query_func, load_data=False, save_data=False): """Gets data from query_func, optionally saving that data to a file; or loads data from a file."""
if hasattr(query_func, '__name__'): func_name = query_func.__name__ elif hasattr(query_func, 'func'): func_name = query_func.func.__name__ pickle_file = '{}.pickle'.format(func_name) if load_data: data = load_object(pickle_file) else: data = query_func() if...
<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_issues(issues, after=None): """Checks issues for BEP 1 compliance."""
issues = closed_issues(issues, after) if after else all_issues(issues) issues = sorted(issues, key=ISSUES_SORT_KEY) have_warnings = False for section, issue_group in groupby(issues, key=ISSUES_BY_SECTION): for issue in issue_group: have_warnings |= check_issue(issue, after) r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def issue_line(issue): """Returns log line for given issue."""
template = '#{number} {tags}{title}' tags = issue_tags(issue) params = { 'title': issue['title'].capitalize().rstrip('.'), 'number': issue['number'], 'tags': ' '.join('[{}]'.format(tag) for tag in tags) + (' ' if tags else '') } return template.format(**params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_changelog(issues, after, heading, rtag=False): """Prints out changelog."""
relevent = relevant_issues(issues, after) relevent = sorted(relevent, key=ISSUES_BY_SECTION) def write(func, endofline="", append=""): func(heading + '\n' + '-' * 20 + endofline) for section, issue_group in groupby(relevent, key=ISSUES_BY_SECTION): func(' * {}:'.format(section...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_css(self): ''' Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"`` ''' if self.a == 1.0: return "rgb(%d, %d, %d)" % (self.r, self.g, self.b) else: return "rgba(%d, %d, %d, %s)" % (self.r, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_hsl(self): ''' Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB` ''' from .hsl import HSL # prevent circular import h, l, s = colorsys.rgb_to_hls(float(self.r)/255, float(self.g)/255, float(self.b)/255) retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yield_for_all_futures(result): """ Converts result into a Future by collapsing any futures inside result. If result is a Future we yield until it's done, the...
while True: # This is needed for Tornado >= 4.5 where convert_yielded will no # longer raise BadYieldError on None if result is None: break try: future = gen.convert_yielded(result) except gen.BadYieldError: # result is not a yieldable t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_all_callbacks(self): """ Removes all registered callbacks."""
for cb_id in list(self._next_tick_callback_removers.keys()): self.remove_next_tick_callback(cb_id) for cb_id in list(self._timeout_callback_removers.keys()): self.remove_timeout_callback(cb_id) for cb_id in list(self._periodic_callback_removers.keys()): 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 add_next_tick_callback(self, callback, callback_id=None): """ Adds a callback to be run on the next tick. Returns an ID that can be used with remove_next_tic...
def wrapper(*args, **kwargs): # this 'removed' flag is a hack because Tornado has no way # to remove a "next tick" callback added with # IOLoop.add_callback. So instead we make our wrapper skip # invoking the callback. if not wrapper.removed: ...
<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_timeout_callback(self, callback, timeout_milliseconds, callback_id=None): """ Adds a callback to be run once after timeout_milliseconds. Returns an ID th...
def wrapper(*args, **kwargs): self.remove_timeout_callback(callback_id) return callback(*args, **kwargs) handle = None def remover(): if handle is not None: self._loop.remove_timeout(handle) callback_id = self._assign_remover(callba...
<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_periodic_callback(self, callback, period_milliseconds, callback_id=None): """ Adds a callback to be run every period_milliseconds until it is removed. Re...
cb = _AsyncPeriodic(callback, period_milliseconds, io_loop=self._loop) callback_id = self._assign_remover(callback, callback_id, self._periodic_callback_removers, cb.stop) cb.start() return callback_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 bokeh_tree(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a URL in the Bokeh GitHub tree, pointing to appropriate tags for releases, or to master otherwise. The link text is simply the URL path supplied, so typical usage might look like: .. code-block:: 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 _make_gh_link_node(app, rawtext, role, kind, api_type, id, options=None): ''' Return a link to a Bokeh Github resource. Args: app (Sphinx app) : current app rawtext (str) : text being replaced with link node. role (str) : role name kind (str) : resource type (issue, pull, et...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def show_bokehjs(bokehjs_action, develop=False): ''' Print a useful report after setuptools output describing where and how BokehJS is installed. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def show_help(bokehjs_action): ''' Print information about extra Bokeh-specific command line options. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree Returns: None ''' print() if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fixup_building_sdist(): ''' Check for 'sdist' and ensure we always build BokehJS when packaging Source distributions do not ship with BokehJS source code, but must ship with a pre-built BokehJS library. This function modifies ``sys.argv`` as necessary so that ``--build-js`` IS present, and ``--inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fixup_for_packaged(): ''' If we are installing FROM an sdist, then a pre-built BokehJS is already installed in the python source tree. The command line options ``--build-js`` or ``--install-js`` are removed from ``sys.argv``, with a warning. Also adds ``--existing-js`` to ``sys.argv`` to signa...
<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_cmdclass(): ''' A ``cmdclass`` that works around a setuptools deficiency. There is no need to build wheels when installing a package, however some versions of setuptools seem to mandate this. This is a hacky workaround that modifies the ``cmdclass`` returned by versioneer so that not having ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def jsbuild_prompt(): ''' Prompt users whether to build a new BokehJS or install an existing one. Returns: bool : True, if a new build is requested, False otherwise ''' print(BOKEHJS_BUILD_PROMPT) mapping = {"1": True, "2": False} value = input("Choice? ") while value not in mappin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def install_js(): ''' Copy built BokehJS files into the Python source tree. Returns: None ''' target_jsdir = join(SERVER, 'static', 'js') target_cssdir = join(SERVER, 'static', 'css') target_tslibdir = join(SERVER, 'static', 'lib') STATIC_ASSETS = [ join(JS, 'bokeh.js'), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hexbin(x, y, size, orientation="pointytop", aspect_scale=1): ''' Perform an equal-weight binning of data points into hexagonal tiles. For more sophisticated use cases, e.g. weighted binning or scaling individual tiles proportional to some other quantity, consider using HoloViews. 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 from_json(self, json, models=None): ''' Decodes column source data encoded as lists or base64 strings. ''' if json is None: return None elif not isinstance(json, dict): raise DeserializationError("%s expected a dict or None, got %s" % (self, json)) new...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convert_timedelta_type(obj): ''' Convert any recognized timedelta value to floating point absolute milliseconds. Arg: obj (object) : the object to convert Returns: float : milliseconds ''' if isinstance(obj, dt.timedelta): return obj.total_seconds() * 1000. eli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convert_datetime_type(obj): ''' Convert any recognized date, time, or datetime value to floating point milliseconds since epoch. Arg: obj (object) : the object to convert Returns: float : milliseconds ''' # Pandas NaT if pd and obj is pd.NaT: return np.nan ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convert_datetime_array(array): ''' Convert NumPy datetime arrays to arrays to milliseconds since epoch. Args: array : (obj) A NumPy array of datetime to convert If the value passed in is not a NumPy array, it will be returned as-is. Returns: array ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def make_id(): ''' Return a new unique ID for a Bokeh object. Normally this function will return simple monotonically increasing integer IDs (as strings) for identifying Bokeh objects within a Document. However, if it is desirable to have globally unique for every object, this behavior can be overr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def transform_array(array, force_list=False, buffers=None): ''' Transform a NumPy arrays into serialized format Converts un-serializable dtypes and returns JSON serializable format Args: array (np.ndarray) : a NumPy array to be transformed force_list (bool, optional) : whether to only ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def transform_array_to_list(array): ''' Transforms a NumPy array into a list of values Args: array (np.nadarray) : the NumPy array series to transform Returns: list or dict ''' if (array.dtype.kind in ('u', 'i', 'f') and (~np.isfinite(array)).any()): transformed = array.as...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def transform_series(series, force_list=False, buffers=None): ''' Transforms a Pandas series into serialized form Args: series (pd.Series) : the Pandas series to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes usi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize_array(array, force_list=False, buffers=None): ''' Transforms a NumPy array into serialized form. Args: array (np.ndarray) : the NumPy array to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def traverse_data(obj, use_numpy=True, buffers=None): ''' Recursively traverse an object until a flat list is found. If NumPy is available, the flat list is converted to a numpy array and passed to transform_array() to handle ``nan``, ``inf``, and ``-inf``. Otherwise, iterate through all items, co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def transform_column_source_data(data, buffers=None, cols=None): ''' Transform ``ColumnSourceData`` data to a serialized format Args: data (dict) : the mapping of names to data columns to transform buffers (set, optional) : If binary buffers are desired, the buffers parameter may b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def encode_binary_dict(array, buffers): ''' Send a numpy array as an unencoded binary buffer The encoded format is a dict with the following structure: .. code:: python { '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >>, 'dtype...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decode_base64_dict(data): ''' Decode a base64 encoded array into a NumPy array. Args: data (dict) : encoded array data to decode Data should have the format encoded by :func:`encode_base64_dict`. Returns: np.ndarray ''' b64 = base64.b64decode(data['__ndarray__']) arra...
<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_py_func(cls, code): ''' Create a ``CustomJSHover`` instance from a Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It is possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_coffeescript(cls, code, args={}): ''' Create a CustomJSHover instance from a CoffeeScript snippet. The function bodies are translated to JavaScript functions using node and therefore require return statements. The ``code`` snippet namespace will contain the variable ``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 get_codeblock_node(self, code, language): """this is copied from sphinx.directives.code.CodeBlock.run it has been changed to accept code and language as an a...
# type: () -> List[nodes.Node] document = self.state.document location = self.state_machine.get_source_and_line(self.lineno) linespec = self.options.get('emphasize-lines') if linespec: try: nlines = len(code.split('\n')) hl_lines = p...
<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_code_language(self): """ This is largely copied from bokeh.sphinxext.bokeh_plot.run """
js_source = self.get_js_source() if self.options.get("include_html", False): resources = get_sphinx_resources(include_bokehjs_api=True) html_source = BJS_HTML.render( css_files=resources.css_files, js_files=resources.js_files, bjs_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def autoload_static(model, resources, script_path): ''' Return JavaScript code and a script tag that can be used to embed Bokeh Plots. The data for the plot is stored directly in the returned JavaScript code. Args: model (Model or Document) : resources (Resources) : script_pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def components(models, wrap_script=True, wrap_plot_info=True, theme=FromCurdoc): ''' Return HTML components to embed a Bokeh plot. The data for the plot is stored directly in the returned HTML. An example can be found in examples/embed/embed_multiple.py The returned components assume that BokehJS reso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def file_html(models, resources, title=None, template=FILE, template_variables={}, theme=FromCurdoc, suppress_callback_warning=False, _always_new=False): ''' Return an HTML document that embeds Bokeh Model or Document ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def json_item(model, target=None, theme=FromCurdoc): ''' Return a JSON block that can be used to embed standalone Bokeh content. Args: model (Model) : The Bokeh object to embed target (string, optional) A div id to embed the model into. If None, the target id must ...