query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Query available sources for sequence details. Add additional methods below to allow fetching from other sources. Perform mutations etc if given via metadata.
def _query_sequence_sources(self): if self.uniprot_id: self._query_uniprot() elif self.ncbi_id: self._query_ncbi() if "mutations" in self.metadata.keys(): mutations = self.metadata["mutations"].split() del self.metadata["mutations"] # remove mutat...
[ "def _query_sequence_sources(self):\n pass", "async def get_sources(sources):\n url = URL + 'sources'\n params = {\"language\": 'en'}\n \n # AIOHTTP session start\n session = aiohttp.ClientSession()\n async with aiohttp.ClientSession() as session:\n async with session.get(url, ssl=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch the amino acid sequence from UniProt.
def _query_uniprot(self): import requests import json response = requests.get(f"https://www.ebi.ac.uk/proteins/api/proteins/{self.uniprot_id}") if response.status_code != 200: raise ValueError(f"Failed to fetch sequence for UniProt ID {self.uniprot_id}") response = ...
[ "def fetch_uniprot_fasta(accession_id):\n base_url = \"http://www.uniprot.org/uniprot/\"\n \n fasta_url = base_url + accession_id + \".fasta\"\n \n sequence = \"\"\n \n for line in urllib.request.urlopen(fasta_url):\n text = line.decode(\"utf-8\").strip()\n \n if text.star...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch the amino acid sequence from NCBI.
def _query_ncbi(self): import requests response = requests.get( f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" f"db=protein&id={self.ncbi_id}&rettype=fasta&retmode=text" ) if response.status_code != 200: raise ValueError(f"Failed to fet...
[ "def get_sequence(contig_faa):\n seq = util.NOT_AVAILABLE\n if os.path.isfile(contig_faa) and not os.stat(contig_faa).st_size == 0:\n record = SeqIO.read(open(contig_faa), \"fasta\")\n seq = record.seq\n return seq", "def fetch_uniprot_fasta(accession_id):\n base_url = \"http://www.unipr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert an NCBI protein accession to the corresponding UniProt ID.
def ncbi_to_uniprot(ncbi_id): import requests url = "https://www.uniprot.org/uploadlists/" params = {"from": "P_REFSEQ_AC", "to": "SWISSPROT", "format": "tab", "query": ncbi_id} response = requests.get(url, params=params) response = response.text.split("\n") if len(resp...
[ "def get_uniprot_id(hgnc_id):\n uniprot_id = uniprot_ids.get(hgnc_id)\n return uniprot_id", "def fetch_uniprot_fasta(accession_id):\n base_url = \"http://www.uniprot.org/uniprot/\"\n \n fasta_url = base_url + accession_id + \".fasta\"\n \n sequence = \"\"\n \n for line in urllib.reques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs validation through type checking on the given value. The value should be an instance of ``typ`` to pass validation. Otherwise ``ValidationError`` is raised. If ``allow_empty`` is False, ``Missing`` is raised when the value is None.
def validate(self): if self.value is None and self.allow_empty: return self.value if self.value is None: raise Missing(f"{self.name} is required") if not type(self.value) == self.typ: raise ValidationError( f"{self.name} should be {self.typ}. "...
[ "def Validate(value, type):\n if not value:\n raise ValueError('Value should not be empty; received %s.' % value)\n elif not isinstance(value, type):\n raise TypeError('Expected a %s, but received %s (a %s).' % \n (type, value, value.__class__))", "def check_type_value(val, name, expect...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the polynomial expansion in the denominator and numerator of the controller function K and G then this function returns the poles and zeros of the closed loop transfer function in terms of reference signal the arrays for the input must range from the highest order of the polynomial to the lowest
def Poly_Zeros_T(Poly_z_K,Poly_p_K,Poly_z_G,Poly_p_G): Poly_z=numpy.polymul(Poly_z_K,Poly_z_G) Poly_p=numpy.polyadd(numpy.polymul(Poly_p_K, Poly_z_G), numpy.polymul(Poly_p_K, Poly_p_G)) # return the poles and zeros of T Zeros=numpy.roots(Poly_z) Poles=numpy.roots(Poly_p) ...
[ "def _g(self,pp,p,k):\n \n # define prefact \n # get the corresponding legendre polynomial \n Pk = legendre(k)\n # define momentum transfer dependent on angles \n qval=np.sqrt(p**2+pp**2-2*p*pp*self.xp)\n \n # build integral of regularized OBE \n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append an ical event
def append(self, event): self.cal.add_component(event) self.size +=1
[ "def add_event_to_ical(event, cal):\n ical_event = cal.add('vevent')\n name = event.name\n if event.restriction == Event.MEMBER:\n name += \" (Members Only)\"\n elif event.restriction == Event.OFFICER:\n name += \" (Officers Only)\"\n ical_event.add('summary').value = name\n ical_eve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode the 1D barcodes in a set of images and log the result.
def main(): stats = [] start = timer() for file_name in get_dataset(): # load image and ground truth detection mask img = cv2.imread(settings.PATH + file_name) ground_truth_mask = cv2.imread(settings.PATH_GT_MASKS + file_name) # Find list of barcode regions (rotated rectan...
[ "def decode_one(img):\n\n \"\"\" obtain image data\"\"\"\n if len(img.shape) == 3:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n width, height = img.shape\n \n \"\"\" resize\"\"\"\n maxLen = max([width, height])\n if maxLen < QR_CODE_PATCH_MIN_SIZE:\n img = cv2.resize(img, (150,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the features group list
def clear_features(self): self.features_group_list = []
[ "def clear_groups(self):\n self.__groups = []", "def clear_Groups(self):\n\n\t\tself.__groups[:] = []", "def clear_surface_groups(self):\n self.surface_groups = {}", "def reset_features_list(self):\n self.categorical_features = Data.categorical_features.copy()\n self.continuous_fea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize first row and column of array with values = 1
def initArrayWithNumbers(self, array): for i in range(array.shape[0]): array[i][0] = 1 for j in range(array.shape[1]): array[0][j] = 1 return array
[ "def init_one_d_array(len, val):\n return [val for i in range(len)]", "def ones(shape, dtype):\n result = PitchArray(shape, dtype)\n result.fill(1)\n return result", "def ones_like(other_ary):\n result = PitchArray(other_ary.shape, other_ary.dtype)\n result.fill(1)\n return result", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds fist parent of element of the given type
def findTypeParent(element, tag): p = element while True: p = p.getparent() if p.tag == tag: return p # Not found return None
[ "def getFirstTypeParent(start, node_type):\n parents = start.getAllParents()\n for parent in parents:\n if parent.nodeType() == node_type:\n return parent\n\n return None", "def findTypeParent(element, tag):\n \n p = element\n while True:\n p = p.getparent()\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns list of all skills for specific profile from profile_id through GET request
def get_skills_by_profile(profile_id=None): # get profile object profile = storage.get("Profile", profile_id) if profile is not None: result = [] # use relationship to get all skills for that profile for skills in profile.skills: # append each skill's dictionary ...
[ "def add_skills_to_profile():\n # get specific objects\n profile = storage.get(\"Profile\", profile_id)\n skills = storage.get(\"Skills\", skills_id)\n if profile is not None and skills is not None:\n # check every skill in profile\n for profile_skill in profile.skills:\n # if t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes specific skill from specific profile with their ids through DELETE request
def remove_skills_from_profile(profile_id=None, skills_id=None): # get specific objects profile = storage.get("Profile", profile_id) skills = storage.get("Skills", skills_id) if profile is not None and skills is not None: # check every skill in profile for profile_skill in profile.skills...
[ "def delete_skill(id, skill):\n with app.app_context():\n user = User.query.get(id)\n if user is None:\n return \"User not found\", 404\n skill_db = Skill.query.filter_by(name=skill).first()\n if skill_db is None:\n return \"Skill not found\", 404\n user.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
links specific skills to specific profile through ids through POST request
def add_skills_to_profile(): # get specific objects profile = storage.get("Profile", profile_id) skills = storage.get("Skills", skills_id) if profile is not None and skills is not None: # check every skill in profile for profile_skill in profile.skills: # if the given skill i...
[ "def update_skills(request):\n\n profile = request.user.profile\n skills = request.data[\"skills\"]\n profile_skills = ProfileSkillModel.objects.all()\n # Gather info for new skills to be updated on profile\n profile_skill_data = {}\n profile_skill_data[\"profile\"] = profile.id\n\n # Check tha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the state of the boids as a tensor. The state of the boids stores their attributes across dimensions, such as locations, velocities, and acclerations.
def _init_boids_state(self) -> np.ndarray: dims, n_boids, n_attrs = self.dims, self.num_boids, len(Boids.Attr) max_vel, max_acc = self.max_vel, self.max_acc state = np.zeros([dims, n_boids, n_attrs], dtype="float") for idx, env_dim in zip(range(dims), self.env_bounds): state...
[ "def initialise_positions(self):\r\n #print(\"initialise_positions\")\r\n for i in range(self.numBoids):\r\n self.boids.append(Boid(random.randint(0, self.width), random.randint(self.height, self.height+5)))\r\n #self.boids.append(Boid(random.randint(0, self.width), random.randin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a matrix of the square of the euclidean distance between the the boid at the current index and all other boids
def compute_distance(self): loc = np.extend_dims(self.state[:, :, Boids.Attr.LOC], axis=-1) m = np.tile(loc, (1, 1, self.num_boids)) pos_diff = m-m.transpose(0, 2, 1) self.distance = np.linalg.norm(pos_diff, axis=0)
[ "def compute_distance_matrix(self):\n return np.square(self.data[:, np.newaxis, :] - self.centers[['x1', 'x2']].as_matrix()).sum(axis=2)", "def get_distances(self):\n N = len(self.cells) # Number of cells\n distances = np.zeros([N, N]) # distances between cells\n positions = self.posit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an acceleration delta as the result of the alignment rule The acceleration delta is defined by the difference between a boids' orientation and a linear combination of its neighbors' orientations. The mut_influence tensor will supply the needed cofficients.
def align(self) -> np.ndarray: vel = self.state[:, :, Boids.Attr.VEL] vel_norm = np.linalg.norm(vel, axis=0) orientation = vel / (vel_norm + EPSILON) mut_influence = self._perceive(self.p_range) desired_orientation = np.dot(orientation, mut_influence) desired_orientation ...
[ "def attraction(self, other: Body) -> Vector:\n dist = self.position - other.position\n dist_modsq = dist.lensq\n dist_unit = dist / math.sqrt(dist_modsq) # Unit vector\n G = 6.674384e-11\n force_mod = G * self.mass * other.mass / dist_modsq\n return dist_unit * force_mod"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Temporarily extends boids' p_ranges if no neighbors For a neighborless boid, temporaily increases a boid's p_range to the upper bound of proxim_bounds, else maintain at p_range.
def _extend_p_range(self) -> np.ndarray: mut_influence = self._perceive(self.p_range) neighborless = np.diagonal(mut_influence) return self.proxim_bounds[-1]*neighborless + self.p_range
[ "def bounded_prox(params, prox_step, proxmin, proxmax):\n cuts = params < proxmin\n params[cuts] = proxmin[cuts]\n cuts = params > proxmax\n params[cuts] = proxmax[cuts]\n return params", "def add_boundaries(self):\n\n bound_conns=[]\n bound_coords=[]\n bound_vert_index=[]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the boids' accleration by an acceleration delta.
def update_acc(self, acc_delta: np.ndarray, coeff: float) -> None: self.state[:, :, Boids.Attr.ACC] += acc_delta*coeff self.state[:, :, Boids.Attr.ACC] = maglim( self.state[:, :, Boids.Attr.ACC], self.max_acc)
[ "def accelerate_object(velocity, acceleration, dt):\n return change_vector(velocity, acceleration, dt)", "def apply_behaviour(self, boids, boids_in_radius):\r\n avg_velocity, center_of_mass, avg_vector, total = self.compute_in_radius(boids_in_radius)\r\n \r\n alignment = self.align(boids, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append a new rule to the boids' default behavioral rules appends a new rule to the boids' existing rule
def append_rules(self, *args: Tuple[Callable, float]) -> None: for rule, _ in args: setattr(Boids, rule.__name__, rule) self.rules.update({rule: coeff for (rule, coeff) in args})
[ "def append(self, rule):\n self.rules.append(rule)", "def add_rule(self, rule):\n self.rules.append(rule)", "def add_rule(self, rule):\n self.__rules__.append(rule)", "def add_rule(self, rule):\n \n self.rules.append(rule)", "def _add_rule(self, rule):\n self.rules_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates coefficient of rules
def update_coeff(self, **kwargs: float) -> None: for rule_name, coeff in kwargs.items(): if rule_name not in self.rules: raise ValueError(f"Behavioral rule {rule_name} does not exist") else: self.rules[getattr(self, rule_name)] = coeff
[ "def updateCoeff(self, **args):\n for par in args:\n self.rateCoeffMeta[par] = args[par]\n meta = self.rateCoeffMeta\n if self.rateCoeffMeta['type'] ==\"constant\":\n self.k = cp.k_const(meta['k'])\n elif self.rateCoeffMeta['type'] ==\"Arrhenius\":\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Limits the magnitude of the input matrix/vector along the 0th axis. This function will only activate if the magnitude of the input is greater than the specified limit.
def maglim(arr: np.ndarray, limit: float) -> np.ndarray: norm = np.linalg.norm(arr, axis=0) return arr / np.where(norm>limit, norm/limit, 1)
[ "def limit(self, upper_limit=None, lower_limit=None):\r\n magnitude = self.magnitude\r\n if upper_limit is None:\r\n upper_limit = magnitude\r\n if lower_limit is None:\r\n lower_limit = magnitude\r\n\r\n if magnitude < lower_limit:\r\n self.magnitude = l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the tag handler.
def _get_tag_handler(holder): return TagHandler(holder)
[ "def GetHandler(self, tag):\n return self._reg_handler.get(tag, None)", "def get_handler(self):\n return self._Handler(self)", "def getHandler(self):\n raise NotImplementedError(\"Shouldn't be called\")", "def get_handler(self):\n return self.connection_handle", "def handler(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search all objects having a given tag and optional category. Return all objects (characters, rooms) matching the search query, in no specific order.
def search(cls, tag_name: str, category: ty.Optional[str] = None ) -> ty.Set[db.Entity]: tags = cls.select(lambda t: t.name == tag_name) if category is not None: tags = tags.filter(category=category) objects = set() for tag in tags: for obj in tag.obj...
[ "def search_tag_all(tag):\n current_page = 0\n total = float(\"inf\")\n\n all_results = []\n while total > 0:\n response_json = search_tag(tag, current_page)\n try:\n total = response_json[\"Pagination\"][\"total\"]\n for product in response_json[\"Products\"]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all the tags on this object, in the given category.
def with_category(self, category: str) -> list: return list(self.__holder.db_tags.filter( lambda t: t.category == category))
[ "def obj_categories(self):\r\n return self._tags", "def tag(self, category_tagger={}):\n self.tags.update(category_tagger)\n return self.tags", "def search(cls, tag_name: str, category: ty.Optional[str] = None\n ) -> ty.Set[db.Entity]:\n tags = cls.select(lambda t: t.name ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles a request to a grit application by feeding it through the pipeline set up in the application config. The final element of the pipeline is typically the Dispatcher, which dispatches the request either to a subapplication or a request handler. Other pipeline elements are . TxWrapper, which initializes the databas...
def handle_request(request, *args, **kwargs): root = request.route.grit_params["root"] logger.info("WSGIApplication::handle_request path: %s method: %s", request.path_qs, request.method) reqctx = RequestCtx(request, request.response, kwargs) def run_pipeline(l): if l: handler_cls = ...
[ "def process_request(self, req, _):\n req.context.connection = self._engine.connect()", "def __call__(self, *args, **kwargs):\n request = flask.request\n return self.handler(request)", "def __call__(self, request):\n\n return self.bind(request)", "def __call__(self, scope):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Node advertises a Node type mDNS announcement with ver_ TXT records in the absence of a Registration API
def test_01(self, test): api = self.apis[NODE_API_KEY] if CONFIG.DNS_SD_MODE != "multicast": return test.DISABLED("This test cannot be performed when DNS_SD_MODE is not 'multicast'") ServiceBrowser(self.zc, "_nmos-node._tcp.local.", self.zc_listener) # Wait for n s...
[ "def _Announce(self):\n key = self._GetServerKey(self.peer_id)\n logging.debug('Encrypting announcement.')\n value = self._Encrypt('%s:%d' % (self.host, self.port))\n logging.debug('Posting announcement.')\n self._dht.Put(key, value)", "def test_adddnsrecord(kasserver, kasapi):\n kasserver.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the IO pins direction of use as either input or output. If resistor is not None, only an output direction on the pin can be used.
def set_dir(self, dir, resistor=None): self.IN = mraa.DIR_IN self.OUT = mraa.DIR_OUT self.PULL_UP = mraa.DIR_OUT_HIGH self.PULL_DOWN = mraa.DIR_OUT_LOW if dir not in (mraa.DIR_OUT, mraa.DIR_IN): # incorrect arguments passed in raise Exception("Incorrect pi...
[ "def set_direction(self, pins, direction):\n self._controller.set_gpio_direction(pins, direction)", "def set_gpio_direction(self, pins, direction):\n with self._lock:\n if pins & self._spi_mask:\n raise SpiIOError('Cannot access SPI pins as GPIO')\n mask = self._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute document indexing with given options
def execute_(options): # initialize configuration config = Configuration() # set formatting and redirect logger output to console (stdout) fmt = logging.Formatter("%(asctime)s: [ %(message)s ]", "%m/%d/%Y %I:%M:%S %p") console = logging.StreamHandler() console.setFormatter(fmt) logger = log...
[ "def index_documents(DomainName=None):\n pass", "def option_search(args):\n print(\"= SEARCH =\")\n print()\n print(\"Index file:\\t\\t{}\".format(args.indexfile))\n print(\"QE enabled:\\t\\t{}\".format(args.queryexpansion))\n if not os.path.exists(args.indexfile):\n raise OSError(\"No su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses a speed in N.NNx format
def parse_speed(as_str: str) -> float: return float(as_str.rstrip("x"))
[ "def _parse_speed(self):\n\n # We are not going to use speed so we don't care about its value.\n field = SampleFields.SPEED\n offset = 7\n speed = int(self._next_bits(7), 2)\n\n if self._is_frozen(field):\n offset = 0\n speed = 0\n\n is_full = self._ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes the fd with the given number unbuffered
def unbuffer_fd(fileno: int): fcntl.fcntl(fileno, fcntl.F_SETFL, fcntl.fcntl(fileno, fcntl.F_GETFL) | os.O_NONBLOCK)
[ "def setNonBlocking(fd):\n\n import fcntl\n\n flags = fcntl.fcntl(fd, fcntl.F_GETFL)\n flags = flags | os.O_NONBLOCK\n fcntl.fcntl(fd, fcntl.F_SETFL, flags)", "def __setNonBlocking(fd):\n flags = fcntl.fcntl(fd, fcntl.F_GETFL)\n flags = flags | os.O_NONBLOCK\n fcntl.fcntl(fd, fcnt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses log lines and try to find the most recent progress log
def process_logs(lines: Sequence[str]) -> Optional[Progress]: for line in reversed(lines): raw_status = dict(PROGRESS_RE.findall(line)) if raw_status: LOGGER.debug(raw_status) try: return Progress.from_raw_dict(raw_status) ...
[ "def parselog(filen, progress=0):\n\n # Process a file and return a populated logfile object\n #\n # Maximum size of text buffer to use\n bufsize = 50\n # Initial size of chunks to process\n chunksize = 50\n # Regular expression object\n regex = patternmatch()\n # Buffer objects\n buff...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a stop signal the running ffmpeg process. Raises `RuntimeError` if ffmpeg is not running.
def stop(self): if not self.ffmpeg: raise RuntimeError("ffmpeg is not running") self.ffmpeg.send_signal(signal.SIGINT)
[ "def async_stop_ffmpeg(self):\n return self.ffmpeg.close()", "def stop(self):\n if self._proc_is_alive():\n\n if os.name == 'nt':\n # os.killpg is not available on Windows\n # See: https://bugs.python.org/issue5115\n self._proc.kill()\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nearest neighbor algorithm. A is an NxN array indicating distance between N locations start is the index of the starting location Returns the path and cost of the found solution
def NN(A): A = np.array(A) path = [0] cost = 0 N = A.shape[0] mask = np.ones(N, dtype=bool) # boolean values indicating which # locations have not been visited mask[0] = False for i in range(N-1): last = path[-1] next_ind = np.argmin(A[la...
[ "def NN(A, start):\n path = [start]\n cost = 0\n N = A.shape[0]\n mask = np.ones(N, dtype=bool) # boolean values indicating which \n # locations have not been visited\n mask[start] = False\n\n for i in range(N-1):\n last = path[-1]\n next_ind = np.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize and sync config with trains
def update_config(config: OmegaConf): # expected config_global format schema = OmegaConf.structured(config._metadata.object_type) # serialize config # For config logging we use yaml format (Trains: Artifacts -> Model configuration) # save config in a temp yaml file config_global_file = tempfil...
[ "def save_config(self):\n try:\n print(\"Clearing active users\")\n for room in self.rooms:\n room.room_attrbts['active'].clear()\n print('Saving config...')\n print(\"Known clients:\")\n self.pp.pprint(self.clients)\n print(\"K...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main test program calculates score for program. It first tests the getEuler method on graphs in test files. Then tests it on randomly generated undirected simple graphs.
def main(): dirPath = "./tests/" score = 0 # Run test files to check correctness print("\n======================= TEST CORRECTNESS =======================\n") print("\n------- There are no Euler circuits in the first two tests -----\n") score += 4 - testInput(dirPath + "disconnected", 0) ...
[ "def main():\r\n test = TesterNeighbour()\r\n test.setUp()\r\n test.test_result_n()\r\n print(\"result_of_algorithm_test - passed\")", "def testDriver():\n exam1=90\n exam2=85\n assignmentScores = [50, 60, 70, 80, ]\n computeGrades(exam1, exam2, assignmentScores)", "def test_server():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the getEuler method for a graph. Prints the results.
def testOnGraph(graph): print("Graph has " + str(graph.totalVertices()) + " vertices, and " + str(graph.totalEdges()) + " edges.") circuit = graph.findEuler if (circuit is None): print("Graph has no Euler Circuit") return 0 elif (isValidEuler(graph, circuit)): print("Va...
[ "def FindEulerCycle(self):\n\n if self.IsEulerGraph():\n nodes_copy = [n for n in self.nodes]\n edges_copy = [e for e in self.edges]\n connections_copy = [(a, b) for (a, b) in self.connections]\n euler_cycle = list()\n\n starting_node_index = random.rand...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies whether a walk is a valid Euler circuit for a graph.
def isValidEuler(graph, circuit): # First check if the path is a circuit if not circuit.isCircuit(): print("Error: Path returned is not a circuit") return False # Then check if the circuit has the correct number of edges circuitLength = circuit.length() totalEdges = graph.totalEdge...
[ "def testOnGraph(graph):\n print(\"Graph has \" + str(graph.totalVertices())\n + \" vertices, and \" + str(graph.totalEdges()) + \" edges.\")\n circuit = graph.findEuler\n if (circuit is None):\n print(\"Graph has no Euler Circuit\")\n return 0\n elif (isValidEuler(graph, circuit)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms dict to flatten structure by join all dict keys with ``sep`` until MutableMapping occurs.
def flatten(d: MutableMapping, sep: str = ".", parent_key: str = "") -> dict: items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): items.extend(flatten(v, sep=sep, parent_key=new_key).items()) else: ...
[ "def expand_dict(dictionary: dict, separator=\"_\") -> List[str]:\n tempList = []\n for key, value in dictionary.items():\n if type(value) == dict:\n tempList.extend([key+separator+item for item in expand_dict(value)])\n else:\n tempList.append(key)\n\n return tempList",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function used to test main menu console display
def main_menu_for_testing(): print(PROMPT_TEXT)
[ "def main_menu():\n print()\n print(\"Menu Options:\")\n print(\"-------------\")\n print(\"Enter \\\"A\\\" for analysis\\nEnter \\\"H\\\" for help\\nEnter \\\"Q\\\" to quit\")", "def helpmenusautomatictesting(self):\n self.rdmc.ui.printer(\n \"\\n************************************...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to get price
def getprice(): print("Get price") latest_price = get_latest_price(item_code) return latest_price
[ "def retrievePrice(self):\n pass", "def getTotalPrice():", "def getPrice(self):\r\n return self.getFieldVal(self.PRICE)", "def get_price(self):\n return self.price", "def get_price(item):\n return float(item[1])", "def getCryptoPrice():\n\tpass", "def itemPrice(self):\n\t\tphone_pri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function adds an item that's neither furniture nor an applicance
def add_non_furniture_nor_appliance(itemcode, itemdescription, itemprice, itemrentalprice): newitem = Inventory(itemcode, itemdescription, itemprice, itemrentalprice) FULLINVENTORY[itemcode] = newitem.returnasdictionary()
[ "def test_add_already_present(self):\n food_item = self.create_a_food_item()\n # remove an entry from the frozen\n self.shelves['frozen'].food_dict.popitem()\n rc = process_new_item(self.shelves, food_item)\n self.assertEqual(rc, NewItemStatus.ok)\n food_item_dup = self.cre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function adds a new piece of furniture
def add_furniture(itemcode, description, marketprice, rentalprice): material = input("Enter item material: ") size = input("Enter item size (S,M,L,XL): ") newitem = Furniture(itemcode, description, marketprice, rentalprice , material, size) FULLINVENTORY[...
[ "def add_furniture_to_room(self):\n #\n # This addFurnitureToRoom method is implemented for you.\n # Do not change it.\n #\n # Generate the size (both width and length) of the furniture. The\n # furniture size cannot exceed the room's width and height\n #\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function adds a new appliance
def add_appliance(itemcode, description, marketprice, rentalprice): itembrand = input("Enter item brand: ") itemvoltage = input("Enter item voltage: ") newitem = ElectricAppliances \ (itemcode, description, marketprice, rentalprice, itembrand, itemvoltage) FULLINVENTORY[itemcode] = ne...
[ "def post_service_appliance_create(self, resource_dict):\n pass", "def post_service_appliance_set_create(self, resource_dict):\n pass", "def pre_service_appliance_create(self, resource_dict):\n pass", "def post_service_appliance_update(self, resource_id, resource_dict):\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function gets item information from user input.
def iteminfo(): itemcode = input("Enter item code: ") if itemcode in FULLINVENTORY: printdict = FULLINVENTORY[itemcode] for key, value in printdict.items(): print("{}:{}".format(key, value)) else: print("Item not found in inventory")
[ "def item_info():\n item_code = get_input(\"Enter item code: \")\n if item_code in FULL_INVENTORY:\n print_dict = FULL_INVENTORY[item_code]\n output = \"\"\n for key, value in print_dict.items():\n output += (\"{}:{}{}\".format(key, value, \"\\n\"))\n else:\n output =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to exit the program
def exitprogram(): sys.exit()
[ "def exit_program():\n quit()", "def quit_program():\n sys.exit()", "def exit_program():\n print(\"Good Bye! Happy Searching...\")", "def quit():\n sys.exit()", "def quit_program():\n quit()", "def program_close():\n\n print(\"\\n\")\n sys.exit(0)", "def exit(self, *args):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for training an agent on a simplified version of blackjack with a passive dealer. noOfDecks is the number decks the agents trains with sampleSpaceSearching specifies the sampleSpaceExploitation specifies the method can be one of QL, TD, SARSA gamma is the discount factor qTable has None set as default, if usin...
def agentTraining(noOfDecks, sampleSpaceSearching, sampleSpaceExploitation, method, gamma, qTable=None): deckSize = noOfDecks*52 optimalScore = 0 # winning score and losing Score egreedyScore = 0 pO = [0,0...
[ "def train_many(command, drinks = {'none':'none'}, flavors = ['none']):\n try:\n flavors.remove('flavor_strength') #don't need to train for flavor_strength\n except:\n pass\n stt = stt_google\n amounts = ['0.1', '-0.1']\n filenames = ['command_training.csv', 'drink_training.csv', 'flavo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load T5 model to generate a summarization given a string.
def t5(model: str = 'base', **kwargs): model = model.lower() if model not in _t5_availability: raise Exception( 'model not supported, please check supported models from malaya.summarize.available_t5()' ) path = PATH_SUMMARIZE['argmax'] s3_path = S3_PATH_SUMMARIZE['argmax'] ...
[ "def t5(model: str = 'base', compressed: bool = True, **kwargs):\n\n model = model.lower()\n if model not in _t5_availability:\n raise Exception(\n 'model not supported, please check supported models from malaya.summarization.abstractive.available_t5()'\n )\n\n from malaya.model.t5...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test navigation stops at a skip table
def test_fkey_nav_stops_on_skip(dumper, db): dumper.reader.load_db( db.create_sample( 5, fkeys=[ ("table1", "t2id", "table2", "id"), ("table2", "t3id", "table3", "id"), ("table3", "t4id", "table4", "id"), ], ) ) ...
[ "def verify_skip(self, d_stmt, table): \n pass", "def test_should_skip(self):\n pass", "def skip(self):\n self.click_back_button()", "def test_skip_list_no_skip(self):\n mock_sqr = SequenceRun()\n mock_sqr.instrument_run_id = TestConstant.instrument_run_id.value\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that table4 gets two referrers.
def test_two_referrers(dumper, db): dumper.reader.load_db( db.create_sample( 5, fkeys=[ ("table1", "t2id", "table2", "id"), ("table1", "t3id", "table3", "id"), ("table2", "t24id", "table4", "id"), ("table3", "t34id", "ta...
[ "def test_table_reference(self):\n networktables_mock = unittest.mock.Mock()\n table_mock = unittest.mock.Mock()\n # When table is gotten from first network, table will be None,\n # from second network will return table_mock\n networktables_mock.getTable.side_effect = [None, tabl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps a `TextResponse` to a `ScrapyYelpItem` instance.
def _handle_search_results(self, response: TextResponse) -> ScrapyYelpItem: # get yConfig pattern = re.compile(r"""\n\s+yConfig\s+=\s+""", re.MULTILINE | re.DOTALL) soup = BeautifulSoup(response.text, "html.parser") script = soup.find("script", text=pattern) myjson = script.get_...
[ "def read_item(text: Text):\n\n predictions = predict([[text.title], [text.body]])\n\n return predictions", "def process_response(self, response, crawler, downloader):\n return response", "def parse_lyrics(self, response, song_id):\n data = {}\n\n raw_lyrics = response.xpath('//div[@c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a tximport job for all eligible experiments.
def run_tximport(): eligible_experiments = ( Experiment.objects.annotate(num_organisms=Count("organisms")) .filter(num_organisms=1, technology="RNA-SEQ", num_processed_samples=0) .prefetch_related("samples__results") ) paginator = Paginator(eligible_experiments, PAGE_SIZE) page ...
[ "def import_action(modeladmin, request, queryset):\n for import_model in queryset:\n import_model.import_data(async_process=True)\n modeladmin.message_user(request, _(\"Launched import consignments tasks...\"))", "def setup_jobs(self):\n transfer_args = [\"analysis_type\", \"perturbation\", \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This command just calls run_tximport. The functionality has been broken out into a separate function to make testing easy.
def handle(self, *args, **options): run_tximport()
[ "def run_tximport():\n eligible_experiments = (\n Experiment.objects.annotate(num_organisms=Count(\"organisms\"))\n .filter(num_organisms=1, technology=\"RNA-SEQ\", num_processed_samples=0)\n .prefetch_related(\"samples__results\")\n )\n\n paginator = Paginator(eligible_experiments, PA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the eigenvalues such that they are no smaller than a specific fraction (specified by 'tolerance') than the leading eigenvalue. Calculation of eigenvalues is done using power method.
def runpower(matrix, n, tolerance, max_num=None, return_vector=True): calculate_next = True eigenvalue_list = [] eigenvector_list = [] leading_eigenvalue = np.nan while(calculate_next): new_eigenvalue, v = runpower_one(matrix, n) if np.isnan(leading_eigenvalue): leading_eigenvalue = new_eigenvalue eigenv...
[ "def eigenvalues(self, constraints='original'):\n\n if self.solved:\n eigsAll = []\n ASize = 0\n\n if self.boundR != None:\n if (constraints == 'all') | (constraints == 'bounded'):\n eigs = eigvalsh(self.resultA[-1])\n eigsAll.extend(eigs)\n if (constraints == 'all'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the generate of this V1Parameter. Generate specifies the generator to be used to generate random string from an input value specified by From field. The result string is stored into Value field. If empty, no generator is being used, leaving the result Value untouched. Optional.
def generate(self): return self._generate
[ "def get_generating_function(self):\n return self._generating_function", "def get_random(self):\n base_genom = \"1\" * sum(self._size_var)\n return utils.randomise_a_string(base_genom)", "def generate_value(self, variable):\n\t\tif variable in self._generators:\n\t\t\treturn self._generator...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the generate of this V1Parameter. Generate specifies the generator to be used to generate random string from an input value specified by From field. The result string is stored into Value field. If empty, no generator is being used, leaving the result Value untouched. Optional.
def generate(self, generate): self._generate = generate
[ "def set_generator(self, gen):\n self.generator = gen", "def generate_token(self, generate_token):\n\n self._generate_token = generate_token", "def generate_name(self, generate_name):\n\n self._generate_name = generate_name", "def generate_date(self, generate_date):\n self._generat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the required of this V1Parameter.
def required(self): return self._required
[ "def get_mandatory_param(self):\n mandatory_params = [k for k, v in self.validation_rule.get('fields').items()\n if self.validation_rule.get(k).get('required') is not None]\n\n return mandatory_params if mandatory_params else None", "def requires_value(self):\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
performs bee latin on a word
def latinize_word(word): if word[0].lower() in 'bcdfghjklmnpqrstvwxyz': word = word[1:] + word[0] + 'uzz' else: word += 'buzz' return word.lower()
[ "def pig_latin(word):\n if word[0] in 'aeiou':\n return word+'hay'\n else:\n return word[1:]+word[0]+'ay'", "def get_pig_latin_word(word):\n #To check the words that start with this combination\n #of their first two characters\n consonant_combination_list = ['sh', 'gl', 'c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
performs bee latin on a sentence
def latinize_sentence(sentence): words = sentence.split() latanized_words = [latinize_word(word) for word in words] return " ".join(latanized_words)
[ "def convert_to_latin(input_text):\n # caps\n input_text = input_text.replace(\"А\", \"a\")\n input_text = input_text.replace(\"Б\", \"b\")\n input_text = input_text.replace(\"В\", \"v\")\n input_text = input_text.replace(\"Г\", \"g\")\n input_text = input_text.replace(\"Д\", \"d\")\n input_tex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
visualization the curves of accuracies for 4 groups of data
def ridge_cross_validation_visualization(lambdas, accuracies): colors = ['r', 'b', 'y', 'g'] labels = ['group_0', 'group_1', 'group_2', 'group_3'] for i in range(len(accuracies)): plt.semilogx(lambdas, accuracies[i], marker=".", color=colors[i], label=labels[i]) plt.xlabel("lambda") plt.ylab...
[ "def poly_cross_validation_visualization(polys, accuracies):\n colors = ['r', 'b', 'y', 'g']\n labels = ['group_0', 'group_1', 'group_2', 'group_3']\n for i in range(len(accuracies)):\n plt.plot(polys, accuracies[i], marker=\".\", color=colors[i], label=labels[i])\n plt.xlabel(\"degree\")\n pl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
visualization the curves of accuracies for 4 groups of data
def poly_cross_validation_visualization(polys, accuracies): colors = ['r', 'b', 'y', 'g'] labels = ['group_0', 'group_1', 'group_2', 'group_3'] for i in range(len(accuracies)): plt.plot(polys, accuracies[i], marker=".", color=colors[i], label=labels[i]) plt.xlabel("degree") plt.ylabel("accur...
[ "def ridge_cross_validation_visualization(lambdas, accuracies):\n colors = ['r', 'b', 'y', 'g']\n labels = ['group_0', 'group_1', 'group_2', 'group_3']\n for i in range(len(accuracies)):\n plt.semilogx(lambdas, accuracies[i], marker=\".\", color=colors[i], label=labels[i])\n plt.xlabel(\"lambda\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a code challenge based on the code verifier
def code_challenge(verifier): digest = hashlib.sha256(verifier).digest() return base64.urlsafe_b64encode(digest).rstrip(b'=')
[ "def gen_code_challenge(code_verifier: str) -> bytes:\n sha256 = hashlib.sha256(code_verifier.encode())\n encoded = urlsafe_b64encode(sha256.digest())\n return encoded.rstrip(b'=')", "def gen_code_verifier(length: int = 128) -> str:\n choices = 'abcdefghijklmnopqrstuvwxyz' \\\n 'ABCDEFGHI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Basic login page with an Authenticate with Okta button. Clicking the button creates an auth URL using the create_auth_url function
def login_page(): text = '<a href="%s">Authenticate with Okta</a>' return text % create_auth_url()
[ "def loginpage(self):\n self.client.get(\"/accounts/\")", "def login(self):", "def click_login_button(self):", "def login():", "def login():\n return render_template('auth/login.html')", "def login_page(self):\n self.validate_form(\"/login\", [\"username\", \"password\"])", "def auth_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This builds an auth url that Okta will accept for the Authorization Code Flow w/ PKCE Verification, the most secure method of auth Okta currently supports.
def create_auth_url(): state = secrets.token_hex(16) nonce = secrets.token_hex(16) credentials = { 'response_type': 'code', 'redirect_uri': REDIRECT_URI, 'client_id': CLIENT_ID, # Define your app scopes here. If you're building an OIDC app you'll # want to stick to th...
[ "def auth_url(self, url):\n\n if self.authenticated:\n return url + '&api_key=' + self.api_key\n else:\n return url", "def get_auth_url():\n\n auth = AuthURL()\n director = URLDirector()\n director.construct_url(auth)\n\n return auth.url", "def get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Okta API call to get all groups in the Okta instance
def list_groups(access_token): request_url = OKTA_URL + "api/v1/groups" headers = {"Authorization": "Bearer " + access_token} group_request = requests.get(request_url, headers=headers).json() return group_request
[ "def list_groups():\n init_dao(env('client_id'), env('client_secret'), env('tenant_id'))\n return Response(get_all_groups(r.args.get('since'),r.args), content_type=CT)", "def get_all_groups(self) -> APIResponse:\n return self._get(\"list\")", "def test_get_api_group_list(self):\n pass", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle GET requests for single bug/ticket type
def retrieve(self, request, pk=None): try: bug_type = BugType.objects.get(pk=pk) serializer = BugTypeSerializer(bug_type, context={'request': request}) return Response(serializer.data) except Exception as ex: return HttpResponseServerError(ex)
[ "def retrieve(self, request, pk=None):\n try:\n # `pk` is a parameter to this function, and\n # Django parses it from the URL route parameter\n # http://localhost:8000/bugs/2\n #\n # The `2` at the end of the route becomes `pk`\n bug = Bug.o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle GET requests to get all bug/ticket types
def list(self, request): bug_types = BugType.objects.all() # Note the additional `many=True` argument to the # serializer. It's needed when you are serializing # a list of objects instead of a single object. serializer = BugTypeSerializer( bug_types, many=True, conte...
[ "def request_issue_types(cfg):\n url = cjm.request.make_cj_url(cfg, \"issuetype\")\n return cjm.request.make_cj_request(cfg, url).json()", "def get_all_ticket_by_type(request):\n user_id = request.POST.get(\"user_id\") # 用户user_id\n status = request.POST.get(\"status\") # 单条任务完成情况\n type = reques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle PUT requests for a bug types
def update(self, request, pk=None): bug_type = BugType.objects.get(pk=pk) bug_type.label = request.data["label"] bug_type.save() # 204 status code means everything worked but the # server is not sending back any data in the response return Response({}, status=status.HTTP...
[ "def put(self):\n type_model = request.json\n\n type_model = namedtuple(\"Type\", type_model.keys())(*type_model.values())\n repository = TypeRepository(\n FLASK_APP.config[\"DBUSER\"],\n FLASK_APP.config[\"DBPASS\"],\n FLASK_APP.config[\"DBHOST\"],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle DELETE requests for a single bug_types
def destroy(self, request, pk=None): try: bug_type = BugType.objects.get(pk=pk) bug_type.delete() return Response({}, status=status.HTTP_204_NO_CONTENT) except BugType.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NO...
[ "def delete_type_exercise():\n request_body = request.json\n id_tipo_ejercicio = request_body['id_tipo_ejercicio']\n try:\n type_exercise = type_exercise_service.get_by_id(id_tipo_ejercicio)\n if type_exercise:\n type_exercise_service.delete_exercise(type_exercise)\n res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_create
def test_dashboards_v2_create(self): pass
[ "def test_dashboards_v2_show(self):\n pass", "def create_dashboard(self, save=True, **kwargs):\n index = self.object_index()\n if not kwargs: kwargs = dict(name=\"Test Dashboard %s\" % index, slug=\"test-dashboard-%s\" % index)\n d = Dashboard(**kwargs)\n\n if not save: return d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_delete
def test_dashboards_v2_delete(self): pass
[ "def test_dashboard_delete_dashboard(self):\n pass", "def test_dashboards_v2_delete_share(self):\n pass", "def test_alerts_delete(self):\n pass", "def test_delete_activity_admin(self):\n self.login_admin()\n res = self.delete_activity()\n\n assert 'Deletion successful...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_delete_share
def test_dashboards_v2_delete_share(self): pass
[ "def test_remove_share(self):\n self.app.delete(url=\"/config/shares?share=80&destination=gsiftp://nowhere&vo=dteam\", status=400)\n self.app.delete(url=\"/config/shares?share=80&destination=gsiftp://nowhere&vo=dteam&source=gsiftp://source\", status=204)", "def test_dashboards_v2_share(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_link
def test_dashboards_v2_link(self): pass
[ "def test_dashboards_v2_show(self):\n pass", "def test_link_list(self):\n response = self.client.get('/tests/dashboard/')\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"example.com\")", "def test_dashboards_v2_share(self):\n pass", "def test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_list
def test_dashboards_v2_list(self): pass
[ "def test_dashboard_get_all_dashboards(self):\n pass", "def test_dashboards_v2_show(self):\n pass", "def test_dashboard_get_one_dashboard(self):\n pass", "def test_dashboards_v2_create(self):\n pass", "def test_dashboards_v2_link(self):\n pass", "def test_dashboards_v2_u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_list_shares
def test_dashboards_v2_list_shares(self): pass
[ "def test_dashboards_v2_share(self):\n pass", "def display_shares(self):\n\t\tassert False, \"Not yet implemented\"", "def list_shares_with_detail(self, params=None):\n return self.list_shares(detailed=True, params=params)", "def test_index_nas_shares(self):\n pass", "def get_shares_lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_request_access
def test_dashboards_v2_request_access(self): pass
[ "def test_get_access_resource(self):\n pass", "def test_user_get_specific_request(self):\n request_resource = self.client().get(\n '/api/v2/users/requests/1', headers=self.headers)\n data = json.loads(request_resource.data.decode())\n requests = data['request']\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_share
def test_dashboards_v2_share(self): pass
[ "def test_dashboards_v2_list_shares(self):\n pass", "def test_update_dashboard_sharing(self):\n pass", "def test_dashboards_v2_delete_share(self):\n pass", "def test_search_dashboard_sharing(self):\n pass", "def test_test_result_nas_share(self):\n pass", "def test_show_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_show
def test_dashboards_v2_show(self): pass
[ "def test_dashboards_v2_list(self):\n pass", "def test_dashboard_get_one_dashboard(self):\n pass", "def test_dashboard_get_all_dashboards(self):\n pass", "def test_dashboards_v2_create(self):\n pass", "def test_dashboards_v2_link(self):\n pass", "def test_dashboard_page(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for dashboards_v2_update
def test_dashboards_v2_update(self): pass
[ "def test_dashboard_update_dashboard(self):\n pass", "def test_update_dashboard(self):\n pass", "def test_dashboard_partially_update_dashboard(self):\n pass", "def test_update_dashboard_panel(self):\n pass", "def test_update_dashboard_panel_setting(self):\n pass", "def t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialise the lists where the loss of training and validation will be saved.
def on_train_begin(self, logs={}): self.losses = [] self.val_losses = []
[ "def _initLosses(self):\n self.lossTracker = lossTracker(self.datasets)", "def store_training_validation_file_list(data_paths, save_dir, train_num,\n logger):\n training_dir = data_paths[0]\n validation_dir = data_paths[1]\n\n save_list = os.path.join(save_di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
At the end of each epoch calculate NDCG of the validation set. If the model performance is improved, the model weights are saved. Update the list of validation NDCG by adding obtained value
def on_epoch_end(self, batch, logs={}): # recommend top k items based on training part of validation set top_k = self.recommend_k_items(x=self.val_tr, k=self.k, remove_seen=True) # convert recommendations from sparse matrix to dataframe top_k_df = self.mapper.map_back_sparse(top_k, kind...
[ "def on_validation_epoch_end(self) -> None:\n self.log_dict(self.val_metrics.compute())\n self.val_metrics.reset()", "def train_DCGAN():\n\n best_fid_score = 1000\n if os.path.exists('/content/drive/My Drive/DCGAN/best_fid_score.txt'):\n best_fid_score = float(next(open('best_fid.txt'))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialise a list in which the beta value will be saved at the end of each epoch.
def on_train_begin(self, logs={}): self._beta = []
[ "def on_epoch_end(self, epoch, logs={}):\n tmp = K.eval(self.beta)\n self._beta.append(tmp)", "def on_batch_end(self, epoch, logs={}):\n self.update_count = self.update_count + 1\n\n new_beta = min(\n 1.0 * self.update_count / self.total_anneal_steps, self.anneal_cap\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
At the end of each batch the beta should is updated until it reaches the values of anneal cap.
def on_batch_end(self, epoch, logs={}): self.update_count = self.update_count + 1 new_beta = min( 1.0 * self.update_count / self.total_anneal_steps, self.anneal_cap ) K.set_value(self.beta, new_beta)
[ "def batch_sample_beta(self):\n\n # derive contexts from breakpoints arrangement\n cat_dict = self.get_category_flat_dict()\n for cat in cat_dict.keys():\n \n beta_indices = np.where(np.array(self.categories) == cat)[0]\n #print(beta_indices, cat, self.categorie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
At the end of each epoch save the value of beta in _beta list.
def on_epoch_end(self, epoch, logs={}): tmp = K.eval(self.beta) self._beta.append(tmp)
[ "def on_batch_end(self, epoch, logs={}):\n self.update_count = self.update_count + 1\n\n new_beta = min(\n 1.0 * self.update_count / self.total_anneal_steps, self.anneal_cap\n )\n\n K.set_value(self.beta, new_beta)", "def on_train_begin(self, logs={}):\n self._beta = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the value of the optimal beta.
def get_optimal_beta(self): if self.annealing: # find the epoch/index that had the highest NDCG@k value index_max_ndcg = np.argmax(self.val_ndcg) # using this index find the value that beta had at this epoch return self.ls_beta[index_max_ndcg] else: ...
[ "def update_beta(self, beta):\n\n if self._safeguard:\n beta *= self.xi_restart\n beta = max(beta, self.min_beta)\n\n return beta", "def nbeta(self) -> int:\n return self._core.nbeta()", "def get_beta(self, lbda):\n raise NotImplementedError", "def beta(self):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the topk items ordered by a relevancy score. Obtained probabilities are used as recommendation score.
def recommend_k_items(self, x, k, remove_seen=True): # return optimal model self.model.load_weights(self.save_path) # obtain scores score = self.model.predict(x) if remove_seen: # if true, it removes items from the train set by setting them to zero seen_...
[ "def get_item_based_topk(self, items, top_k=10, sort_top_k=False):\n\n # convert item ids to indices\n item_ids = items[self.col_item].map(self.item2index)\n\n # if no ratings were provided assume they are all 1\n if self.col_rating in items.columns:\n ratings = items[self.col...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the list of NDCG at each epoch.
def ndcg_per_epoch(self): return self.val_ndcg
[ "def GetEpochs(self):\r\n return self.GetLabelList(self.navpanel,'items')", "def epochs(self):\n # Return\n result = self._epochs\n return result", "def GetEpochs(self):\r\n return self.GetLabelList(self.obspanel, 'items')", "def getMJDs(self):\n return self.getEpochs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns weights and bias shapes at current layer
def get_shape_wb(self): return self.weights.shape, self.bias.shape
[ "def _canonical_bias_shape(self, unused_layer):\n return [self._num_gates_per_layer, self._num_units]", "def layer_weights(self):\n Ws = [layer.W for layer in self.layers]\n return Ws", "def __weights(self,layer, expected_layer_name):\r\n wb = self.__vgg_layers[0][layer][0][0][2]\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate an image from the specs of the given image ID. Typically this function loads the image from a file, but in this case it generates the image on the fly from the specs in image_info.
def load_image(self, image_id): info = self.image_info[image_id] # bg_color = np.array(info['bg_color']).reshape([1, 1, 3]) # image = np.ones([info['height'], info['width'], 3], dtype=np.uint8) # image = image * bg_color.astype(np.uint8) # for shape, color, dims in info['shapes']...
[ "def load_image(self, image_id):\n# logger.info(\"image {}\".format(image_id))\n info = self.image_info[image_id]\n if info[\"image\"] is None:\n im = self.gen_imgs[info[\"path\"]][\"input_images\"][info[\"image_index\"]]\n image = np.ones([info['height'], info['width'], 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate instance masks for num_categories of the given image ID.
def load_mask(self, image_id): info = self.image_info[image_id] num_cards = info['cards'] # count = len(num_cards) count = 1 # there will only ever be 1 card per image (for simplicity) TODO: do multiple documents? mask = np.zeros([info['height'], info['width'], count], dtype=np.u...
[ "def load_mask(self, image_id):\n instance_masks = []\n class_ids = []\n\n # Get image metadata and annotations from the provided ID.\n image_info = self.image_info[image_id]\n annotations = self.image_info[image_id][\"annotations\"]\n # Build mask of shape [height, width, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates random specifications of an image containing a document. Returns whether the image is real or synthetic, and a collection of specifications that can be used to draw/load the image.
def random_image(self, height, width): random_image_properties = {} # flip a coin to determine whether image should be synthetic or real if random.random() < self.prob_real: random_image_properties['real'] = True # select a random row from the list of filenames ...
[ "def detect_expected(self,image,priors):\n # first, generate an image that is like this image, according to the priors\n synthetic_image = Image.generate_like(image,priors)\n # then do synthetic detection in this image", "def random_image():\n\n # select random photo from sample table\n result = db...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches a given directory for rule classes. This is done by finding all python modules in the given directory, adding them to the python path, importing them and then finding any Rule classes in those modules.
def find_rule_classes(extra_path): # Find all python files in the given path modules = [] for filename in os.listdir(extra_path): if fnmatch.fnmatch(filename, '*.py'): modules.append(os.path.splitext(filename)[0]) # No need to continue if there are no modules specified if len(m...
[ "def discover_rule_classes(self, rule_directory):\n if self.debug:\n print('CustomRuleLoader - discover_rule_classes'+str(lineno()))\n print('rule_directory: '+str(rule_directory))\n\n rule_classes = []\n\n rule_filenames = self.discover_rule_filenames()\n\n for dir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse fb message archive csv to deepQA format.
def parse_to_deep_qa_args_parsing(subparsers): help_str = "Parse fb message archive csv to deepQA format." parser_t = subparsers.add_parser('parse_to_deep_qa', help=help_str) help_str = 'Facebook target user on which to parse trainable conversations\n' parser_t.add_argument('-u', '--user', required=Fals...
[ "def parse_csv(self):\n # delim = sys.argv[2]\n delim = ';'\n data_tmp = pandas.read_csv(self.filepath, delimiter=delim)\n rows_read = self.parse_data(data_tmp)\n print('created: ' + str(rows_read) + ' Questions with answers')", "def parse_csv(line: str) -> str: \n\n try:\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This command handler adds a given address to the find list and highlights it green in the UI
def find_instr(bv: BinaryView, addr: int): # Highlight the instruction in green highlight_instr(bv, addr, HighlightStandardColor.GreenHighlightColor) # Add the instruction to the list associated with the current view bv.session_data.mui_find.add(addr)
[ "def addaddr( addr ):\n\t\tif cmds:\n\t\t\tcmds.last().addrs.append( addr )\n\t\telse:\n\t\t\tlog.err( \"A command must preceed the first address\" )", "def addEntryPoint(self, address: ghidra.program.model.address.Address) -> None:\n ...", "def add(self, name, command):", "def __editAddress(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This command handler removes a given address from the find list and undoes the highlights
def rm_find_instr(bv: BinaryView, addr: int): # Remove instruction highlight clear_highlight(bv, addr) # Remove the instruction to the list associated with the current view bv.session_data.mui_find.remove(addr)
[ "def clear_highlighting(self):\n for match in vim.eval('getmatches()'):\n if match['group'] == 'PSearchMatches':\n vim.command(\"call matchdelete({0})\".format(match['id']))", "def removeAll(self, addr: ghidra.program.model.address.Address) -> None:\n ...", "def removeEnt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This command handler adds a given address to the avoid list and highlights it red in the UI
def avoid_instr(bv: BinaryView, addr: int): # Highlight the instruction in red highlight_instr(bv, addr, HighlightStandardColor.RedHighlightColor) # Add the instruction to the list associated with the current view bv.session_data.mui_avoid.add(addr)
[ "def whitelist_add(self, address: str) -> None:\n self._config['whitelist'].append(address)", "def add_address(self, address_item):\r\n self.addresses_to_validate.append(address_item)", "def add_addressitem(self, addressitem):\n self.addresses.append(addressitem)", "def add_address(self, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This command handler removes a given address from the avoid list and undoes the highlights
def rm_avoid_instr(bv: BinaryView, addr: int): # Remove instruction highlight clear_highlight(bv, addr) # Remove the instruction to the list associated with the current view bv.session_data.mui_avoid.remove(addr)
[ "def removeEntryPoint(self, address: ghidra.program.model.address.Address) -> None:\n ...", "def removeInstructionAt(self, address: ghidra.program.model.address.Address) -> None:\n ...", "def removeAll(self, addr: ghidra.program.model.address.Address) -> None:\n ...", "def blacklist_remov...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if avoid_instr is valid for a given address
def avoid_instr_is_valid(bv: BinaryView, addr: int): return addr not in bv.session_data.mui_avoid
[ "def find_instr_is_valid(bv: BinaryView, addr: int):\n return addr not in bv.session_data.mui_find", "def avoid_instr(bv: BinaryView, addr: int):\n\n # Highlight the instruction in red\n highlight_instr(bv, addr, HighlightStandardColor.RedHighlightColor)\n\n # Add the instruction to the list associate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if find_instr is valid for a given address
def find_instr_is_valid(bv: BinaryView, addr: int): return addr not in bv.session_data.mui_find
[ "def avoid_instr_is_valid(bv: BinaryView, addr: int):\n return addr not in bv.session_data.mui_avoid", "def __contains__(self, address):\n return 0x0130 <= address <= 0x013f", "def perform_is_offset_executable(self, addr: int) -> bool:\n\t\treturn self.is_valid_offset(addr)", "def perform_is_valid_o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if solve is valid for a given binary view
def solve_is_valid(bv: BinaryView): return not bv.session_data.mui_is_running
[ "def isValid(self, aSolution):", "def check_if_solvable(self):\n\n self.solvable=True #status of sudoku\n for i in range(0, 9):\n for j in range(0, 9):\n if self.a[i][j]==0:\n continue\n if self.check(i, j)[self.a[i][j]]==0:\n self.solvable=False\n return F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }