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 draw_annotation(img, boxes, klass, is_crowd=None): """Will not modify img"""
labels = [] assert len(boxes) == len(klass) if is_crowd is not None: assert len(boxes) == len(is_crowd) for cls, crd in zip(klass, is_crowd): clsname = cfg.DATA.CLASS_NAMES[cls] if crd == 1: clsname += ';Crowd' labels.append(clsname) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_mask(im, mask, alpha=0.5, color=None): """ Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image o...
if color is None: color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1] im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2), im * (1 - alpha) + color * alpha, im) im = im.astype('uint8') return im
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False): """ Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint ...
assert format in [None, 'zmq_op', 'zmq_ops'] if format is None: dump_fn = dumps else: from zmq_ops import dump_arrays dump_fn = dump_arrays ctx = zmq.Context() socket = ctx.socket(zmq.PUSH) socket.set_hwm(hwm) if bind: socket.bind(addr) else: soc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True): """ Aligned version of tf.image.crop_and_resize, following our definition of floating poi...
assert isinstance(crop_size, int), crop_size boxes = tf.stop_gradient(boxes) # TF's crop_and_resize produces zeros on border if pad_border: # this can be quite slow image = tf.pad(image, [[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC') boxes = boxes + 1 @under_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 narrow_to(self, featuremap): """ Slice anchors to the spatial size of this featuremap. """
shape2d = tf.shape(featuremap)[2:] # h,w slice3d = tf.concat([shape2d, [-1]], axis=0) slice4d = tf.concat([shape2d, [-1, -1]], axis=0) boxes = tf.slice(self.boxes, [0, 0, 0, 0], slice4d) gt_labels = tf.slice(self.gt_labels, [0, 0, 0], slice3d) gt_boxes = tf.slice(self.g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_arg(**maps): """ Apply a mapping on certain argument before calling the original function. Args: maps (dict): {argument_name: map_func} """
def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): if six.PY2: argmap = inspect.getcallargs(func, *args, **kwargs) else: # getcallargs was deprecated since 3.5 sig = inspect.signature(func) arg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_memoized(func): """ Like memoized, but keep one cache per default graph. """
# TODO it keeps the graph alive from ..compat import tfv1 GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__' @memoized def func_with_graph_arg(*args, **kwargs): kwargs.pop(GRAPH_ARG_NAME) return func(*args, **kwargs) @functools.wraps(func) def wrapper(*args, **kwargs): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memoized_ignoreargs(func): """ A decorator. It performs memoization ignoring the arguments used to call the function. """
def wrapper(*args, **kwargs): if func not in _MEMOIZED_NOARGS: res = func(*args, **kwargs) _MEMOIZED_NOARGS[func] = res return res return _MEMOIZED_NOARGS[func] return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shape2d(a): """ Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``. """
if type(a) == int: return [a, a] if isinstance(a, (list, tuple)): assert len(a) == 2 return list(a) raise RuntimeError("Illegal shape: {}".format(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 shape4d(a, data_format='NHWC'): """ Ensuer a 4D shape, to use with 4D symbolic functions. Args: a: a int or tuple/list of length 2 Returns: list: of length 4...
s2d = shape2d(a) if get_data_format(data_format, False) == 'NHWC': return [1] + s2d + [1] else: return [1, 1] + s2d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_only_once(func): """ Decorate a method or property of a class, so that this method can only be called once for every instance. Calling it more than once...
@functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] # cannot use hasattr here, because hasattr tries to getattr, which # fails if func is a property assert func.__name__ in dir(self), "call_only_once can only be used on method or property!" if not hasatt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memoized_method(func): """ A decorator that performs memoization on methods. It stores the cache on the object instance itself. """
@functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] assert func.__name__ in dir(self), "memoized_method can only be used on method!" if not hasattr(self, '_MEMOIZED_CACHE'): cache = self._MEMOIZED_CACHE = {} else: cache = self._MEMOIZED_...
<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_reuse_variable_scope(func): """ A decorator which automatically reuses the current variable scope if the function has been called with the same variable...
used_scope = set() @functools.wraps(func) def wrapper(*args, **kwargs): scope = tf.get_variable_scope() h = hash((tf.get_default_graph(), scope.name)) # print("Entering " + scope.name + " reuse: " + str(h in used_scope)) if h in used_scope: if get_tf_version_tup...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cached_name_scope(name, top_level=True): """ Return a context which either opens and caches a new name scope, or reenter an existing one. Args: top_level(boo...
if not top_level: current_ns = tf.get_default_graph().get_name_scope() if current_ns: name = current_ns + '/' + name ns = _get_cached_ns(name) with tf.name_scope(ns): yield ns
<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_post_init_ops(): """ Copy values of variables on GPU 0 to other GPUs. """
# literally all variables, because it's better to sync optimizer-internal variables as well all_vars = tf.global_variables() + tf.local_variables() var_by_name = dict([(v.name, v) for v in all_vars]) trainable_names = set([x.name for x in tf.trainable_variables()]) post_init_ops...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def humanize_time_delta(sec): """Humanize timedelta given in seconds Args: sec (float): time difference in seconds. Must be positive. Returns: str - time differ...
if sec < 0: logger.warn("humanize_time_delta() obtains negative seconds!") return "{:.3g} seconds".format(sec) if sec == 0: return "0 second" time = datetime(2000, 1, 1) + timedelta(seconds=int(sec)) units = ['day', 'hour', 'minute', 'second'] vals = [int(sec // 86400), 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 get_rng(obj=None): """ Get a good RNG seeded with time, pid and the object. Args: obj: some object to use to generate random seed. Returns: np.random.RandomS...
seed = (id(obj) + os.getpid() + int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 4294967295 if _RNG_SEED is not None: seed = _RNG_SEED return np.random.RandomState(seed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_only_once(): """ Each called in the code to this function is guaranteed to return True the first time and False afterwards. Returns: bool: whether th...
f = inspect.currentframe().f_back ident = (f.f_code.co_filename, f.f_lineno) if ident in _EXECUTE_HISTORY: return False _EXECUTE_HISTORY.add(ident) 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 get_tqdm_kwargs(**kwargs): """ Return default arguments to be used with tqdm. Args: kwargs: extra arguments to be used. Returns: dict: """
default = dict( smoothing=0.5, dynamic_ncols=True, ascii=True, bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]' ) try: # Use this env var to override the refresh interval setting interval = float(os.environ['TENSORPACK_PR...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_library_full_path(name): """ Similar to `from ctypes.util import find_library`, but try to return full path if possible. """
from ctypes.util import find_library if os.name == "posix" and sys.platform == "darwin": # on Mac, ctypes already returns full path return find_library(name) def _use_proc_maps(name): """ Find so from /proc/pid/maps Only works with libraries that has already been 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 get_dorefa(bitW, bitA, bitG): """ Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively """
def quantize(x, k): n = float(2 ** k - 1) @tf.custom_gradient def _quantize(x): return tf.round(x * n) / n, lambda dy: dy return _quantize(x) def fw(x): if bitW == 32: return x if bitW == 1: # BWN E = tf.stop_gradient(tf....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_text(img, pos, text, color, font_scale=0.4): """ Draw text on an image. Args: pos (tuple): x, y; the position of the text text (str): font_scale (floa...
img = img.astype(np.uint8) x0, y0 = int(pos[0]), int(pos[1]) # Compute text size. font = cv2.FONT_HERSHEY_SIMPLEX ((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, 1) # Place text background. if x0 + text_w > img.shape[1]: x0 = img.shape[1] - text_w if y0 - int(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 segmentation_to_mask(polys, height, width): """ Convert polygons to binary masks. Args: polys: a list of nx2 float array. Each array contains many (x, y) coo...
polys = [p.flatten().tolist() for p in polys] assert len(polys) > 0, "Polygons are empty!" import pycocotools.mask as cocomask rles = cocomask.frPyObjects(polys, height, width) rle = cocomask.merge(rles) return cocomask.decode(rle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def MaxPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.MaxPooling2D`. Default strides is equal to...
if strides is None: strides = pool_size layer = tf.layers.MaxPooling2D(pool_size, strides, padding=padding, data_format=data_format) ret = layer.apply(inputs, scope=tf.get_variable_scope()) return tf.identity(ret, name='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 AvgPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.AveragePooling2D`. Default strides is equa...
if strides is None: strides = pool_size layer = tf.layers.AveragePooling2D(pool_size, strides, padding=padding, data_format=data_format) ret = layer.apply(inputs, scope=tf.get_variable_scope()) return tf.identity(ret, name='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 FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'): """ Unpool the input with a fixed matrix to perform kronecker product with. Args: x (...
data_format = get_data_format(data_format, keras_mode=False) shape = shape2d(shape) output_shape = StaticDynamicShape(x) output_shape.apply(1 if data_format == 'NHWC' else 2, lambda x: x * shape[0]) output_shape.apply(2 if data_format == 'NHWC' else 3, lambda x: x * shape[1]) # a faster imple...
<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_chkpt_vars(dic, path): """ Save variables in dic to path. Args: dic: {name: value} path: save as npz if the name ends with '.npz', otherwise save as a c...
logger.info("Variables to save to {}:".format(path)) keys = sorted(list(dic.keys())) logger.info(pprint.pformat(keys)) assert not path.endswith('.npy') if path.endswith('.npz'): np.savez_compressed(path, **dic) else: with tf.Graph().as_default(), \ tf.Session() ...
<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_checkpoint_path(model_path): """ Work around TF problems in checkpoint path handling. Args: model_path: a user-input path Returns: str: the argument that...
if os.path.basename(model_path) == model_path: model_path = os.path.join('.', model_path) # avoid #4921 and #6142 if os.path.basename(model_path) == 'checkpoint': assert tfv1.gfile.Exists(model_path), model_path model_path = tf.train.latest_checkpoint(os.path.dirname(model_path)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_chkpt_vars(model_path): """ Load all variables from a checkpoint to a dict. Args: model_path(str): path to a checkpoint. Returns: dict: a name:value di...
model_path = get_checkpoint_path(model_path) reader = tfv1.train.NewCheckpointReader(model_path) var_names = reader.get_variable_to_shape_map().keys() result = {} for n in var_names: result[n] = reader.get_tensor(n) 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 put_summary(self, summary): """ Put a `tf.Summary`. """
if isinstance(summary, six.binary_type): summary = tf.Summary.FromString(summary) assert isinstance(summary, tf.Summary), type(summary) # TODO other types for val in summary.value: if val.WhichOneof('value') == 'simple_value': val.tag = re.sub('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 put_scalar(self, name, val): """ Put a scalar. """
if isinstance(val, np.floating): val = float(val) if isinstance(val, np.integer): val = int(val) self._dispatch(lambda m: m.process_scalar(name, val)) s = create_scalar_summary(name, val) self._dispatch(lambda m: m.process_summary(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 put_image(self, name, val): """ Put an image. Args: name (str): val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images in range [0,255]. If chan...
assert isinstance(val, np.ndarray) arr = image_to_nhwc(val) self._dispatch(lambda m: m.process_image(name, arr)) s = create_image_summary(name, arr) self._dispatch(lambda m: m.process_summary(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 _trigger(self): """ Add stats to json and dump to disk. Note that this method is idempotent. """
if len(self._stat_now): self._stat_now['epoch_num'] = self.epoch_num self._stat_now['global_step'] = self.global_step self._stats.append(self._stat_now) self._stat_now = {} self._write_stat()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_call_trace(): """ Enable trace for calls to any function. """
def tracer(frame, event, arg): if event == 'call': co = frame.f_code func_name = co.co_name if func_name == 'write' or func_name == 'print': # ignore write() calls from print statements return func_line_no = frame.f_lineno ...
<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_property(name): """ Delegate property to self.loop """
ret = property( lambda self: getattr(self.loop, name)) if six.PY3: # __doc__ is readonly in Py2 try: ret.__doc__ = getattr(TrainLoop, name).__doc__ except AttributeError: pass return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config(self, steps_per_epoch, starting_epoch, max_epoch): """ Configure the loop given the settings. """
self.starting_epoch = int(starting_epoch) self.max_epoch = int(max_epoch) self.steps_per_epoch = int(steps_per_epoch) # Allow empty epoch (no steps), if we want to run the callbacks only. assert self.steps_per_epoch >= 0 and self.max_epoch >= 0 self._epoch_num = startin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_callbacks(self, callbacks, monitors): """ Setup callbacks and monitors. Must be called after the main graph is built. Args: callbacks ([Callback]): mo...
assert isinstance(callbacks, list), callbacks assert isinstance(monitors, list), monitors describe_trainable_vars() # TODO weird self.register_callback(MaintainStepCounter()) for cb in callbacks: self.register_callback(cb) for cb in self._callbacks: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_hooks(self): """ Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`. A new trainer may override t...
hooks = self._callbacks.get_hooks() self.hooked_sess = tfv1.train.MonitoredSession( session_creator=ReuseSessionCreator(self.sess), hooks=hooks)
<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_default_sess_config(mem_fraction=0.99): """ Return a tf.ConfigProto to use as default session config. You can modify the returned config to fit your need...
conf = tfv1.ConfigProto() conf.allow_soft_placement = True # conf.log_device_placement = True conf.intra_op_parallelism_threads = 1 conf.inter_op_parallelism_threads = 0 # TF benchmark use cpu_count() - gpu_thread_count(), e.g. 80 - 8 * 2 # Didn't see much difference. conf.gpu_option...
<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_tensors_by_names(names): """ Get a list of tensors in the default graph by a list of names. Args: names (list): """
ret = [] G = tfv1.get_default_graph() for n in names: opn, varn = get_op_tensor_name(n) ret.append(G.get_tensor_by_name(varn)) return ret
<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_op_or_tensor_by_name(name): """ Get either tf.Operation of tf.Tensor from names. Args: name (list[str] or str): names of operations or tensors. Raises: ...
G = tfv1.get_default_graph() def f(n): if len(n) >= 3 and n[-2] == ':': return G.get_tensor_by_name(n) else: return G.get_operation_by_name(n) if not isinstance(name, list): return f(name) else: return list(map(f, 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 _add_sync_queues_and_barrier(self, name, dependencies): """Adds ops to enqueue on all worker queues. Args: name: prefixed for the shared_name of ops. depende...
self._sync_queue_counter += 1 with tf.device(self.sync_queue_devices[self._sync_queue_counter % len(self.sync_queue_devices)]): sync_queues = [ tf.FIFOQueue(self.num_worker, [tf.bool], shapes=[[]], shared_name='%s%s' % (name, 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 _apply_shadow_vars(avg_grads): """ Create shadow variables on PS, and replace variables in avg_grads by these shadow variables. Args: avg_grads: list of (gra...
ps_var_grads = [] for grad, var in avg_grads: assert var.name.startswith('tower'), var.name my_name = '/'.join(var.name.split('/')[1:]) my_name = get_op_tensor_name(my_name)[0] new_v = tf.get_variable(my_name, dtype=var.dtype.base_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 _shadow_model_variables(shadow_vars): """ Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``. Returns: list of (shadow_mo...
G = tf.get_default_graph() curr_shadow_vars = set([v.name for v in shadow_vars]) model_vars = tf.model_variables() shadow_model_vars = [] for v in model_vars: assert v.name.startswith('tower'), "Found some MODEL_VARIABLES created outside of the tower function!" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads): """ Apply averaged gradients to ps vars, and then copy the updated variables back to each ...
# TODO do this for variables together? with tf.name_scope('apply_gradients'): var_update_ops = [] for vid, (g, v) in enumerate(ps_var_grads): # TODO do we put momentum variables into local or global? apply_gradient_op = opt.apply_gradients([(g, v)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_initial_sync_op(self): """ Get the op to copy-initialized all local variables from PS. """
def strip_port(s): if s.endswith(':0'): return s[:-2] return s local_vars = tf.local_variables() local_var_by_name = dict([(strip_port(v.name), v) for v in local_vars]) ops = [] nr_shadow_vars = len(self._shadow_vars) for v in 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 _get_sync_model_vars_op(self): """ Get the op to sync local model_variables to PS. """
ops = [] for (shadow_v, local_v) in self._shadow_model_vars: ops.append(shadow_v.assign(local_v.read_value())) assert len(ops) return tf.group(*ops, name='sync_{}_model_variables_to_ps'.format(len(ops)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def MergeAllSummaries(period=0, run_alone=False, key=None): """ This callback is enabled by default. Evaluate all summaries by ``tf.summary.merge_all``, and writ...
if key is None: key = tf.GraphKeys.SUMMARIES period = int(period) if run_alone: return MergeAllSummaries_RunAlone(period, key) else: return MergeAllSummaries_RunWithOp(period, 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 step(self, exploration): """ Run the environment for one step. If the episode ends, store the entire episode to the replay memory. """
old_s = self._current_ob if self.rng.rand() <= exploration: act = self.rng.choice(range(self.num_actions)) else: history = self.recent_state() history.append(old_s) history = np.stack(history, axis=-1) # state_shape + (Hist,) # assum...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def step(self, exploration): """ Execute one step in any of the runners. """
if len(self._runners) > 1: self._populate_job_queue.put(exploration) else: self._runners[0].step(exploration)
<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(self): """ log the time of some heavy callbacks """
if self.tot < 3: return msgs = [] for name, t in self.times: if t / self.tot > 0.3 and t > 1: msgs.append(name + ": " + humanize_time_delta(t)) logger.info( "Callbacks took {:.3f} sec in total. {}".format( self.tot, '; ...
<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_variable(self, name): """ Get a variable used in this tower. The name should not contain the variable scope prefix of the tower. When the tower has the s...
name = get_op_tensor_name(name)[1] if len(self.vs_name): name_with_vs = self.vs_name + "/" + name else: name_with_vs = name return get_op_or_tensor_by_name(name_with_vs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkdir_p(dirname): """ Like "mkdir -p", make a dir recursively, but do nothing if the dir exists Args: dirname(str): """
assert dirname is not None if dirname == '' or os.path.isdir(dirname): return try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(url, dir, filename=None, expect_size=None): """ Download URL to a directory. Will figure out the filename automatically from URL, if not given. """
mkdir_p(dir) if filename is None: filename = url.split('/')[-1] fpath = os.path.join(dir, filename) if os.path.isfile(fpath): if expect_size is not None and os.stat(fpath).st_size == expect_size: logger.info("File {} exists! Skip download.".format(filename)) ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_collection(backup): """ Restore from a collection backup. Args: backup (dict): """
for k, v in six.iteritems(backup): del tf.get_collection_ref(k)[:] tf.get_collection_ref(k).extend(v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_collection_in_tower(self, key): """ Get items from this collection that are added in the current tower. """
new = tf.get_collection(key) old = set(self.original.get(key, [])) # persist the order in new return [x for x in new if x not in old]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ptb_producer(raw_data, batch_size, num_steps, name=None): """Iterate on the raw PTB data. This chunks up raw_data into batches of examples and returns Tensor...
with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]): raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32) data_len = tf.size(raw_data) batch_len = data_len // batch_size data = tf.reshape(raw_data[0 : batch_size * batch_len], [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 CaffeBilinearUpSample(x, shape): """ Deterministic bilinearly-upsample the input images. It is implemented by deconvolution with "BilinearFiller" in Caffe. I...
inp_shape = x.shape.as_list() ch = inp_shape[1] assert ch == 1, "This layer only works for channel=1" # for a version that supports >1 channels, see: # https://github.com/tensorpack/tensorpack/issues/1040#issuecomment-452798180 shape = int(shape) filter_shape = 2 * shape def bilinear_...
<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_compatible_with(self, spec_or_tensor): """Returns True if spec_or_tensor is compatible with this TensorSpec. Two tensors are considered compatible if they...
return (self._dtype.is_compatible_with(spec_or_tensor.dtype) and self._shape.is_compatible_with(spec_or_tensor.shape))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_trainable_vars(): """ Print a description of the current model parameters. Skip variables starting with "tower", as they are just duplicates built b...
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) if len(train_vars) == 0: logger.warn("No trainable variables in the graph!") return total = 0 total_bytes = 0 data = [] for v in train_vars: if v.name.startswith('tower'): continue shape...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def embed(self, x, nfeatures=2): """Embed all given tensors into an nfeatures-dim space. """
list_split = 0 if isinstance(x, list): list_split = len(x) x = tf.concat(x, 0) # pre-process MNIST dataflow data x = tf.expand_dims(x, 3) x = x * 2 - 1 # the embedding network net = slim.layers.conv2d(x, 20, 5, scope='conv1') net...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allreduce_grads(all_grads, average): """ All-reduce average the gradients among K devices. Results are broadcasted to all devices. Args: all_grads (K x N): ...
if get_tf_version_tuple() <= (1, 12): from tensorflow.contrib import nccl else: from tensorflow.python.ops import nccl_ops as nccl nr_tower = len(all_grads) if nr_tower == 1: return all_grads new_all_grads = [] # N x K for grads in zip(*all_grads): summed = ncc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allreduce_grads_hierarchical(all_grads, devices, average=False): """ Hierarchical allreduce for DGX-1 system. Args: all_grads (K x N): List of list of gradi...
num_gpu = len(devices) assert num_gpu == 8, num_gpu assert len(all_grads) == num_gpu, len(all_grads) group_size = num_gpu // 2 agg_all_grads = [] # N x K for varid, grads in enumerate(zip(*all_grads)): # grads: K gradients g0_main_gpu = varid % num_gpu g1_main_gpu = (g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregate_grads(all_grads, colocation=False, devices=None, average=True): """ Average the gradients. Args: all_grads (K x N x 2): A list of K lists. Each of...
assert not (devices is not None and colocation) if devices is not None: assert isinstance(devices, list), devices nr_tower = len(all_grads) if nr_tower == 1: return all_grads[0] def aggregate(grads): if average: return tf.multiply(tf.add_n(grads), 1.0 / nr_towe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fpn_map_rois_to_levels(boxes): """ Assign boxes to level 2~5. Args: boxes (nx4): Returns: [tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of i...
sqrtarea = tf.sqrt(tf_area(boxes)) level = tf.cast(tf.floor( 4 + tf.log(sqrtarea * (1. / 224) + 1e-6) * (1.0 / np.log(2))), tf.int32) # RoI levels range from 2~5 (not 6) level_ids = [ tf.where(level <= 2), tf.where(tf.equal(level, 3)), # == is not supported tf.where(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 proposal_metrics(iou): """ Add summaries for RPN proposals. Args: iou: nxm, #proposal x #gt """
# find best roi for each gt, for summary only best_iou = tf.reduce_max(iou, axis=0) mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt') summaries = [mean_best_iou] with tf.device('/cpu:0'): for th in [0.3, 0.5]: recall = tf.truediv( tf.count_nonzero(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fastrcnn_predictions(boxes, scores): """ Generate final results from predictions of all proposals. Args: boxes: n#classx4 floatbox in float32 scores: nx#clas...
assert boxes.shape[1] == cfg.DATA.NUM_CLASS assert scores.shape[1] == cfg.DATA.NUM_CLASS boxes = tf.transpose(boxes, [1, 0, 2])[1:, :, :] # #catxnx4 scores = tf.transpose(scores[:, 1:], [1, 0]) # #catxn def f(X): """ prob: n probabilities box: nx4 boxes Returns: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _on_state(self, state, client): """ Launch forward prediction for the new state given by some client. """
def cb(outputs): try: distrib, value = outputs.result() except CancelledError: logger.info("Client {} cancelled.".format(client.ident)) return assert np.all(np.isfinite(distrib)), distrib action = np.random.choice(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 _process_msg(self, client, state, reward, isOver): """ Process a message sent from some client. """
# in the first message, only state is valid, # reward&isOver should be discarded if len(client.memory) > 0: client.memory[-1].reward = reward if isOver: # should clear client's memory and put to queue self._parse_memory(0, client, 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 export_serving(self, filename, tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING], signature_name='prediction_pipeline'): "...
self.graph = self.config._maybe_create_graph() with self.graph.as_default(): input = PlaceholderInput() input.setup(self.config.input_signature) with PredictTowerContext(''): self.config.tower_func(*input.get_input_tensors()) input_tenso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_logger(name): """This logs the time usage of a code block"""
start_time = time.time() yield end_time = time.time() total_time = end_time - start_time logging.info("%s; time: %ss", name, total_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 initialize_ray(): """Initializes ray based on environment variables and internal defaults."""
if threading.current_thread().name == "MainThread": plasma_directory = None object_store_memory = os.environ.get("MODIN_MEMORY", None) if os.environ.get("MODIN_OUT_OF_CORE", "False").title() == "True": from tempfile import gettempdir plasma_directory = gettempdir() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply( self, func, num_splits=None, other_axis_partition=None, maintain_partitioning=True, **kwargs ): """Applies func to the object. See notes in Parent cla...
import dask if num_splits is None: num_splits = len(self.list_of_blocks) if other_axis_partition is not None: return [ DaskFramePartition(dask.delayed(obj)) for obj in deploy_func_between_two_axis_partitions( self.axi...
<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_dummies( data, prefix=None, prefix_sep="_", dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None, ): """Convert categorical variable ...
if sparse: raise NotImplementedError( "SparseDataFrame is not implemented. " "To contribute to Modin, please visit " "github.com/modin-project/modin." ) if not isinstance(data, DataFrame): ErrorMessage.default_to_pandas("`get_dummies` on non-DataFrame...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shuffle(self, func, lengths, **kwargs): """Shuffle the order of the data in this axis based on the `lengths`. Extends `BaseFrameAxisPartition.shuffle`. Args:...
num_splits = len(lengths) # We add these to kwargs and will pop them off before performing the operation. kwargs["manual_partition"] = True kwargs["_lengths"] = lengths args = [self.axis, func, num_splits, kwargs, False] args.extend(self.list_of_blocks) return se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shuffle(self, func, num_splits=None, **kwargs): """Shuffle the order of the data in this axis based on the `func`. Extends `BaseFrameAxisPartition.shuffle`. ...
if num_splits is None: num_splits = len(self.list_of_blocks) args = [self.axis, func, num_splits, kwargs] args.extend(self.list_of_blocks) return [ PyarrowOnRayFramePartition(obj) for obj in deploy_ray_axis_func._remote(args, num_return_vals=num_spli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, func, **kwargs): """Apply a function to the object stored in this partition. Note: It does not matter if func is callable or an ObjectID. Ray wil...
oid = self.oid self.call_queue.append((func, kwargs)) def call_queue_closure(oid_obj, call_queues): for func, kwargs in call_queues: if isinstance(func, ray.ObjectID): func = ray.get(func) if isinstance(kwargs, ray.ObjectID): ...
<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_pandas(self): """Convert the object stored in this partition to a Pandas DataFrame. Returns: A Pandas DataFrame. """
dataframe = self.get().to_pandas() assert type(dataframe) is pandas.DataFrame or type(dataframe) is pandas.Series return dataframe
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(cls, obj): """Put an object in the Plasma store and wrap it in this object. Args: obj: The object to be put. Returns: A `RayRemotePartition` object. """
return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(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 merge( left, right, how="inner", on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=("_x", "_y"), copy=True, indi...
if not isinstance(left, DataFrame): raise ValueError( "can not merge DataFrame with instance of type {}".format(type(right)) ) return left.merge( right, how=how, on=on, left_on=left_on, right_on=right_on, left_index=left_index, ...
<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_distributed(partition_column, lower_bound, upper_bound): """ Check if is possible distribute a query given that args Args: partition_column: column used t...
if ( (partition_column is not None) and (lower_bound is not None) and (upper_bound is not None) ): if upper_bound > lower_bound: return True else: raise InvalidArguments("upper_bound must be greater than lower_bound.") elif (partition_column 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 is_table(engine, sql): """ Check with the given sql arg is query or table Args: engine: SQLAlchemy connection engine sql: SQL query or table name Returns: Tr...
if engine.dialect.has_table(engine, sql): 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 get_table_metadata(engine, table): """ Extract all useful infos from the given table Args: engine: SQLAlchemy connection engine table: table name Returns: Di...
metadata = MetaData() metadata.reflect(bind=engine, only=[table]) table_metadata = Table(table, metadata, autoload=True) return table_metadata
<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_table_columns(metadata): """ Extract columns names and python typos from metadata Args: metadata: Table metadata Returns: dict with columns names and pyt...
cols = OrderedDict() for col in metadata.c: name = str(col).rpartition(".")[2] cols[name] = col.type.python_type.__name__ return cols
<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_query(query): """ Check query sanity Args: query: query string Returns: None """
q = query.lower() if "select " not in q: raise InvalidQuery("SELECT word not found in the query: {0}".format(query)) if " from " not in q: raise InvalidQuery("FROM word not found in the query: {0}".format(query))
<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_query_columns(engine, query): """ Extract columns names and python typos from query Args: engine: SQLAlchemy connection engine query: SQL query Returns: ...
con = engine.connect() result = con.execute(query).fetchone() values = list(result) cols_names = result.keys() cols = OrderedDict() for i in range(len(cols_names)): cols[cols_names[i]] = type(values[i]).__name__ return cols
<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_partition_column(partition_column, cols): """ Check partition_column existence and type Args: partition_column: partition_column name cols: dict with c...
for k, v in cols.items(): if k == partition_column: if v == "int": return else: raise InvalidPartitionColumn( "partition_column must be int, and not {0}".format(v) ) raise InvalidPartitionColumn( "partit...
<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_query_info(sql, con, partition_column): """ Return a columns name list and the query string Args: sql: SQL query or table name con: database connection o...
engine = create_engine(con) if is_table(engine, sql): table_metadata = get_table_metadata(engine, sql) query = build_query_from_table(sql) cols = get_table_columns(table_metadata) else: check_query(sql) query = sql.replace(";", "") cols = get_query_columns(en...
<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_put_bounders(query, partition_column, start, end): """ Put bounders in the query Args: query: SQL query string partition_column: partition_column name ...
where = " WHERE TMP_TABLE.{0} >= {1} AND TMP_TABLE.{0} <= {2}".format( partition_column, start, end ) query_with_bounders = "SELECT * FROM ({0}) AS TMP_TABLE {1}".format(query, where) return query_with_bounders
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_index(self, axis, data_object, compute_diff=True): """Computes the index after a number of rows have been removed. Note: In order for this to be used...
def pandas_index_extraction(df, axis): if not axis: return df.index else: try: return df.columns except AttributeError: return pandas.Index([]) index_obj = self.index if not axis else 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 numeric_columns(self, include_bool=True): """Returns the numeric columns of the Manager. Returns: List of index names. """
columns = [] for col, dtype in zip(self.columns, self.dtypes): if is_numeric_dtype(dtype) and ( include_bool or (not include_bool and dtype != np.bool_) ): columns.append(col) return columns
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def numeric_function_clean_dataframe(self, axis): """Preprocesses numeric functions to clean dataframe and pick numeric indices. Args: axis: '0' if columns and '...
result = None query_compiler = self # If no numeric columns and over columns, then return empty Series if not axis and len(self.index) == 0: result = pandas.Series(dtype=np.int64) nonnumeric = [ col for col, dtype in zip(self.columns, self.dt...
<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, other, **kwargs): """Joins a list or two objects together. Args: other: The other object(s) to join on. Returns: Joined objects. """
if not isinstance(other, list): other = [other] return self._join_list_of_managers(other, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concat(self, axis, other, **kwargs): """Concatenates two objects together. Args: axis: The axis index object to join (0 for columns, 1 for index). other: The...
return self._append_list_of_managers(other, axis, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copartition(self, axis, other, how_to_join, sort, force_repartition=False): """Copartition two QueryCompiler objects. Args: axis: The axis to copartition alo...
if isinstance(other, type(self)): other = [other] index_obj = ( [o.index for o in other] if axis == 0 else [o.columns for o in other] ) joined_index = self._join_index_objects( axis ^ 1, index_obj, how_to_join, sort=sort ) # We have 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 to_pandas(self): """Converts Modin DataFrame to Pandas DataFrame. Returns: Pandas DataFrame of the DataManager. """
df = self.data.to_pandas(is_transposed=self._is_transposed) if df.empty: if len(self.columns) != 0: df = pandas.DataFrame(columns=self.columns).astype(self.dtypes) else: df = pandas.DataFrame(columns=self.columns, index=self.index) 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 from_pandas(cls, df, block_partitions_cls): """Improve simple Pandas DataFrame to an advanced and superior Modin DataFrame. Args: cls: DataManger object to c...
new_index = df.index new_columns = df.columns new_dtypes = df.dtypes new_data = block_partitions_cls.from_pandas(df) return cls(new_data, new_index, new_columns, dtypes=new_dtypes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _inter_df_op_handler(self, func, other, **kwargs): """Helper method for inter-manager and scalar operations. Args: func: The function to use on the Manager/s...
axis = kwargs.get("axis", 0) axis = pandas.DataFrame()._get_axis_number(axis) if axis is not None else 0 if isinstance(other, type(self)): return self._inter_manager_operations( other, "outer", lambda x, y: func(x, y, **kwargs) ) 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 binary_op(self, op, other, **kwargs): """Perform an operation between two objects. Note: The list of operations is as follows: - add - eq - floordiv - ge - g...
func = getattr(pandas.DataFrame, op) return self._inter_df_op_handler(func, other, **kwargs)
<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(self, other, **kwargs): """Uses other manager to update corresponding values in this manager. Args: other: The other manager. Returns: New DataManager...
assert isinstance( other, type(self) ), "Must have the same DataManager subclass to perform this operation" def update_builder(df, other, **kwargs): # This is because of a requirement in Arrow df = df.copy() df.update(other, **kwargs) ...