query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be.
def find_files(suffix, path): # Recursion result = [] if not bool(path): return [] if not bool(suffix): suffix = None if os.path.isdir(path): # if the current path is a file if path.endswith(suffix): # if the file has extension suffix='.c' result.append(path) else: children = os.lis...
[ "def find_files(suffix, path):\n\n if os.path.isfile(path): # edge case, when suppied path is a file by itself -- added as per suggestion in code review\n if path.endswith(suffix):\n return [path]\n\n path_list = []\n for file_name in os.listdir(path):\n file_path = os.path.join(pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set all weights and biases to a value between [range/2 and range/2]
def randomize_weights_and_biases(self, value_range = 1): self.weights = np.array(np.random.uniform(-value_range/2, value_range/2, self.weights.shape)) self.bias_visible = np.array(np.random.uniform(-value_range/2, value_range/2, self.bias_visible.shape)) self.bias_hidden = np.array(np.random.unifor...
[ "def default_weight_initializer(self):\n self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]\n self.weights = [np.random.randn(y, x)/np.sqrt(x)\n for x, y in zip(self.sizes[:-1], self.sizes[1:])]", "def init_weights(self):\r\n default_init_weights(self, 1)", "def init_w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns B_H, given the prior visible and hidden terms Assume visibles[0] = V{t1}, visibles[1] = V{t2}, etc. Similar for hiddens
def get_bias_hidden(self, visibles, hiddens): B_H = np.zeros((self.num_hidden,1)) + self.bias_hidden for n in range(self.num_delays): B_H = B_H + np.dot(self.B[n].transpose(), hiddens[n]) B_H = B_H + np.dot(self.C[n].transpose(), visibles[n]) return B_H
[ "def get_probability_hidden(self, visibles, hiddens):\n\n # H = sigmoid(W'V_t + B_H(V_{t-m...t-1}, H{t-m...t-1}))\n B_H = self.get_bias_hidden(visibles[1:], hiddens)\n return sigmoid(np.dot(self.weights.transpose(), visibles[0]) + B_H)", "def get_probability_visible(self, visibles, hidden):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns B_V, given the prior visible terms Assume visibles[0] = V{t1}, visibles[1] = V{t2}, etc...
def get_bias_visible(self, visibles): B_V = np.zeros((self.num_visible,1)) + self.bias_visible for n in range(self.num_delays): B_V = B_V + np.dot(self.A[n].transpose(), visibles[n]) return B_V
[ "def render_visible2(V):\n\n # make V into listed sorted by slope: O(n)\n V = sorted(V, key=lambda l: l.m)\n X = visible_intersections(V)\n\n x = sym.Symbol(\"x\")\n piecewise = [ (V[i].m*x + V[i].b, x < X[i]) for i in range(len(X))]\n piecewise.append( (V[-1].m*x + V[-1].b, True) )\n return pi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the probability of setting hidden units to 1, given the history of hidden and visible units. Assumes visibles[0] = V{t}, visibles[1] = V{t1}, ... and hiddens[0] = H{t1}, hiddens[1] = H{t2}, ... visibles should have one extra entry than hiddens
def get_probability_hidden(self, visibles, hiddens): # H = sigmoid(W'V_t + B_H(V_{t-m...t-1}, H{t-m...t-1})) B_H = self.get_bias_hidden(visibles[1:], hiddens) return sigmoid(np.dot(self.weights.transpose(), visibles[0]) + B_H)
[ "def get_probability_visible(self, visibles, hidden):\n\n B_V = self.get_bias_visible(visibles)\n return sigmoid(np.dot(self.weights, hidden) + B_V)", "def sample_hidden(self, visibles, hiddens):\n\n P_hidden = self.get_probability_hidden(visibles, hiddens)\n\n h_sample = [1.0 if random.random...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the probability of setting visible units to 1, given the the hidden units and history of visible units. Assume visibles[0] = V{t1}, visibles[1] = V{t2}, etc. Then hiddens = H{t}
def get_probability_visible(self, visibles, hidden): B_V = self.get_bias_visible(visibles) return sigmoid(np.dot(self.weights, hidden) + B_V)
[ "def get_probability_hidden(self, visibles, hiddens):\n\n # H = sigmoid(W'V_t + B_H(V_{t-m...t-1}, H{t-m...t-1}))\n B_H = self.get_bias_hidden(visibles[1:], hiddens)\n return sigmoid(np.dot(self.weights.transpose(), visibles[0]) + B_H)", "def sample_hidden(self, visibles, hiddens):\n\n P_hidde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a sample of the hidden layer given the visible layer.
def sample_hidden(self, visibles, hiddens): P_hidden = self.get_probability_hidden(visibles, hiddens) h_sample = [1.0 if random.random() < p else 0.0 for p in P_hidden] return np.array([h_sample]).transpose()
[ "def get_hidden(self, layer):", "def generateHiddenSamples(self, n=1e5):\n\n\t\thiddenSamples = numpy.zeros((int(n), self.h_units))# each row will be a sample from hidden units\n\t\tii = numpy.random.randint(low=0, high=self.data.shape[0]-1, size=n )\n\t\tvisible = self.data[ii,:]\n\t\thprob = sigmoid( numpy.dot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a list of buttons that the user can click to look at the schedule.
async def send_schedule_list_message( ctx: Union[GuildContext, discord.Interaction], *, message_text: str, custom_id_prefix: str): # Set up a translation table tra = vbu.translation(ctx, "main") # Work out what our interaction is interaction: discord.Interaction if ...
[ "def action_buttons(node: pipelines.Node):\n path = node.path()\n return [\n response.ActionButton(\n action=flask.url_for('mara_pipelines.run_page', path='/'.join(path[:-1]),\n with_upstreams=True, ids=path[-1]),\n label='Run with upstreams', icon=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Packs object init options as a dict, binding missing kwargs with defaults.
def _pack_init_args(obj: object, *args, **kwargs) -> dict[str, Any]: init_signature = signature(obj.__init__) # type: ignore bound_signature = init_signature.bind(*args, **kwargs) bound_signature.apply_defaults() bound_args = bound_signature.arguments # Note: type `OrderedDict` return dict(bound_a...
[ "def obj_with_no_args_to_init_dict(obj: Any) -> InitDict:\n\n return {ARGS_LABEL: [], KWARGS_LABEL: {}}", "def kwargs_to_initdict(kwargs: KwargsDict) -> InitDict:\n return {ARGS_LABEL: [], KWARGS_LABEL: kwargs}", "def __init__(self, initOpts=None, setupBox=None, setupAtoms=None,\n\t forceField...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Infer init namespace from a given class.
def _infer_init_namespace(cls: type) -> tuple[str, ...]: init_signature = signature(cls.__init__) # type: ignore namespace = tuple(init_signature.parameters.keys()) return namespace[1:] # Note: disregard `self`
[ "def _infer_settings_namespace(cls: type) -> tuple[str, ...]:\n if cls.__init__ is object.__init__: # type: ignore\n return () # Note: to avoid `*(*kw)args` from `object.__init__`\n init_namespace: tuple[str, ...] = _infer_init_namespace(cls)\n return tuple(name for name in init_namespace if not n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Infer strategy settings namespace from a given class.
def _infer_settings_namespace(cls: type) -> tuple[str, ...]: if cls.__init__ is object.__init__: # type: ignore return () # Note: to avoid `*(*kw)args` from `object.__init__` init_namespace: tuple[str, ...] = _infer_init_namespace(cls) return tuple(name for name in init_namespace if not name.start...
[ "def _get_settings_class():\n if not hasattr(django_settings, \"AUTH_ADFS\"):\n msg = \"The configuration directive 'AUTH_ADFS' was not found in your Django settings\"\n raise ImproperlyConfigured(msg)\n cls = django_settings.AUTH_ADFS.get('SETTINGS_CLASS', DEFAULT_SETTINGS_CLASS)\n return im...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve closest common ancestor class from the input classes' MROs.
def _closest_common_ancestor(*args) -> type: cls_list = map(lambda obj: obj if isinstance(obj, type) else type(obj), args) mros = [cls.mro() for cls in cls_list] base = min(mros, key=len) mros.remove(base) for cls in base: if all(cls in mro for mro in mros): return cls return...
[ "def merge_classes(self, t2):\n # find reps\n rep = self.get_representative()\n t2_rep = t2.get_representative()\n\n # update parents\n t1_parents = copy(rep.parents)\n rep.parents = set()\n t2_parents = copy(t2_rep.parents)\n t2_rep.parents = t1_parents.union...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return closest common strategy ancestor or None.
def _shared_strategy_ancestor(*strategies) -> type: shared: type = _closest_common_ancestor(*strategies) if shared in (None, *_BASE_STRATEGY_CLASSES) or not issubclass(shared, _BaseStrategy): return None return shared
[ "def _closest_common_ancestor(*args) -> type:\n cls_list = map(lambda obj: obj if isinstance(obj, type) else type(obj), args)\n mros = [cls.mro() for cls in cls_list]\n base = min(mros, key=len)\n mros.remove(base)\n for cls in base:\n if all(cls in mro for mro in mros):\n return cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A copy of original args.
def original_args(self) -> dict[str, Any]: original_args = getattr(self, "_original_args", {}) return deepcopy(original_args)
[ "def extra_args(self):\n return deepcopy(self._extra_args)", "def pass_args(input_args):\n\n global args\n args = input_args", "def copyInPlace(*args, **kwargs):\n \n pass", "def _sysargs_hacks():\n orig_sysargv = copy.copy(sys.argv)\n yield\n sys.argv = orig_sysargv", "def _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the strategy class is a facade subclass of the given ancestor.
def is_facade(cls, ancestor: Any) -> bool: if not isinstance(ancestor, type): ancestor = type(ancestor) if not (issubclass(cls, ancestor) and issubclass(ancestor, _BaseStrategy)): return False # Note: subclassing is transitive (A -> B -> C then A -> C) filtered_mro = lis...
[ "def inherits_from(obj, a_class):\n if type(obj) != a_class:\n if isinstance(obj, a_class):\n return True\n return False", "def inherits_from(obj, a_class):\n if isinstance(obj, a_class) and type(obj) is not a_class:\n\n return True\n else:\n return False", "def is_su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gradient check for a function f.
def gradcheck_naive(f, x): rndstate = random.getstate() random.setstate(rndstate) fx, grad = f(x) # Evaluate function value at original point h = 1e-4 # Do not change this! # Iterate over all indexes in x it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite']) while not it....
[ "def gradient_checker(self, f, w, min_diff=1e-5):\n random_state = np.random.get_state()\n np.random.set_state(random_state)\n loss, grad = f(w) # Evaluate function value at with some weights vector\n h = 1e-4 # a small value, epsilon\n\n # Iterate over all indexes ix in x to ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the size of a sub plotter in (total_y_pixels, total_x_pixels), based on the number of subplots that are going to be plotted.
def get_subplot_figsize(self, number_subplots): if self.subplot_figsize is not None: return self.subplot_figsize if self.mat_plot_1d is not None: if self.mat_plot_1d.figure.config_dict["figsize"] is not None: return self.mat_plot_1d.figure.config_dict["fi...
[ "def calc_subplots_size(nplots: int, ncols: int, sp_height: int) -> tuple:\n nrows = round(nplots / ncols)\n figsize = (ncols * sp_height, nrows * sp_height)\n return nrows, figsize", "def _ncols(self):\n return min(self.max_cols, self._nsubplots)", "def _get_plot_dimensions(self) -> Tuple[int, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return sqlalchemy.sql.text of insertion with checking foreignkeys constraint if foreignkey records do not exist, no record will be inserted. insert_with_check_foreignkey(DeviceBaseInfo.__table__, 'device_mac', 'id')
def insert_with_check_foreignkey(table, *fields): fkeys = [] for fkey in table.foreign_keys: if fkey.parent.name in fields: fkeys.append(fkey) sql = ["INSERT INTO %s " % table.name] sql.append("(" + ",".join(fields) + ") ") if fkeys: sql.append("SELECT " + ",".join(":%s A...
[ "def insert(self, sql):", "def _my_insert(target_table, temp_table, session, if_record_exists):\n temp_inspect = inspect(temp_table)\n\n # convey type to columns list\n column_list = [c for c in temp_inspect.columns]\n pk_list = [k for k in temp_inspect.primary_key]\n\n # get ri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a certain option, passes details to the required controller (FilenMenuController) for the selected option and suboption
def invokeFileController(self, option, subOption): if option == FileMenu.OPEN: self.imageArray, self.filename = FMC.openImage(subOption, self.winfo_screenwidth(), self.winfo_screenheight()) self.imageDimensions = (self.imageArray.shape[1], self.imageArray.shape[0]) self.updat...
[ "def _perform_action(self, option):\n if option == 1:\n self.current_user.view_budgets()\n elif option == 2:\n self.current_user.record_transaction()\n elif option == 3:\n self.current_user.view_transactions()\n elif option == 4:\n self.current...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a certain option, passes details to the required controller (AlgorithmController) for the selected option.
def invokeAlgorithm(self, option): if option == ALG.Algorithm.PIXELATE: self.imageArray, self.filename = AC.callPixelateAlgorithm(self.filename) elif option == ALG.Algorithm.PIXELATE_AND_SHRINK: self.imageArray, self.filename = AC.callPixelateAndShrinkAlgorithm(self.filename) ...
[ "def _perform_action(self, option):\n if option == 1:\n self.current_user.view_budgets()\n elif option == 2:\n self.current_user.record_transaction()\n elif option == 3:\n self.current_user.view_transactions()\n elif option == 4:\n self.current...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the image on the canvas and resizes it to fit the screen of the device being used.
def updateCanvas(self): image = Image.open(self.filename) self.canvasImage = ImageTk.PhotoImage(image) self.mainCanvas.create_image(0, 0, anchor="nw", image=self.canvasImage) self.mainCanvas.config(width=self.imageDimensions[0], height=self.imageDimensions[1]) print(Globals.pixel...
[ "def update_image(self):\n self.image = self.capture_image()\n self.update_background()", "def show_image(self):\n if self.image_id:\n self.canvas.delete(self.image_id)\n\n width, height = self.image.size\n cw = self.canvas.winfo_width()\n ch = self.canvas.winf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the "rdivision" modulo of x and y. Computes the real quotient of x and y (Qr), rounds it the closest integer (Qz), then computes the remainder as dividend divisor Qz.
def r_div_mod(x, y): return x-(round(float(x)/float(y))*y)
[ "def div_interval(x, y):\n assert (y != 0), \"Y cannot be 0!\"\n\n reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))\n return mul_interval(x, reciprocal_y)", "def div_interval(x, y):\n \"*** YOUR CODE HERE ***\"\n assert not (lower_bound(y) <= 0 and upper_bound(y) >= 0), \"Interval y cont...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up object recognition and load models
def _setup_object_recognition(self): logging.info('Loading ML models') self.daddy = Daddy() self.daddy.set_callbacks(self.object_detected, self.object_expired)
[ "def __init__(self, detection_model_path=PATH + \"people_emotions/people_emotions/gender_emotion_detector/trained model/haarcascade_frontalface_default.xml\",\n emotion_model_path=PATH + \"people_emotions/people_emotions/gender_emotion_detector/trained model/fer2013_mini_XCEPTION.102-0.66.hdf5\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the relay controller
def _setup_relay(self): self.rc = RelayController()
[ "def initControllerSetup(self):\r\n # Set the front motors to be the followers of the rear motors\r\n self.frontLeft.set(WPI_TalonSRX.ControlMode.Follower, DRIVETRAIN_REAR_LEFT_MOTOR)\r\n self.frontRight.set(WPI_TalonSRX.ControlMode.Follower, DRIVETRAIN_REAR_RIGHT_MOTOR)\r\n\r\n # Set th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback for an object being detected
def object_detected(self, detection): logging.info(f'{detection.label} detected') try: if detection.is_person(): self.activate_arm() except Exception: pass
[ "def train_simple_object_detector(*args, **kwargs): # real signature unknown; restored from __doc__\n pass", "def recognize(self, image, boxes):\r\n raise NotImplementedError", "def object_hook(self, object_dict):\n instance = self.decoder(object_dict)\n self.condition_list.append(instance)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the arm should activate
def _should_arm_activate(self): current = self._get_time() timed_out_at = self.last_detected + self.arm_activity_timeout return current > timed_out_at
[ "def activate_arm(self):\n if not self._should_arm_activate():\n logging.info('Not activating arm; within timeout')\n return\n self._cycle_arm()", "def activate():\n \n if Robo.state != \"active\":\n Robo.state = \"active\"\n print \"Robot is now active\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activate the zombie arm
def activate_arm(self): if not self._should_arm_activate(): logging.info('Not activating arm; within timeout') return self._cycle_arm()
[ "def arm_drone(self):\n\n self.take_control()\n time.sleep(1) # To make sure we are in guided mode before arming\n self.arm()\n\n # Set the current global position as the home position\n self.set_home_as_current_position()\n\n if self.armed:\n self.state = State...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes the frames from the stream
def process_frames_from_stream(self): while True: logging.debug('Checking Frame') frame = self.stream.get_frame() if self.stream.is_frame_empty(frame): continue self.latest_frame = frame self.daddy.process_frame(frame)
[ "def parseFrames(self):\n\n start = self.buf.find(\"\\x00\")\n\n while start != -1:\n end = self.buf.find(\"\\xff\")\n if end == -1:\n # Incomplete frame, try again later.\n return\n else:\n frame, self.buf = self.buf[start ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the bit depth of the given image.
def getBitDepth(im=None, numpy=False): import error if im==None: im=getImage() bd=im.getBitDepth() if numpy==False: return bd elif bd==8: return 'uint8' elif bd==16: return 'uint16' elif bd==32: return 'float' else: raise error.ImageTypeNotSupported, "RGB images not supported"
[ "def _get_bit_depth(color_count):\n for i in [1, 2, 4, 8]:\n if color_count <= 2**i:\n return i", "def get_bit_depth(af):\n try:\n cmd = ['soxi', '-b', af]\n with open(os.devnull, 'wb') as f:\n bit_depth = int(subprocess.check_output(cmd, stderr=f))\n except sub...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of slices on the image.
def nSlices(im=None): if im==None: im=getImage() return im.getNSlices()
[ "def split_num_slices_per_axis(self):\n return self.__split_num_slices_per_axis", "def __len__(self) -> int:\n return self.num_images", "def getNumberOfSuperpixels(self) -> retval:\n ...", "def GetNumberOfDimensions(self) -> \"unsigned int\":\n return _ITKIOImageBaseBasePython.itkI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the selected slice to 'n'.
def setSlice(n, im=None): if im==None: im=getImage() im.setSlice(n)
[ "def selectEveryNth(self, n): \n\t\tif not n:\n\t\t\tfor i in range(len(self.buttonList)):\n\t\t\t\tself.selectedFrames[i] = 0\n\t\t\t\tself.setButtonState(self.buttonList[i], 0)\n\t\t\treturn\n\t\tfor i, btn in enumerate(self.buttonList):\n\t\t\tif not (i) % n:\n\t\t\t\tself.selectedFrames[i] = 1\n\t\t\t\ts...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the image shape as a tuple of (nslices, width, height).
def getShape(im=None): if im==None: im=getImage() return (im.getNSlices(), im.getWidth(), im.getHeight())
[ "def get_image_shape(self) -> Tuple[int, int]:", "def image_shape(fidelity=None):\n return [2 * Bridge.HEIGHT, Bridge.WIDTH]", "def image_shape(self):\n return self.mri_imgs[0].shape", "def get_images_shape():\n return (self.batch_size, self.OUTPUT_SIZE, self.OUTPUT_SIZE, self.NUM_CHANNEL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays a message in the ImageJ status bar.
def showStatus(msg): import ij.IJ ij.IJ.showStatus(msg)
[ "def show_message(self, msg):\n bar = self.statusBar()\n bar.showMessage(msg)", "def show_message(self, msg):\n self.statusbar.SetLabel(msg)", "def show_message(self, text):\n self.statusbar.showMessage(text, 2000)", "def status(text):\n if SHOW_UI:\n pygame.display.set_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves value in the preferences file using the keyword key.
def setPrefs(key, value): import ij.Prefs ij.Prefs.set(key, str(value)) ij.Prefs.savePreferences()
[ "def SetKeyword(key, value):", "def write_pref(pref_name, pref, s3_bucket, prefs_path='metadata/Preferences.plist'):\n prefs_plist = read_plist_s3(prefs_path, s3_bucket)\n prefs_plist[pref_name] = pref\n write_plist_s3(prefs_plist, prefs_path, s3_bucket)", "def save(self):\n pickle.dump(self.key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs an ImageJ command using the specified image and options.
def run(command, options=None, im=None): import ij.IJ if options==None: ij.IJ.run(command) elif im==None: ij.IJ.run(command, options) else: ij.IJ.run(im, command, options)
[ "def runIjandShow(image_name):\n if os.path.isfile(image_name):\n subp.Popen([IJShow.ijpath, image_name],\n shell=False, stdin=None, stdout=None, stderr=None, close_fds=True)\n else:\n logging.warning('Specified file ' + image_name + \" does not exist\")", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invalidate this reference to this file descriptor, closing it if necessary Returns true if we removed the last reference, and closed the FD. We'll use the task inside the last file descriptor to be invalidated to actually do the close.
async def invalidate(self) -> bool: if self._invalidate(): # we were the last handle for this fd, we should close it logger.debug("invalidating %s, no handles remaining, closing", self) await rsyscall.near.close(self.task.sysif, self.near) del fd_table_to_near_to_...
[ "def release_fd(self):\n if isinstance(self._fd, WeakRef): return\n if self.fd is None: return\n self.get_handle() # because fd might be released unexpectedly, we must keep handle\n self._fd = WeakRef(self._fd)", "def closing_fd(self, fd):\n pass", "def close(self) -> None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy this file descriptor into this task, if it isn't already in there. The immediate use case for this is when we're passed some FD handle and some task to use for some purpose, and we're taking ownership of the task. If the FD handle is already in the task, we don't need to copy it, since we necessarily are taking ow...
def maybe_copy(self: T_fd, task: FileDescriptorTask[T_fd]) -> T_fd: if self.task == task: return self else: return self.for_task(task)
[ "async def prep_fd_transfer(self) -> t.Tuple[FileDescriptor, t.Callable[[Task, FileDescriptor], Connection]]:\n pass", "def execute(self, env, args):\n\n task_name = args.task_name\n clone_task = args.clone_task\n\n if not env.task.create(task_name, clone_task):\n raise erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unshare this task's file descriptor table. When such an unshare is done, the new file descriptor table may contain file descriptors which were copied from the old file descriptor table but are not now referenced by any FileDescriptor. Likewise, the old file descriptor table may contain file descriptors which are no lon...
async def unshare_files(self) -> None: if self.manipulating_fd_table: raise Exception("can't unshare_files while manipulating_fd_table==True") # do a GC now to improve efficiency when GCing both tables after the unshare gc.collect() await run_fd_table_gc(self.fd_table) ...
[ "def removefshare(self, protocol, vfs, sharename,\n fpg=None, fstore=None):", "def erase_lookup_tables(self):\n erase_lookup_tables(self)", "def uncacheTable(self, tableName: str) -> None:\n self._ssql_ctx.uncacheTable(tableName)", "def deallocate_shared_mem(self):\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for adding records to the blog
def add_record(title, description): connection = sqlite3.connect('blog.sqlite3') cursor = connection.cursor() sql = f'INSERT INTO records (Title, Description) VALUES ("{title}", "{description}")' cursor.execute(sql) connection.commit() connection.close() return None
[ "def _db_add_post_entries():\n\n\twith io.open('data/post_list.json', mode='r', encoding='utf-8') as json_file: \n\t\tpost_list = json.load(json_file)\n\n\tposts = post_list['posts']\n\n\tdb = get_db()\n\tfor post in posts:\n\t\tif 'thumbnail_img_url' not in post:\n\t\t\timg = 'img/empty.png'\n\t\telse:\n\t\t\ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test adding dividend. Dividend sum is always entered in EURos
def test_dividend(self): dividend_sum = 231.76 self.account.div(security=self.security, price=1.3, cash_amount=dividend_sum, date=timezone.now(), currency=self.currency_eur, exchange_rate=1) positions = self.account.get_positions() ...
[ "def test_calculate_dividend_yield(self):\n\n def case(stock, price, exp_yield):\n self.assertEqual(stock.calculate_dividend_yield(price), exp_yield)\n\n price = 100.0\n\n case(self.tea, price, 0)\n case(self.pop, price, 0.08)\n case(self.ale, price, 0.23)\n case...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
arrseq can be an iterator that yield 2D(grey) or 3D(color) image extension to PIL save TIFF
def saveTiffMultipageFromSeq(arrseq, fn, rescaleSeqTo8bit=False, rgbOrder="rgba", **params): # if arr.ndim == 4: # if arr.shape[1] not in (1,2,3,4): # raise ValueError, "can save 4d arrays (color) only with second dim of len 1..4 (RG[B[A]])" # elif arr.ndim != 3: # raise ValueEr...
[ "def test_sequence_oif_series():\n fname = private_file('oif/MB231cell1_paxgfp_PDMSgasket_'\n 'PMMAflat_30nm_378sli.oif.files/*.tif')\n tifs = TiffSequence(fname, pattern='axes')\n assert len(tifs) == 756\n assert tifs.shape == (2, 378)\n assert tifs.axes == 'CZ'\n # memory...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if the function correctly returns the least significant bit(s)
def test_least_significant_bit_basic(self): number = 0b10110000111 self.assertEqual(lsb(number), 0b1) self.assertEqual(lsb(number, 4), 0b0111) self.assertEqual(lsb(number, 9), 0b110000111) self.assertEqual(lsb(number, 10), 0b110000111) self.assertEqual(lsb(number, 11), ...
[ "def least_significant(num, n):\n mask = 2**n - 1\n return num & mask", "def test_least_significant_bit_long(self):\n\n number = 0b111110010001000101001101010101001111101010011010000111011110010010011110011011101\n self.assertEqual(lsb(number), 0b1)\n\n number = 0b1010101100010101101010...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if the function correctly returns the least significant bit(s) from long integers
def test_least_significant_bit_long(self): number = 0b111110010001000101001101010101001111101010011010000111011110010010011110011011101 self.assertEqual(lsb(number), 0b1) number = 0b101010110001010110101010101111100101101000001101001010110001101000101101010101010 self.assertEqual(lsb(n...
[ "def test_least_significant_bit_basic(self):\n\n number = 0b10110000111\n\n self.assertEqual(lsb(number), 0b1)\n self.assertEqual(lsb(number, 4), 0b0111)\n self.assertEqual(lsb(number, 9), 0b110000111)\n self.assertEqual(lsb(number, 10), 0b110000111)\n self.assertEqual(lsb(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the value of the dipole form factor for a given Q^2
def dipole_form_factor(q2): return (1 + q2 / 0.71) ** -2
[ "def dipolePotential(x,y,q,d):\n V1 = pointPotential(x,y,q,-d/2,0.)\n V2 = pointPotential(x,y,q,d/2,0.)\n Vdp = V1 - V2\n return Vdp", "def dipolePotential(x,y,q,d):\n posx = x+ d/2\n posy = y \n o = pointPotential(x,y,q,posx,posy)\n posx = x- d/2\n posy = y\n b = pointPotential(x,y,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the needed Instrument objects
def create_instrument(): logger.info('Creating Instruments...') instrument_codes = ['STOCK', 'FX', 'BOND', 'INDICIE'] instrument_names = ['Stocks', 'Foreign Exchange', 'Bonds', 'Indicies'] instrument_descriptions = ['Company shares', 'Foreign exchange instruments', 'Treasuries/Corporate bonds', ...
[ "def CreateInstruments(self):\r\n def sim(s):\r\n \"\"\"Nested function used only here, returns a simplified string\"\"\"\r\n s = s.replace('\\\\r','\\r')\r\n s = s.replace('\\\\n','\\n')\r\n #Other simplifications might be necessary in the future I suppose.\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the Currency and FX objects
def create_currency(): logger.info('Creating Currencies..') save_currencies() logger.info('Created Currencies') logger.info('Creating Currency Pairs..') save_currency_pairs() logger.info('Created Currency Pairs') logger.info('Creating FX Data...') get_fx_data() logger.info('Created F...
[ "def create_currencies():\n\tspecs = load_metadata().get('currencies', [])\n\tfor spec in specs:\n\t\t_create_currency(**spec)", "def __init__(self):\n self.currency_id = ''\n self.currency_code = ''\n self.currency_name = ''\n self.currency_symbol = ''\n self.price_precision = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the Country objects
def create_country(): logger.info('Creating Countries..') country_codes = ['USA', 'UK', 'CN', 'CAN', 'GER'] country_names = ['United States of America', 'United Kingdom', 'China', 'Canada', 'Germany'] country_currencies = ['USD', 'GBP', 'CNY', 'CAD', 'EUR'] for code, name, currency_code in zip(cou...
[ "def setUp(self):\n self.test_country_1 = Country('Country_one', 100, 1000)\n self.test_country_2 = Country(\"Country_two\", 50, 100)", "def setUp(self):\n if not self.all_countries:\n print(\"Loading all countries...\")\n country_names = CountryInfo().all()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the Exchange objects
def create_exchange(): logger.info('Creating Exchanges..') exchange_codes = ['NYSE', 'NASDAQ', 'LSE', 'SSE'] exchange_names = ['New York Stock Exchange', 'NASDAQ Stock Market', 'London Stock Exchange', 'Shanghai Stock Exchange'] exchange_countries = ['USA', 'USA', 'UK', 'CN'] ...
[ "def create_exchanges():\n coinbasepro = ccxt.coinbasepro({\n 'apiKey': api_keys.coinbasepro['apiKey'],\n 'secret': api_keys.coinbasepro['secret'],\n 'enableRateLimit': True,\n })\n\n cex = ccxt.cex({\n 'apiKey': api_keys.cex['apiKey'],\n 'secret': api_keys.cex['secret'],...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the DataType objects
def create_data_type(): logger.info('Creating Data Types..') data_codes = ['DAILY', 'INTRADAY'] data_description = ['Data for a 24 period', 'Data for a 1 minute perioo'] for code, description in zip(data_codes, data_description): DataType.objects.update_or_create(code=code, description=descrip...
[ "def createDataType(self, name=None, iconName=\"dataType\", propertyDefinitions=None):\r\n\r\n if name is None:\r\n datatypeName = self._NEW_BASE_DATATYPE_NAME\r\n else:\r\n datatypeName = name\r\n if datatypeName in self._dataTypes:\r\n counter = 0\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the Stock objects
def create_stocks(): logger.info('Creating Stocks and Stock Data...') logger.info('Adding NYSE Stocks...') NYSE().save_stocks() logger.info('Added NYSE Stocks') logger.info('Adding NASDAQ Stocks...') NASDAQ().save_stocks() logger.info('Added NASDAQ Stocks')
[ "def create_stock():\n return {\n \"code\": \"success\",\n \"message\": \"stock created\"\n }", "def __create_stock_transfer_jobs(self):\n self.add_debug('Create pool creation transfer jobs ...')\n\n current_index = max(self.__transfer_jobs.keys())\n\n for sector_index, is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function evaluates the accuracy of the predicted photometric redshifts. It calculates the fraction of objects within a 0.1/0.2/0.3 redshift distance to the true values, the fraction of objects within a relative redshift distance of 0.1/0.2/0.3 (dz01, dz02, dz03) and the standard deviation and the relative redshift...
def evaluate_photoz(z_true, z_phot): delta_z = abs(z_phot - z_true) print "Standard deviation: " print np.std(z_phot - z_true) dz03 = float(len(np.where(delta_z < 0.3)[0]))/float(len(delta_z)) dz02 = float(len(np.where(delta_z < 0.2)[0]))/float(len(delta_z)) dz01 = float(len(np.where(delta_z ...
[ "def compute_depth_errors(gt, pred):\n thresh = np.maximum((gt / pred), (pred / gt))\n a1 = np.mean((thresh < 1.25 ).astype(np.float))\n a2 = np.mean((thresh < 1.25 ** 2 ).astype(np.float))\n a3 = np.mean((thresh < 1.25 ** 3 ).astype(np.float))\n \n rmse = (gt - pre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates a redshiftredshift plot of measured redshifts against photometrically determined redshifts. It returns the matplotlib plot.
def plot_redshifts(y_true, y_pred): # Tex font rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) rc('text', usetex=True) fig = plt.figure(num=None, figsize=(4.5, 4), dpi=140) fig.subplots_adjust(left=0.12, bottom=0.14, right=0.94, top=0.96) ax = fig.add_subplot(1, 1, 1) ...
[ "def plot_shifted_spectrum(self, wavlim=(5158, 5172)):\n if not isinstance(wavlim, list) and not isinstance(wavlim, np.ndarray):\n wavlim = [wavlim]\n\n num_regions = np.shape(wavlim)[0]\n\n for i in range(num_regions):\n plt.subplot(num_regions, 1, i + 1)\n\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
display the square with all its sums and its magic character
def displayMagicSquare(square): n = len(square) sommeMagique = n*(n**2+1)//2 magik = True # V0 : afficher les valeurs uniquement en mode carré for i in range(n): for j in range(n): print("{:>3}".format(square[i][j]), end=' ') # V1 : afficher les sommes de lignes ...
[ "def display_magic_square(s, magic):\n print('Magic value: %d' % magic)\n for i in range(len(s)):\n print('%.3d|' * len(s) % tuple(s[i]))", "def show_sub_square(self, start, size):\n end = start + size\n ret_str = ''\n for row in range(start, end):\n for col in range(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Downloads image from an url and returns PIL image
def download_image(image_url): resp = requests.get(image_url, stream=True, timeout=5) im_bytes = BytesIO(resp.content) image = Image.open(im_bytes) return image
[ "def url_to_img(url):\n response = requests.get(url)\n return Image.open(BytesIO(response.content))", "def loadImageFromURL(url,destFileName):\r\n f = open(destFileName,'wb')\r\n f.write(requests.get(url).content)\r\n f.close()\r\n img = readParkingImage(destFileName)\r\n return img", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Conducts a search for searchText on facebook search box. Returns a list of matches with links to the matched profiles and some basic info.
def conductSearch(self, searchText): soup = BeautifulSoup(self.currentPageContent) # Make sure we are logged in... if not self.isLoggedIn(): print "We are not logged in. Please login to conduct a search.\n" return None # Find the search form ... This is to check t...
[ "def get_search_results(self, keyword):\n\n if keyword is not None and len(keyword) > 0:\n search_results = []\n # Trim keyword to IMDb max length\n if len(keyword) > 20:\n keyword = keyword[:20]\n request = f'https://v2.sg.media-imdb.com/suggestion/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a graph of contacts (or members in case of groups) of the target entity. Returns the results in the form of a dictionary. The 'level' parameter specifies the depth and it defaults to 2.
def buildGraph(self, targetEntity, level=2): pass
[ "def make_membership_tree(context, person, node):\n if node in person.gather_entities():\n return {\n 'node': node,\n 'person': person,\n }\n\n request = context['request']\n entity = entity_for_page(request.current_page)", "def contact_details_for_entity(context):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gaussian 2D Model, also does convolution with global kernel parameter
def gaussian2D(x, y, centerx, centery, sigmax, sigmay, amplitude, theta): # TODO: find a way to optimise? Spending half of total time here because of convolution cost2 = np.cos(theta) ** 2 sint2 = np.sin(theta) ** 2 sin2t = np.sin(2. * theta) xstd2 = sigmax ** 2 ystd2 = sigmay ** 2 xdiff = x - ...
[ "def gauss_kernel(sigma):\n l = int(np.ceil(2 * sigma))\n x = np.linspace(-l, l, 2*l+1)\n\n # FORNOW\n gx = np.zeros_like(x)\n\n \"\"\"\n *******************************************\n *** TODO: compute gaussian kernel at each x\n *******************************************\n \"\"\"\n \n sigma_denom = (si...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flattens variance and converts to error
def flatten_error(var): im_var = convert_data_to_odd_axes(var) try: output = (im_var.filled(0.0)).flatten() except: output = im_var.flatten() error = np.sqrt(output) # error is st.dev., so take square root of variance to get it error = np.nan_to_num(error, nan=-0.001) # if any...
[ "def _flatten_error_array( error, axis ):\n if error is not None:\n error_squared = error * error\n flat_errorsq = np.average( error_squared, axis=axis )\n flat_error = np.sqrt( flat_errorsq )\n else:\n flat_error = None\n return flat_error", "def normalized_variance(timeserie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns parameters guess. If priors are given (non 0), then takes them as guess. Otherwise makes its own guess
def get_param_guess(x, y, z, priors=np.zeros(16)): priors_to_send = np.zeros(16) maxx, minx = np.max(x) + 1, np.min(x) maxy, miny = np.max(y) + 1, np.min(y) maxz, minz = np.max(z), 0 centerx = x[np.argmax(z)] centery = y[np.argmax(z)] height = (maxz - minz) sigmax = (maxx - minx) / 6.0...
[ "def guess_params(true_params, percent):\n\tP = copy_params(true_params, False)\n\tfor i in ['Me', 'Re', 'n']:\n\t\tbulge = i+'B'\n\t\tdisc = i+'D'\n\t\tP[bulge].value *= (1.- percent)\n\t\tP[disc].value *= (1.+ percent)\n\tP['nD'].value = 1.\n\tP['nD'].vary = False\n\treturn P", "def initialGuessParameters(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether a number is even
def is_even(number): return number % 2 == 0
[ "def isEven(number: int) -> bool:\n return ((number % 2) == 0)", "def check_if_number_even(n):\n if (n % 2) == 0:\n return True\n else:\n return False", "def is_even(x):\n return True", "def is_even(number):\n try:\n if int(number) % 2 == 0:\n return True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flattens data, variance and returns x, y and error coordinates
def flatten_xy_err(og_im_data, var): im_data = convert_data_to_odd_axes(og_im_data) data_size_x = np.size(im_data[0]) total_size = np.size(im_data) data_size_y = int(total_size / data_size_x) error = flatten_error(var) x = np.linspace(0, data_size_x-1, data_size_x) x = np.tile(x, data_siz...
[ "def flatten_error(var):\n im_var = convert_data_to_odd_axes(var)\n try:\n output = (im_var.filled(0.0)).flatten()\n except:\n output = im_var.flatten()\n error = np.sqrt(output) # error is st.dev., so take square root of variance to get it\n error = np.nan_to_num(error, nan=-0.001)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots image, given x, y, data and fit in out
def plot_image(out, data, x, y, var, mod, name, image_showing, save_image): x_max = int(np.max(x)+1) y_max = int(np.max(y)+1) print(out.fit_report()) X, Y = np.meshgrid(np.linspace(np.min(x), np.max(y), x_max), # Converts x,y,z values to meshgrid for drawing np.linspace(np...
[ "def plot(image, classified_boxes, window_size):\n fig1 = plt.figure(dpi=400)\n ax1 = fig1.add_subplot(1,1,1) \n ax1.imshow(image, cmap=plt.cm.gray)\n ax1.axis('off')\n for box in classified_boxes:\n x_min, y_min, x_max, y_max = box[0]-.5, box[1]-.5, box[0]+window_size[0]-.5, box[1]+window_siz...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts parameters into separate float variables
def convert_params_to_variables(params): amplitude = params['amplitude'] * 1 center_x = params['centerx'] * 1 center_y = params['centery'] * 1 sigma_x = params['sigmax'] * 1 sigma_y = params['sigmay'] * 1 return amplitude, center_x, center_y, sigma_x, sigma_y
[ "def ufloat_params_into_params(ufloat_params):\n\n params = {}\n for param_name, ufloat_param in ufloat_params.items():\n value = ufloat_param.nominal_value\n error = ufloat_param.std_dev\n params[param_name] = {\n 'v': value,\n 'e': error\n }\n\n return pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a protocol handler, and (optionally) send enable sentence.
def register_handler(self, protocol, handler, send_enable=True): self.handlers[protocol] = handler if send_enable: fields = get_csv_args(handler) if not fields: fields = '*' self.cmd('ENABLE', protocol, fields)
[ "async def on_protocol_event(self, cmd: typing.Any):\n pass", "def registerMessageHandler(self, messageType, handler):\n pass", "def decide_protocol_handler(client, PROTOCOL):\n if PROTOCOL==\"smtp\":\n smtp_conversation(client)\n\n elif PROTOCOL==\"pop\":\n pop_conversation(cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Archive persons specified by their ID, but not users.
def archive_persons(address_book, ids): archived = 0 # this list() call is needed as we might delete from the source of the ids: for name in list(ids): person = address_book[name] ref_target = gocept.reference.interfaces.IReferenceTarget( zope.security.proxy.getObject(person)) ...
[ "def income_archive(self):\n\n id = int(self.request.matchdict.get('id'))\n\n \"\"\" Every user can edit every income object.\n So no authorization needed. \"\"\"\n c = Income.by_id(id)\n if not c:\n return HTTPNotFound()\n\n c.archived = True\n DBSession....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function implements several variants of Zeta by modifying some key parameters. Scores can be document proportions (binary features) or relative frequencies. Scores can be taken directly or subjected to a logtransformation (log2, log10) Scores can be subtracted from each other or divided by one another. The combina...
def calculate_scores(docprops1, docprops2, relfreqs1, relfreqs2, absolute1, absolute2, logaddition, segment_length): # Define logaddition and division-by-zero avoidance addition logaddition = logaddition divaddition = 0.00000000001 # == Calculate subtraction variants == # sd0 - Subtraction, docprops...
[ "def zscore_hypergeometric(fgMatches, fgSize, bgMatches, bgSize):\n if bgSize == 0 or fgSize == 0:\n raise RuntimeError('bgSize and fgSize must not be 0 for calculation!')\n fgMatches, fgSize, bgMatches, bgSize = map(scipy.float_, [fgMatches, fgSize, bgMatches, bgSize])\n mean = fgSize * (float(bgMa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reduces the numerator by acc returns whatever is left in acc.
def Consume(self, acc=None): left = max(0, self.n - acc) acc -= min(self.n, acc) self.n = left return acc
[ "def _normAcc(self, acc):\n if acc > 1: acc = 1\n elif acc < 0: acc = 0\n return acc", "def acc(self, argument: int):\n self.accumulator += argument\n self.jmp(1)", "def setAcc(self, acc):\n self.triple[2] = self. _normAcc(acc)", "def acc(self, value: int) -> None:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A hook to format each row . This method gets called on each row in the results. <ust return the object
def format_row(self, row_obj): return row_obj
[ "def handle_row(self, row):\n pass", "def process_row(self, row):\n\n return row", "def _process_row(self, row):\n # Must be overridden.", "def format_table(row):\n shelter_name = row[\"FacilityName\"]\n last_report = row[\"timestamp_local\"]\n district = integrify(row[\"CouncilD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and return a new `Employee` instance, given the validated data.
def create(self, validated_data): return Employee.objects.create(**validated_data)
[ "def create_employee(self, new_employee):\n # TO-DO", "def from_json_create_employee(cls, data):\n\n # List Comprehension\n return [cls(row['name'], row['email'], row['role']) for row in data]\n\n # Using a For looping to achieve the same results.\n # employees = []\n\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
take a list of the regression datasets and normalize them. This mutates the datasets in place
def normalize(datasets: List[DSet], std: bool = True) -> None: if std: params = datasets[0].standard_normalize() for d in datasets[1:]: d.standard_normalize(*params) return params = datasets[0].one_normalize() for d in datasets[1:]: d.one_normalize(*params)
[ "def normalize_data(x_train, x_test):\n train_mean_1 = np.mean(x_train[:,:,:,:,0])\n train_mean_2 = np.mean(x_train[:,:,:,:,1])\n train_std_dev_1 = np.std(x_train[:,:,:,:,0])\n train_std_dev_2 = np.std(x_train[:,:,:,:,1])\n x_train[:,:,:,:,0] = (x_train[:,:,:,:,0] - train_mean_1) / train_std_dev_1 # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a single user row from 'user' table _filter is ignored id user_id is provided
def get(cls, connection, user_id, **_filter): session = connection.SESSION user = None try: user_obj = (session.query(schema.User).filter_by(id=user_id).one() if user_id else session.query(schema.User).filter_by(**_filter).one()) ...
[ "def get_user(user_id):\n\n try:\n return Stakeholder.objects.all().filter(pk=user_id)[0]\n except LookupError:\n # if connector supports exception, should raise userDoesNotExist\n return None\n\n # all() -> SELECT * FROM stakeholder;\n # all().filter(nick_name = 'a') -> SELECT * FR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get user ID for user_name from 'user' table
def get_user_id(cls, connection, user_name): user = cls.get(connection, None, **{NAME_KEY: user_name}) return user.get(ID_KEY)
[ "def get_user_id(data):\n username = data['username']\n #return 404 if user is not found\n user_id = User.query.filter_by(username=username).first_or_404().id\n\n return user_id", "def get_username_id(self, username):\n c = self.db.cursor()\n try:\n c.execute(\"\"\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a single user row from 'user' table _filter is ignored id user_id is provided
def delete(cls, connection, user_id, **_filter): session = connection.SESSION deleted = True try: user_obj = (session.query(schema.User).filter_by(id=user_id).one() if user_id else session.query(schema.User).filter_by(**_filter).one()) ...
[ "def delete_user(id):\n return u.delete(id)", "def deleteUser(request, userID):\n if (\n request.user.is_authenticated\n and request.user.userinfo.isAdmin\n and not request.user.userinfo.isPending\n ):\n u = userInfo.objects.get(pk=userID)\n v = UserAccount.objects.get(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the book with this id and increment its votes
def vote_f(request, book_id): #book = Book.objects.get(id=book_id) #book.votes_f += 1 #book.save() # TODO: so would it be better to just have votes in the Votes model and add # them up for each book? I.e. above you would actuall not do book.votes_f, # do blah.get_votesblah. So take care of the...
[ "def upvotePost(self):\n self.votes = self.votes + 1\n self.save()", "def add_vote(video):\n video.votes = models.F('votes') + 1\n video.save()", "def update(self, request, pk):\n instance = Post.objects.get(pk=pk)\n instance.amount_of_upvotes += 1\n instance.save()\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that evidence rows can be parsed.
def test_parse_evidence(self): evidence = [ ('--', ''), ('SN', '1'), ('ID', 'Aferr subtype specific proteins'), ('DN', 'Crispy Proteins'), ('RQ', '0'), ('EV', 'IPR017545; TIGR03114; sufficient;'), ('TG', 'GO:0043571;') ]...
[ "def test_parse_evidence_insufficient(self):\n evidence = [\n ('--', ''),\n ('SN', '1'),\n ('ID', 'Aferr subtype specific proteins'),\n ('DN', 'Crispy Proteins'),\n ('RQ', '1'),\n ('EV', 'IPR017545; TIGR03114;'),\n ('TG', 'GO:004357...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the evidence rows can be properly parsed if the evidence is insufficient.
def test_parse_evidence_insufficient(self): evidence = [ ('--', ''), ('SN', '1'), ('ID', 'Aferr subtype specific proteins'), ('DN', 'Crispy Proteins'), ('RQ', '1'), ('EV', 'IPR017545; TIGR03114;'), ('TG', 'GO:0043571;') ...
[ "def test_parse_evidence(self):\n evidence = [\n ('--', ''),\n ('SN', '1'),\n ('ID', 'Aferr subtype specific proteins'),\n ('DN', 'Crispy Proteins'),\n ('RQ', '0'),\n ('EV', 'IPR017545; TIGR03114; sufficient;'),\n ('TG', 'GO:0043571...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the evidence rows can be properly parsed if the evidence has no go terms.
def test_parse_evidence_no_go_terms(self): evidence = [ ('--', ''), ('SN', '1'), ('ID', 'Aferr subtype specific proteins'), ('DN', 'Crispy Proteins'), ('RQ', '1'), ('EV', 'IPR017545; TIGR03114;'), ] parsed_evidence = parse_...
[ "def test_parse_evidence_insufficient(self):\n evidence = [\n ('--', ''),\n ('SN', '1'),\n ('ID', 'Aferr subtype specific proteins'),\n ('DN', 'Crispy Proteins'),\n ('RQ', '1'),\n ('EV', 'IPR017545; TIGR03114;'),\n ('TG', 'GO:004357...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can determine that an evidence is a genome property.
def test_has_genome_property(self): evidences = [ ('--', ''), ('SN', '3'), ('ID', 'Selfish genetic elements'), ('RQ', '0'), ('EV', 'GenProp0066;') ] evidence = parse_evidences(evidences)[0] self.assertEqual(evidence.has_gen...
[ "def test_get_genome_properties(self):\n\n test_evidence = self.tree.root.steps[0].functional_elements[0].evidence[0]\n\n self.assertEqual(test_evidence.has_genome_property, True)\n self.assertEqual(test_evidence.property_identifiers, ['GenProp0089'])\n\n test_child_genome_property = tes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can get the InterPro identifiers for an evidence.
def test_get_interpro_identifiers(self): evidence = [ ('--', ''), ('SN', '1'), ('ID', 'Aferr subtype specific proteins'), ('DN', 'Crispy Proteins'), ('RQ', '0'), ('EV', 'IPR017545; TIGR03114; sufficient;'), ('TG', 'GO:0043571;'...
[ "def test_get_consortium_identifiers(self):\n\n evidence = [\n ('--', ''),\n ('SN', '1'),\n ('ID', 'Aferr subtype specific proteins'),\n ('DN', 'Crispy Proteins'),\n ('RQ', '0'),\n ('EV', 'IPR017545; TIGR03114; sufficient;'),\n ('TG...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can get the consortium identifiers for an evidence.
def test_get_consortium_identifiers(self): evidence = [ ('--', ''), ('SN', '1'), ('ID', 'Aferr subtype specific proteins'), ('DN', 'Crispy Proteins'), ('RQ', '0'), ('EV', 'IPR017545; TIGR03114; sufficient;'), ('TG', 'GO:0043571...
[ "def _get_evidence_identifiers(self, consortium=False):\n global_identifiers = []\n for functional_element in self.functional_elements:\n for evidence in functional_element.evidence:\n if consortium:\n current_identifiers = evidence.consortium_identifiers\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can get genome properties of an evidence.
def test_get_genome_properties(self): test_evidence = self.tree.root.steps[0].functional_elements[0].evidence[0] self.assertEqual(test_evidence.has_genome_property, True) self.assertEqual(test_evidence.property_identifiers, ['GenProp0089']) test_child_genome_property = test_evidence.g...
[ "def test_has_genome_property(self):\n\n evidences = [\n ('--', ''),\n ('SN', '3'),\n ('ID', 'Selfish genetic elements'),\n ('RQ', '0'),\n ('EV', 'GenProp0066;')\n ]\n\n evidence = parse_evidences(evidences)[0]\n self.assertEqual(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a liveupdate broadcast for a specific event.
def send_event_broadcast(event_id, type, payload): websockets.send_broadcast(namespace="/live/" + event_id, type=type, payload=payload)
[ "def update(self, event: MispEvent) -> None:\n event.timestamp = datetime.datetime.now()\n event.published=0\n raw_evt = event.to_xml()\n self.server.POST('/events/%d' % event.id, raw_evt)", "def broadcast(event):\n for listener in _registered[event.kind]:\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
introspects the given "local" object, returns id_pack as expected by BaseNetref The given object is "local" in the sense that it is from the local cache. Any object in the local cache exists in the current address space or is a netref. A netref in the local cache could be from a chainedconnection. To handle type relate...
def get_id_pack(obj): # TODO: Remove that when ghpythonlib.components.__namedtuple.__getattr__ is fixed if hasattr(obj, "____id_pack__") and not isinstance( obj, ghpythonlib.components.__namedtuple ): # netrefs are handled first since __class__ is a d...
[ "def get_id_pack(obj):\n\n if hasattr(obj, \"____id_pack__\"):\n # netrefs are handled first since __class__ is a descriptor\n return obj.____id_pack__\n # str(obj).split(':')[0] == \"Microsoft.Scripting.Actions.NamespaceTracker\" should also work\n eli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
introspects the given "local" object, returns id_pack as expected by BaseNetref The given object is "local" in the sense that it is from the local cache. Any object in the local cache exists in the current address space or is a netref. A netref in the local cache could be from a chainedconnection. To handle type relate...
def get_id_pack(obj): if hasattr(obj, "____id_pack__"): # netrefs are handled first since __class__ is a descriptor return obj.____id_pack__ # str(obj).split(':')[0] == "Microsoft.Scripting.Actions.NamespaceTracker" should also work elif ( ...
[ "def get_id_pack(obj):\n\n # TODO: Remove that when ghpythonlib.components.__namedtuple.__getattr__ is fixed\n if hasattr(obj, \"____id_pack__\") and not isinstance(\n obj, ghpythonlib.components.__namedtuple\n ):\n # netrefs are handled first since __c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the character attributes (colors) of the console screen buffer.
def get_text_attr(): csbi = CONSOLE_SCREEN_BUFFER_INFO() GetConsoleScreenBufferInfo(stdout_handle, byref(csbi)) return csbi.wAttributes
[ "def get_text_attr():\r\n\tcsbi = CONSOLE_SCREEN_BUFFER_INFO()\r\n\tGetConsoleScreenBufferInfo(stdout_handle, byref(csbi))\r\n\treturn csbi.wAttributes", "def get_colors(self) -> List[RGBColor]:\n return [display_character.color for display_character in self]", "def _drawing_attribs(self):\n attri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the character attributes (colors) of the console screen buffer. Color is a combination of foreground and background color, foreground and background intensity.
def set_text_attr(color): SetConsoleTextAttribute(stdout_handle, color)
[ "def setColors(self, fg=None, bg=None):\n if self.console._lockColors is self:\n self.console._lockColors = None\n if fg is not None:\n self._fgcolor = _formatColor(fg)\n if bg is not None:\n self._bgcolor = _formatColor(bg)", "def _setChar(self, x, y, char, f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read or initialize build cache file.
def init_cache(self): self.cache = {} try: with open(os.path.join(self.root, "make.cache"), 'r') as f: cache_raw = f.read() self.cache = json.loads(cache_raw) except IOError: pass
[ "def read_cache(self):\n if os.path.exists(self._cache_file):\n self._cache = _read_cache_file(self._cache_file)\n else:\n self._cache = {}", "def _init_cache(self):\r\n logging.debug('Looking for cache file: %s', self.cachefile)\r\n if os.path.exists(self.cachefi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Autodetect what directories in the module_root are buildable modules and add them to the modules list.
def autodetect_modules(self): modules = [] # Look in module_root root, dirs, _ = next(os.walk(self.module_root)) for d in dirs: if "config.cpp" in os.listdir(os.path.join(root, d)) and not d in self.ignore: modules.append(d) # Look in module_root\addons if it exists if os.path.isdir(os.path.join(se...
[ "def add_modules_path(self):\n\n if self.root_path is None:\n return\n\n for target in set(self.modules_path + self.mandatory_modules_path):\n target_dir = os.path.join(self.root_path, target)\n if os.path.exists(target_dir):\n for dirpath, dirs, files i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the signing key specified from command line if necessary.
def make_key(self): if self.key: if not os.path.isfile(os.path.join(self.root, self.key + ".biprivatekey")): print_green("\nRequested key does not exist.") ret = subprocess.call([self.dscreatekey, self.key], stdout = subprocess.DEVNULL if self.quiet else None, stderr = subprocess.DEVNULL if self.quiet els...
[ "def _gen_key(version):\n priv = keys.generate_sign_key()\n pub = keys.public_sign_key(priv)\n return trcs.Key(version=version, priv_key=priv, pub_key=pub)", "def make_key():\n path = os.path.join(SSH_KEY_DIR.name, SSH_PRIVATE_KEY)\n if not os.path.exists(path):\n cmd = \"ssh-keygen -t rsa -m PEM -b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy built modules to Arma 3 folder for testing.
def copy_to_a3(self): print_blue("Copying addon to Arma 3 folder.") reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: k = winreg.OpenKey(reg, r"SOFTWARE\Wow6432Node\Bohemia Interactive\Arma 3") a3_path = winreg.EnumValue(k, 1)[1] winreg.CloseKey(k) except IOError: print_error("Coul...
[ "def copy_build_files(base_dir, builder):\n builder.run_root('if [ ! -e /build ]; then mkdir /build; fi')\n for f in BUILD_FILES:\n # /build is used instead of /tmp here because /tmp can be bind-mounted\n # during build on Singularity (and the copied files are hidden by this\n # mount).\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots a graph in graphviz dot notation.
def plot_dot_graph(graph, filename=None): if not plot.pygraphviz_available: logger.error("Pygraphviz is not installed, cannot generate graph plot!") return if not plot.PIL_available: logger.error("PIL is not installed, cannot display graph plot!") return agraph = AGraph(grap...
[ "def view_dot_graph(graph, filename=None, view=False):\n # Optionally depends on graphviz package\n import graphviz as gv\n\n src = gv.Source(graph)\n if view:\n # Returns the output file path\n return src.render(filename, view=view)\n else:\n # Attempts to show the graph in IPyt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flattens a list so that all prime numbers in embedded lists are returned in a flat list
def flatten_list_prime(l): pass
[ "def reduce_to_primes(l):\n factors = []\n for i in l:\n pf = list(get_prime_factors(i))\n if pf:\n factors.extend(pf)\n else:\n factors.append(i)\n return factors", "def flatten(l):\n return [item for sublist in l for item...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a new CassiopeiaTree by merging leaves. Pairs of leaves in the given tree is iteratively merged until a stopping condition is met (specified by ``ratio`` or ``number_of_merges`` when initializing the sampler). Pairs of leaves are selected by the following
def subsample_leaves( self, tree: CassiopeiaTree, collapse_source: Optional[str] = None, collapse_duplicates: bool = True, ) -> CassiopeiaTree: n_merges = ( self.__number_of_merges if self.__number_of_merges is not None else int(tree.n_cell...
[ "def get_random_tagged_tree(number_leafnodes, percentage_parasites, percentage_unknown, p_multifurcation, beta_distribution_parameters):\n # Arguments:\n # number_leafnodes - needed for randomized function\n # percentage_parasites\n # percentage_unknown - proportion of ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the zip and initiate training by the model.
def train_from_zip(self, zip_file_path): text = load_text_zip(zip_file_path) model.learn(text)
[ "def train_from_zip(self, zip_file_path):\n text = self.load_text_zip(zip_file_path)\n self.model.learn(text)", "def do_training():\n train_cls = Train()\n train_cls.run()", "def __init_dirs(self) -> None:\r\n if not os.path.exists(self.path_to_encodings): os.makedirs(self.path_to_enc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the zip and initiate training by the model.
def train_from_zip(self, zip_file_path): text = self.load_text_zip(zip_file_path) self.model.learn(text)
[ "def train_from_zip(self, zip_file_path):\n text = load_text_zip(zip_file_path)\n model.learn(text)", "def do_training():\n train_cls = Train()\n train_cls.run()", "def __init_dirs(self) -> None:\r\n if not os.path.exists(self.path_to_encodings): os.makedirs(self.path_to_encodings)\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clean up data features that used in neural network models. Features like 'range', 'variance', 'cov', 'lengthStdDev' are in range [inf, inf] or [0, inf]. These features may cause problems in NN model and need to be normalized. We adopt normalization by distribution here. To take range as an example, this feature distrib...
def cleanup_data_features_nn(data_features: dict): # Normalize range, var and cov raw_range = data_features.get('range', 0.0) norm_range = 1 if isinstance(raw_range, str) else min(1.0, math.sqrt(raw_range) / 25528.5) raw_var = data_features.get('variance', 0.0) norm_var = 1 if isinstance(raw_var, st...
[ "def normalize_features(train_filtered, test_filtered):\n for c in test_filtered.columns:\n # If not binary\n if train_filtered[c].max() > 1.001 or train_filtered[c].min() < -0.001:\n # Standardize in train\n # Standardize in test with the scale parameters of train\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
epw_to_data_frame(IO) Gets the data out of an epw file, and returns it as a pandas DataFrame.
def epw_to_data_frame(file_): return pandas.read_csv( file_, header=8, names=field_names, index_col=False, na_values=missing_values, parse_dates={'datetime': [0, 1, 2, 3, 4]}, date_parser=date_converter )
[ "def to_dataframe(fp):\n # Avoid circular import problems.\n # Xport Modules\n from xport.v56 import load\n warnings.warn('Please use ``xport.v56.load`` in the future', DeprecationWarning)\n library = load(fp)\n dataset = next(iter(library.values()))\n return dataset", "def h5ToDf(filename):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare lines striped from whitespaces characters.
def compare_lines(lines, lines2): for l, l_test in zip(lines, lines2): assert l.strip() == l_test.strip()
[ "def cmp_lines(path_1, path_2):\n line_1 = line_2 = ' '\n with open(path_1, 'r') as file_1:\n with open(path_2, 'r') as file_2:\n while line_1 != '' and line_2 != '':\n line_1 = file_1.readline()\n line_2 = file_2.readline()\n if line_1 != line_2:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a response object for requesting geolocation permissions. The returned object's speech can be modified if you want to add more information.
def request_geolocation_permission_response(): response = mycity_response_data_model.MyCityResponseDataModel() response.output_speech = GENERIC_GEOLOCATION_PERMISSON_SPEECH response.card_type = "AskForPermissionsConsent" response.card_permissions = ["alexa::devices:all:geolocation:read"] response.sh...
[ "def request_device_address_permission_response():\n response = mycity_response_data_model.MyCityResponseDataModel()\n response.output_speech = GENERIC_DEVICE_PERMISSON_SPEECH\n response.card_type = \"AskForPermissionsConsent\"\n response.card_permissions = [\"read::alexa:device:all:address\"]\n resp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a response object for requesting geolocation permissions. The returned object's speech can be modified if you want to add more information.
def request_device_address_permission_response(): response = mycity_response_data_model.MyCityResponseDataModel() response.output_speech = GENERIC_DEVICE_PERMISSON_SPEECH response.card_type = "AskForPermissionsConsent" response.card_permissions = ["read::alexa:device:all:address"] response.should_en...
[ "def get_location_by_filter(self, **kwargs):\n\n all_params = ['filter', 'page', 'limit', 'sort']\n all_params.append('callback')\n\n params = locals()\n for key, val in iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }