query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Takes an elementtree Element ('poster') and stores the poster, using the size as the dict key.
def set(self, poster_et): size = poster_et.get("size") value = poster_et.text self[size] = value
[ "def set_poster(self, poster):\n self.poster = poster", "async def _poster(self, ctx, *, value=None):\r\n key = 'poster'\r\n # test key for url\r\n if ctx.message.server.id not in self.guilds:\r\n data = _unknown_guild(ctx)\r\n await self.bot.send_message(ctx.mess...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to return largest image.
def largest(self): for cur_size in ["original", "mid", "cover", "thumb"]: if cur_size in self: return self[cur_size]
[ "def _geometry_from_largest(img, size):\n w, h = geometry(img)\n if w > h:\n return size, _proportional_dim(w, size, h)\n else:\n return _proportional_dim(h, size, w), size", "def most_similar_image():\n most_similar_index = -1\n return most_similar_index", "def _get_best_streamer_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches for a film by its title. Returns SearchResults (a list) containing all matches (Movie instances)
def search(self, title): title = urllib.quote(title.encode("utf-8")) url = config['urls']['movie.search'] % (title) etree = XmlHandler(url).getEt() search_results = SearchResults() for cur_result in etree.find("movies").findall("movie"): cur_movie = self._parseMovie(c...
[ "def search_movies_by_title(title):\n\n searched_movies = []\n for movie in movie_dict.values():\n if title in movie.movie_title:\n searched_movies.append(movie.movie_title)\n return searched_movies", "def search_film(film_title=None, year=None, imdb_id=None,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the scoped ``Context`` for the current running ``Task``.
def activate(self, context, loop=None): loop = self._get_loop(loop) if not loop: self._local.set(context) return context # the current unit of work (if tasks are used) task = asyncio.Task.current_task(loop=loop) setattr(task, CONTEXT_ATTR, context) ...
[ "def set_context(self, context):\n success = win32.SetThreadContext(self.handle, win32.byref(context))\n if not success:\n raise win32.Win32Exception()", "def set(contextIn):\n global context\n context = contextIn", "def set_context(self, context):", "def jvm_context_manager(par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper to determine if we have a currently active context
def _has_active_context(self, loop=None): loop = self._get_loop(loop=loop) if loop is None: return self._local._has_active_context() # the current unit of work (if tasks are used) task = asyncio.Task.current_task(loop=loop) if task is None: return False ...
[ "def IsContextful(self) -> bool:", "def get_current_context():\n\n click_core_ctx = click.get_current_context()\n if click_core_ctx:\n return click_core_ctx.find_object(Context) or click_core_ctx.ensure_object(Context)\n\n return None", "def current():\n\n return Context.__cur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the scoped Context for this execution flow. The ``Context`` uses the current task as a carrier so if a single task is used for the entire application, the context must be handled separately.
def active(self, loop=None): loop = self._get_loop(loop=loop) if not loop: return self._local.get() # the current unit of work (if tasks are used) task = asyncio.Task.current_task(loop=loop) if task is None: # providing a detached Context from the current...
[ "def activate(self, context, loop=None):\n loop = self._get_loop(loop)\n if not loop:\n self._local.set(context)\n return context\n\n # the current unit of work (if tasks are used)\n task = asyncio.Task.current_task(loop=loop)\n setattr(task, CONTEXT_ATTR, co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set if the capturing is simulated
def setSimulatedMode(self, simulate:bool, path:str): self.Simulating = simulate self.SimulatingPath = path self.log(Messages.comp_setSimulateMode.format(self.ME_NAME, str(simulate)), LogTypes.INFO)
[ "def toggle_sim():\n\tglobal sim_on\n\tif sim_on == False:\n\t\tsim_on = True\n\telse:\n\t\tsim_on = False", "def is_simulator(self) -> bool:\r\n ...", "def toggle_simulation(self):\n enabled = self.ui.simButton.isChecked()\n self.ui.resetButton.setEnabled(enabled)\n\n if enabled:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run ditaa with plaintext input. Return relative path to the generated image.
def generate_diagram(plaintext): imgpath = generate_image_path(plaintext) srcfd, srcfname = tempfile.mkstemp(prefix="ditaasrc", text=True) outfd, outfname = tempfile.mkstemp(prefix="ditaaout", text=True) with os.fdopen(srcfd, "w") as src: src.write(plaintext) try: cmd = DITAA_CMD.form...
[ "def buildDds(fpath, tex):\n w, h = tex.get_dimensions()\n tp = textypes.get(tex.textype, None)\n if tp is None:\n raise ValueError(\"Unknown textype(=%i) for %s\" % (tex.textype, fpath))\n exe = bin_path(\"RawtexCmd.exe\")\n command = f\"{exe} {fpath} {tp} 0 {w} {h}\"\n rawtex = sp.Popen(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Upgrade DXF versions AC1012 and AC1014 to AC1015.
def upgrade_to_ac1015(dwg): def upgrade_layout_table(): if 'ACAD_LAYOUT' in dwg.rootdict: setup_model_space(dwg) # setup layout entity and link to proper block and block_record entities setup_paper_space(dwg) # setup layout entity and link to proper block and block_record entit...
[ "def upgrade_to_ac1009(dwg):\r\n add_upgrade_comment(dwg, dwg.dxfversion, 'AC1009 (R12)')\r\n dwg.dxfversion = 'AC1009'\r\n dwg.header['$ACADVER'] = 'AC1009'\r\n # as far I know, nothing else to do\r", "def update_controller_upgrade_flag(self, context):\n LOG.info(\"update_controller_upgrade_fl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Upgrade DXF versions prior to AC1009 (R12) to AC1009.
def upgrade_to_ac1009(dwg): add_upgrade_comment(dwg, dwg.dxfversion, 'AC1009 (R12)') dwg.dxfversion = 'AC1009' dwg.header['$ACADVER'] = 'AC1009' # as far I know, nothing else to do
[ "def upgrade_to_ac1015(dwg):\r\n def upgrade_layout_table():\r\n if 'ACAD_LAYOUT' in dwg.rootdict:\r\n setup_model_space(dwg) # setup layout entity and link to proper block and block_record entities\r\n setup_paper_space(dwg) # setup layout entity and link to proper block and block...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable 'handles' for DXF R12 to be consistent with later DXF versions. Write entitydbhandles into entitytags.
def enable_handles(dwg): def has_handle(tags, handle_code): for tag in tags.noclass: if tag.code == handle_code: return True return False def put_handles_into_entity_tags(): for handle, tags in dwg.entitydb.items(): is_not_dimstyle = tags...
[ "def add_handle(self, handle: str) -> None:\n self._entity_space.append(handle)", "def test_can_not_reset_entity_handle():\n db = EntityDB()\n entity1 = DXFEntity()\n entity2 = DXFEntity()\n db.add(entity1)\n db.add(entity2)\n handle = entity1.dxf.handle\n\n assert db.reset_handle(enti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Humanreadable string representation of DataType enum.
def toStr(dt): if dt == DataType.COLOR: return 'color' elif dt == DataType.MONOCHROME: return 'monochrome' elif dt == DataType.BOOL: return 'mask' elif dt == DataType.CATEGORICAL: return 'labels' elif dt == DataType.FLOW: ...
[ "def datatype(self) -> str:", "def getDataTypeName(self) -> unicode:\n ...", "def data_type_sql(self) -> str:\n if self.data_type == FieldDataType.NUMBER:\n return f\"{self.data_type.value} ({self.precision}, {self.scale})\"\n if self.data_type == FieldDataType.TEXT and self.leng...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns PIL's conversion mode for the corresponding data_type.
def pilModeFor(data_type, data=None): if data_type == DataType.COLOR: # Data may be single-channel, but the user requested us to treat # it like a RGB image. if data is None or len(data.shape) < 3 or data.shape[2] < 4: return 'RGB' else: ...
[ "def dtype(self):\n return self.pixel_type", "def get_image_mode(d: np.ndarray) -> str:\n if d.ndim != 3:\n raise ValueError(\"expected an array with 3 dimensions, received {d.ndim} dims\")\n if d.shape[0] == 3:\n mode = \"RGB\"\n elif d.shape[0] == 1:\n mode = \"L\"\n else...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map a global position, e.g. QCursor.pos(), to the corresponding pixel location.
def pixelFromGlobal(self, global_pos): return self._img_viewer.pixelFromGlobal(global_pos)
[ "def calc_pos(self, gridpos):\n x,y = gridpos\n x = self.x_offset + self.x_u * x\n y = self.y_offset + self.y_u * y\n return x, y", "def change_cursor_position (self) :\n\t\tmain_window = self.installed()\n\t\tif main_window is not None :\n\t\t\tx = float(str(self._xcoord.text() ) )\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Analyzes the internal _data field (range, data type, channels, etc.) and sets member variables accordingly. Additionally, information will be printed to stdout and shown on the GUI.
def __prepareDataStatistics(self): contains_nan = np.any(np.isnan(self._data)) contains_inf = np.any(np.isinf(self._data)) if contains_nan or contains_inf: # Prepare output string nonfin_str = '' if contains_inf: nonfin_str += 'Inf' ...
[ "def __analyze_dataset(self):\n info_file = os.path.join(self.work_dir, self.data_name + '_info.txt')\n\n #if not analyzed before, analyze\n if os.path.exists(info_file) == False :\n logging.info('analyze data %s' %(self.data_path))\n if pysol.analyze_data(self.data_path,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary of currently applied UI settings/attributes. This can be used to restore these settings after opening/displaying subsequent data via restoreDisplaySettings().
def currentDisplaySettings(self): settings = { 'win-size': self.size(), 'win-pos': self.mapToGlobal(QPoint(0, 0)), 'num-inspectors': len(self._inspectors) } inspection_widgets_settings = [insp.currentDisplaySettings() for insp in self._inspectors] sett...
[ "def get_global_attributes(self):\n \n # I don't like accessing the private _attributes variable, but I don't\n # see any other way to do this\n return self._file._attributes", "def createSettingsDict(self):\n self.settings = dict()\n # self.settings.update(self.pl['setti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reapplies the display settings previously obtained via currentDisplaySettings() where applicable. This means that if the data type changed in between, typespecific UI settings/attributes will not be restored.
def restoreDisplaySettings(self, settings): if settings is None: return self.resize(settings['win-size']) # Note that restoring the position doesn't always work (issues with # windows that are placed partially outside the screen) self.move(settings['win-pos']) ...
[ "def change_display_type(self, context):\n self.outputs[0].display_type = self.display_type\n for i in range(3):\n self.inputs[i].display_type = self.display_type\n if BLENDER_VERSION >= \"3.1\" and context:\n self.socket_value_update(context)", "def updatePropertiesWidg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a message to be displayed upon the status bar showing the data point at the cursor position. Requires result of _queryDataLocation as input.
def __statusBarMessage(self, query): s = query['pos'] + ', ' + query['dtypestr'] + ': ' + query['rawstr'] if query['currlayer'] is not None: s += ', Current layer: ' + query['currlayer'] if query['pseudocol'] is not None: s += ', Pseudocolor: ' + query['pseudocol'] ...
[ "def __tooltipMessage(self, query):\n s = '<table><tr><td>Position:</td><td>' + query['pos'] + '</td></tr>'\n s += '<tr><td>' + query['dtypestr'] + ':</td><td>' + query['rawstr'] + '</td></tr>'\n if query['currlayer'] is not None:\n s += '<tr><td>Layer:</td><td>' + query['currlayer']...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a HTML formatted tooltip message showing the data point at the cursor position. Requires result of _queryDataLocation as input.
def __tooltipMessage(self, query): s = '<table><tr><td>Position:</td><td>' + query['pos'] + '</td></tr>' s += '<tr><td>' + query['dtypestr'] + ':</td><td>' + query['rawstr'] + '</td></tr>' if query['currlayer'] is not None: s += '<tr><td>Layer:</td><td>' + query['currlayer'] + '</td>...
[ "def _tip_fn(x, y, data):\n # data_string:str = '\\n'.join([f\"{k}:\\t{str(v)}\" for k, v in zip(active_datapoint_column_names, data)])\n data_string:str = '\\n'.join([f\"{k}:\\t{str(v)}\" for k, v in asdict(data).items()])\n print(f'_tip_fn(...): data_string: {data_string}')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the index of the currently "active" inspection widget. If there are multiple inspection widgets, the one currently under the mouse is considered active. If no widget is under the mouse, this falls back to the first inspection widget.
def __getActiveInspector(self): for inspector_id in range(len(self._inspectors)): if self._inspectors[inspector_id].underMouse(): return inspector_id return 0
[ "def getCurrentIndex(self):\r\n for i in range(MpGlobal.Window.tabMain.count()):\r\n \r\n widget = MpGlobal.Window.tabMain.widget( i )\r\n \r\n if widget == self:\r\n return i\r\n \r\n raise IndexError(\"Tab not in TabBar. index out...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DESCRIPTION Allow a coarse grained structure to be visualized in pymol like an atomistic structure by drawing bonds and elastic network. Without a top/tpr file, this function only adds bonds between the backbone beads so they can be nicely visualized using line or stick representation. Adding a top/tpr file provides to...
def garnish(file="topol.top", selection='all', gmx=None, fix_elastics=1, guess_prot=1, show=1): fix_elastics = bool(int(fix_elastics)) guess_prot = bool(int(guess_prot)) show = bool(int(show)) # Retain order so pymol does not sort the atoms, giving a different result when saving the file cmd.set("r...
[ "def parse_bgp_file(filename, fileout):\n\n file = open(filename, 'r')\n desc = file.read().split('\\n')\n file.close()\n\n ases = []\n doshuffle = False\n bgp_string = \"from network_manager import *\\ntopo = EBGPTopo()\\n\"\n for line in desc:\n if len(line) == 0:\n continue...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a colored ERROR message
def error(message, label="ERROR: "): return colored(label + message, fg='red', style='bright')
[ "def red_err(message):\n return \"\\33[91m\" + message + \"\\33[0m\"", "def print_error(message):\n print(Fore.RED + message + Fore.RESET)", "def indicate_error():\n print_right('[' + c.red('ERROR') + ']', 8)", "def error(self, text):\n self.message('ERROR', text, color='red')", "def error(*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a colored CRITICAL message
def critical(message, label=""): return colored(label + message, fg='white', bg='red', style='bright')
[ "def critical_string(self, text):\n return \"%s[CRITICAL] %s%s%s%s\" % (self.HEADER, self.ENDCOLOR, self.CRITICAL, text, self.ENDCOLOR)", "def red_err(message):\n return \"\\33[91m\" + message + \"\\33[0m\"", "def critical(self, msg, raw=False):\n self._msg(('' if raw else 'CRITICAL: ') + str(m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can parse the units that we expect to be able to.
def test_parse_expected(): expected = [ "degC", "degF", "K", "g", "kg", "mg", "ton", "L", "mL", "inch", "ft", "mm", "um", "second", "ms", "hour", "minute", "ns", "g/cm^3", "g/mL", "kg/cm^3" ] for unit in expected: parse_units(unit)
[ "def test_Units_isvalid(self):\n self.assertTrue(Units(\"m\").isvalid)\n self.assertTrue(Units(\"days since 2019-01-01\").isvalid)\n self.assertTrue(\n Units(\"days since 2019-01-01\", calendar=\"360_day\").isvalid\n )\n\n self.assertFalse(Units(\"qwerty\").isvalid)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we cannot parse the units that we do not expect to.
def test_parse_unexpected(): unexpected = [ "rankine", "slug", "hand", "year", "St" ] for unit in unexpected: with pytest.raises(UndefinedUnitError): parse_units(unit)
[ "def test_bad_units(self):\r\n self.assertRaises(ValueError, convert_temperature, 0, 'C', 'R')\r\n self.assertRaises(ValueError, convert_temperature, 0, 'N', 'K')", "def test_Units_isvalid(self):\n self.assertTrue(Units(\"m\").isvalid)\n self.assertTrue(Units(\"days since 2019-01-01\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path.
def which(cmd, mode=os.F_OK | os.X_OK, path=None): def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # If we're given a path with a directory part, look it up directly rather # than referring to PATH directories. This includes che...
[ "def which(cmd, mode=os.F_OK | os.X_OK, path=None):\n # Check that a given file can be accessed with the correct mode.\n # Additionally check that `file` is not a directory, as on Windows\n # directories pass the os.access check.\n def _access_check(fn, mode):\n return (os.pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a list of files in a folder to PDF using `wkhtmltopdf`. If `xvfbrun` is present, the process is automatically parallelized
def convert_to_pdf(htmlfolder: str, filenames: List[str], outfolder: str = "./pdf/", cmd: str = "wkhtmltopdf") -> None: def _convert_file_parallel(filename: str): infile = htmlfolder + filename.replace(".Rmd", ".html") outfile = outfolder + filename.replace(".Rmd", ".pdf") # Return if provid...
[ "def application(request):\n if request.method != 'POST':\n return\n\n request_is_json = request.content_type.endswith('json')\n\n source_files = []\n # source_file = tempfile.NamedTemporaryFile(suffix='.html')\n \n payload = json.loads(request.data)\n\n pages = payload['contents']\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a boolean np array corresponding to where the floor is
def get_floor_map(m): am = m < 0 return am
[ "def bottomfloor(p):\n return p == 1", "def ifloor(x):\n\n return np.floor(x).astype(int)", "def topfloor(p):\n return p == 5", "def higherfloor(p1, p2):\n return p1-p2 > 0", "def flag_in_sight():\n my_sight = sight()\n for row in range(len(my_sight)):\n for col in range(len(my_sight[row]))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function that grabs the user id from a token. Ugly, merge with login_required somehow, without using session data
def get_user_id(): auth = request.headers.get('Authorization') if auth: try: auth_token = auth.split(" ")[1] except IndexError as e: current_app.logger.debug(e) auth_token = '' else: auth_token = '' if auth_token and not BlacklistToken.query.f...
[ "def get_user_id(token):\n\n user_name = get_user_name(token)\n\n if user_name is None:\n return None\n\n if user_name == \"Test\":\n user_name = \"superuser\"\n\n user = user_service.get_user_by_user_name(user_name)\n\n if user is None:\n return None\n\n return user[\"id\"]",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a boolean mask from sequence lengths.
def sequence_mask(lengths, max_len=None): if max_len is None: max_len = lengths.max().item() mask = torch.arange(0, max_len, dtype=torch.long).type_as(lengths) mask = mask.unsqueeze(0) mask = mask.repeat(1, *lengths.size(), 1) mask = mask.squeeze(0) mask = mask.lt(lengths.unsqueez...
[ "def mask(lengths):\n shape = lengths.shape\n\n lengths = lengths.view(-1)\n p = lengths.max()\n \n tensor = torch.zeros(p, lengths.shape[0])\n for i, l in enumerate(lengths):\n tensor[:l, i] = 1\n\n return tensor.view((p,) + shape)", "def get_mask_from_length(length):\n batch_size ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the first portion of every subexperiment params file we generate. Between the head and the tail are the experiment specific options.
def _paramsFileHead(): str = \ """ # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following te...
[ "def load_experiment_params(parmfile, rasterfs=100, sub_spont=True):\n params = {}\n expt = BAPHYExperiment(parmfile)\n rec = expt.get_recording(rasterfs=rasterfs, resp=True, stim=False)\n resp = rec['resp'].rasterize()\n if sub_spont == True:\n prestimsilence = resp.extract_epoch('PreStimSile...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a set of possible report keys for an experiment's results. A report key is a string of key names separated by colons, each key being one
def _appendReportKeys(keys, prefix, results): allKeys = results.keys() allKeys.sort() for key in allKeys: if hasattr(results[key], 'keys'): _appendReportKeys(keys, "%s%s:" % (prefix, key), results[key]) else: keys.add("%s%s" % (prefix, key))
[ "def _matchReportKeys(reportKeyREs=[], allReportKeys=[]):\n\n matchingReportKeys = []\n\n # Extract the report items of interest\n for keyRE in reportKeyREs:\n # Find all keys that match this regular expression\n matchObj = re.compile(keyRE)\n found = False\n for keyName in allReportKeys:\n matc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract all items from the 'allKeys' list whose key matches one of the regular expressions passed in 'reportKeys'.
def _matchReportKeys(reportKeyREs=[], allReportKeys=[]): matchingReportKeys = [] # Extract the report items of interest for keyRE in reportKeyREs: # Find all keys that match this regular expression matchObj = re.compile(keyRE) found = False for keyName in allReportKeys: match = matchObj.ma...
[ "def matched_keys(key_path: Any, all_keys: Sequence, case_ignored: bool, space_trimmed: bool = False) -> List:\n normalized = normalize(key_path, case_ignored, space_trimmed)\n keys = [k for k in all_keys if key_matches(k, normalized, case_ignored)]\n\n if len(keys) > 1:\n logger.warning(f\"Multiple...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a specific item by name out of the results dict. The format of itemName is a string of dictionary keys separated by colons, each key being one level deeper into the results dict. For example,
def _getReportItem(itemName, results): subKeys = itemName.split(':') subResults = results for subKey in subKeys: subResults = subResults[subKey] return subResults
[ "def getSpecificItem(itemName):\r\n return session.query(Item).filter_by(name=itemName).one()", "def get_item(name):\n for item in globals().values():\n if isinstance(item, MarketItem) and item.name == name:\n return item\n\n raise Exception(\"Invaid item '{}'\".format(name))", "def g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the complete set of results generated by an experiment (passed in 'results'), filter out and return only the ones the caller wants, as specified through 'reportKeys' and 'optimizeKey'. A report key is a string of key names separated by colons, each key being one
def filterResults(allResults, reportKeys, optimizeKey=None): # Init return values optimizeDict = dict() # Get all available report key names for this experiment allReportKeys = set() _appendReportKeys(keys=allReportKeys, prefix='', results=allResults) #----------------------------------------------------...
[ "def filter_query_results(self, results, datatype):\n # Need to filter all instruments' results by filter.\n # Choose filter with the most files\n # Only for flats\n if ((datatype == 'flat') and (self.instrument != 'fgs')):\n if self.instrument in ['nircam', 'niriss']:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This creates an experiment directory with a base.py description file created from 'baseDescription' and a description.py generated from the given params dict and then runs the experiment.
def runModelGivenBaseAndParams(modelID, jobID, baseDescription, params, predictedField, reportKeys, optimizeKey, useStreams, jobsDAO, modelCheckpointGUID, logLevel=None, predictionCacheMaxRecords=None): from nupic.swarming.ModelRunner import OPFModelRunner # The logger for this method log...
[ "def main(configurationDirectory):\n import sys\n if len(sys.argv)>1:\n configFile=sys.argv[1]\n runtime=ExperimentRuntime(configurationDirectory, configFile)\n else:\n runtime=ExperimentRuntime(configurationDirectory, \"experiment_config.yaml\")\n\n runt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activity tick handler; services all activities
def tick(self): # Run activities whose time has come for act in self.__activities: if not act.iteratorHolder[0]: continue try: next(act.iteratorHolder[0]) except StopIteration: act.cb() if act.repeating: act.iteratorHolder[0] = iter(xrange(act.period...
[ "def tick(self):\n # Run activities whose time has come\n for act in self.__activities:\n if not act.iteratorHolder[0]:\n continue\n\n try:\n next(act.iteratorHolder[0])\n except StopIteration:\n act.cb()\n if act.repeating:\n act.iteratorHolder[0] = iter(xr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to filter a list based on whether the object has any of the attribute values for the given attributes. Keeps the objects in which atleast one attr_vals matches the given ones for the given attrs.
def filter_list_or(list_to_filter, attrs, attr_vals, list_type): if list_type == "actor" and False in [(attr in ACTOR_JSON_TO_NODE_DICT) for attr in attrs]: return [] if list_type == "movie" and False in [(attr in MOVIE_JSON_TO_NODE_DICT) for attr in attrs]: return [] dict_to_use = ACTOR_JSO...
[ "def filter_by_attrs(args, **kwargs):\n if not kwargs:\n return args\n ret = []\n add_arg = True\n for arg in args:\n for attr, attr_vals in kwargs.items():\n if not isinstance(attr_vals, list):\n attr_vals = [attr_vals]\n\n mod = None\n reve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to handle an OR GET request on the API. Returns list of objects where atleast one of the attrs has the right attr_val.
def or_get_request_helper(attr1, attr_val1, attr2, attr_val2, orig_dict, list_type: str): items_matching_request = orig_dict.values() attr_val1 = attr_val1.replace("_", " ") attr_val2 = attr_val2.replace("_", " ") items_matching_request = filter_list_or(items_matching_request, [attr1, attr2], [attr_val1...
[ "def handle_movies_or_get_request(attr1, attr_val1, attr2, attr_val2):\n movies_matching_query = or_get_request_helper(attr1, attr_val1, attr2, attr_val2, MOVIES, \"movie\")\n return make_response(jsonify(movies_matching_query),\n 200 if len(movies_matching_query) > 0 else 400)", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for OR GET requests on the actors API
def handle_actor_or_get_request(attr1, attr_val1, attr2, attr_val2): actors_matching_query = or_get_request_helper(attr1, attr_val1, attr2, attr_val2, ACTORS, "actor") return make_response(jsonify(actors_matching_query), 200 if len(actors_matching_query) > 0 else 400)
[ "def handle_actor_and_get_request():\n\n attr_dict = request.args.to_dict()\n # print(attr_dict)\n actors_matching_query = and_get_request_helper(attr_dict, ACTORS, \"actor\")\n return make_response(jsonify(actors_matching_query),\n 200 if len(actors_matching_query) > 0 else 400)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for OR GET requests on the movies API
def handle_movies_or_get_request(attr1, attr_val1, attr2, attr_val2): movies_matching_query = or_get_request_helper(attr1, attr_val1, attr2, attr_val2, MOVIES, "movie") return make_response(jsonify(movies_matching_query), 200 if len(movies_matching_query) > 0 else 400)
[ "def handle_movie_and_get_request():\n attr_dict = request.args.to_dict()\n # print(attr_dict)\n movies_matching_query = and_get_request_helper(attr_dict, MOVIES, \"movie\")\n return make_response(jsonify(movies_matching_query),\n 200 if len(movies_matching_query) > 0 else 400)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for GET query on the actors API.
def handle_get_actor_request(name): name = name.replace("_", " ") # print(name) if name in ACTORS: return make_response(jsonify(ACTORS[name].__dict__), 200) return make_response(jsonify("Couldn't find the actor in our database."), 400)
[ "def handle_actor_and_get_request():\n\n attr_dict = request.args.to_dict()\n # print(attr_dict)\n actors_matching_query = and_get_request_helper(attr_dict, ACTORS, \"actor\")\n return make_response(jsonify(actors_matching_query),\n 200 if len(actors_matching_query) > 0 else 400)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for GET requests on the actors API
def handle_actor_and_get_request(): attr_dict = request.args.to_dict() # print(attr_dict) actors_matching_query = and_get_request_helper(attr_dict, ACTORS, "actor") return make_response(jsonify(actors_matching_query), 200 if len(actors_matching_query) > 0 else 400)
[ "def handle_get_actor_request(name):\n name = name.replace(\"_\", \" \")\n # print(name)\n if name in ACTORS:\n return make_response(jsonify(ACTORS[name].__dict__), 200)\n return make_response(jsonify(\"Couldn't find the actor in our database.\"), 400)", "def handle_actor_or_get_request(attr1, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for GET requests on the movies API
def handle_movie_and_get_request(): attr_dict = request.args.to_dict() # print(attr_dict) movies_matching_query = and_get_request_helper(attr_dict, MOVIES, "movie") return make_response(jsonify(movies_matching_query), 200 if len(movies_matching_query) > 0 else 400)
[ "def search_movies(request):\n movie_title = request.data['title']\n search_movie_url = 'https://api.themoviedb.org/3/search/movie?api_key={}&query={}'.format(api_key, movie_title)\n connect = req.urlopen(search_movie_url)\n data = json.loads(connect.read())\n return JsonResponse({'search results': d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for PUT requests on the Actors API.
def handle_actor_put_request(name): name = name.replace("_", " ") if (name not in ACTORS) or (not request.json): return make_response(jsonify("Bad Request"), 400) return update_list(ACTORS, name, request.json, ACTOR_JSON_TO_NODE_DICT)
[ "def put(self):\n failed, model, entity = self._get_model_and_entity(True, True)\n if failed: return\n jobj = jsonutil.receive_json(self.request)\n jobj = jsonutil.update_entity(entity, jobj)\n self._serve(jobj)\n updated_entity_path = \"/%s/%s\" % (self._classname, jobj['id'])\n self.response....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for PUT requests on the Movies API.
def handle_movie_put_request(name): name = name.replace("_", " ") if (name not in MOVIES) or (not request.json): return make_response(jsonify("Bad Request"), 400) return update_list(MOVIES, name, request.json, MOVIE_JSON_TO_NODE_DICT)
[ "def update_movies(request, movie_id, *args, **kwargs):\n movie_serializer_class = MovieSerializer\n queryset = Movie.objects.all()\n serializer = movie_serializer_class(data=request.data)\n try:\n serializer.is_valid(raise_exception=True)\n data = serializer.validated_data\n name =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for POST requests on the Actors API.
def handle_actor_post_request(name): name = name.replace("_", " ") if not request.json: return make_response(jsonify("Bad Request"), 400) if name in ACTORS: return update_list(ACTORS, name, request.json, ACTOR_JSON_TO_NODE_DICT) else: return add_to_list(ACTORS, name, request.json...
[ "def test_post_actors(self):\n body = {\n \"age\": 2,\n \"gender\": \"female\",\n \"name\": \"test\"\n }\n response = self.client.post('/actors',\n content_type='application/json',\n data=json...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for POST requests on the Movies API.
def handle_movie_post_request(name): name = name.replace("_", " ") if not request.json: return make_response(jsonify("Bad Request"), 400) if name in MOVIES: return update_list(MOVIES, name, request.json, MOVIE_JSON_TO_NODE_DICT) else: return add_to_list(MOVIES, name, request.json...
[ "def test_post_movies(self):\n body = {\n \"release_date\": \"2020/06/11\",\n \"title\": \"test\"\n }\n response = self.client.post('/movies',\n content_type='application/json',\n data=json.dumps(body))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for DELETE requests on the actors API.
def handle_actor_delete_request(name): name = name.replace("_", " ") if name in ACTORS: del ACTORS[name] return make_response(jsonify("Deleted Successfully"), 201) else: return make_response(jsonify("Actor not in database."), 400)
[ "def test_delete_actors(self):\n response = self.client.delete('/actors/1')\n body = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(body['message'], 'Actor Successfully deleted.')", "def test_delete_actor_director(self):\r\n w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for DELETE requests on the movies API.
def handle_movie_delete_request(name): name = name.replace("_", " ") if name in MOVIES: del MOVIES[name] return make_response(jsonify("Deleted Successfully"), 201) else: return make_response(jsonify("Movie not in database."), 400)
[ "def delete_movies(request, movie_id, *args, **kwargs):\n try:\n movie = Movie.objects.filter(id=movie_id)\n if movie.exists():\n movie.delete()\n return Response({'msg': 'Movie deleted.'}, status=status.HTTP_200_OK)\n else:\n return Response({'msg': 'Movie d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Init PickleUtils with a file name.
def __init__(self, filename): self.PICKLE_NAME = filename
[ "def load(self, filename):\n raise NotImplementedError(\"Loading from pickled files is not yet supported.\")", "def __init__(self, bitfile_name):\n super().__init__()\n\n if not isinstance(bitfile_name, str):\n raise TypeError(\"Bitstream name has to be a string.\")\n\n if o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function taken an unlimited number of arguments and prints them back together. This is meant for printing long names
def print_variable_full_name(*names): #print(names) for name in names: print(name, end=" ") print()
[ "def print_Bio(name, city, *familyMembers):\r\n print(\"*\" * 50)\r\n print(\r\n f\"Hello Everyone,\\nMy name is :'{name}', I am from '{city}' \\nMy Famaily memebers are :\")\r\n for memeber in familyMembers:\r\n print(f\"{memeber}\", end=' ,')\r\n print('\\n')", "def pargen(n):\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the process method with the default queryset.
def test_process_default_qs(self): self.assertEquals(len(self.alert.associated_tags), 0) Tag.objects.process(value=self.text, obj=self.alert) self.assertEquals(len(self.alert.associated_tags), 2)
[ "def test_process_filtered_qs(self):\n topic = Topic.objects.get(name='Names')\n queryset = Tag.objects.filter(topic=topic)\n self.assertEquals(len(self.alert.associated_tags), 0)\n Tag.objects.process(value=self.text, obj=self.alert, queryset=queryset)\n self.assertEquals(len(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the process method with the a filtered queryset.
def test_process_filtered_qs(self): topic = Topic.objects.get(name='Names') queryset = Tag.objects.filter(topic=topic) self.assertEquals(len(self.alert.associated_tags), 0) Tag.objects.process(value=self.text, obj=self.alert, queryset=queryset) self.assertEquals(len(self.alert.as...
[ "def test_run_all_filters(self):\n\n def filter1(model: AnalyticsEventModel):\n model.ExtraData[\"key1\"] = \"value1\"\n\n def filter2(model: AnalyticsEventModel):\n model.ExtraData[\"key2\"] = \"value2\"\n\n event_model = create_event_model()\n filter1(event_model)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the assign_tag method.
def test_assign_tag(self): tag = Tag.objects.get(pk=3) alert = Alert.objects.get(pk=1) tag_relation = tag.assign_tag(alert) self.assertEqual(tag_relation.tagged_object, alert)
[ "def test_new_tag_info(self):\n Tags()", "def test_tag_instance(self):\n self.assertTrue(isinstance(self.tag, TestTag))", "def test_tag_runs(self):\n pass", "def test_add_tag_for_task(self):\n pass", "def setTag(self, t):\r\n self.tag = t", "def test_storage_project_iso_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that None is returned if the field does not exist in the Alert data.
def test_non_string(self): datatagger = DataTagger( container=self.container, field_name='foobar' ) actual = datatagger._get_value(self.alert) expected = None self.assertEqual(actual, expected)
[ "def checkFruFieldInJson(self, field: str) -> bool:\n if \"Custom Data\" in field:\n return True\n if field in self.fru_data_in_json.keys() and not self.fru_data_in_json[field]:\n return True\n if (\n field in self.fru_data_in_json.keys()\n and self.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for when the Tag does not already exist and create_tags is True.
def test_no_tag_create_tag_true(self): self.assertFalse(Tag.objects.filter(name='newtag').exists()) actual = self.datatagger._get_tag('newtag') expected = Tag.objects.get_by_natural_key(topic_name='Names', tag_name='newtag') self.assertEq...
[ "def test_no_tag_create_tag_false(self):\n datatagger = DataTagger.objects.get(pk=2)\n actual = datatagger._get_tag('newtag')\n expected = None\n self.assertEqual(actual, expected)\n self.assertFalse(Tag.objects.filter(name='newtag').exists())", "def test_tag_does_not_exist(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for when the Tag does not already exist and create_tags is False.
def test_no_tag_create_tag_false(self): datatagger = DataTagger.objects.get(pk=2) actual = datatagger._get_tag('newtag') expected = None self.assertEqual(actual, expected) self.assertFalse(Tag.objects.filter(name='newtag').exists())
[ "def test_no_tag_create_tag_true(self):\n self.assertFalse(Tag.objects.filter(name='newtag').exists())\n actual = self.datatagger._get_tag('newtag')\n expected = Tag.objects.get_by_natural_key(topic_name='Names',\n tag_name='newtag')\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for when an appropriate Tag does not exist.
def test_tag_does_not_exist(self): self.datatagger.create_tags = False self.datatagger._tag_exact_match(self.alert, 'piedpiper') self.assertEqual(len(self.alert.associated_tags), 0) self.assertFalse(Tag.objects.filter(name='pied piper').exists())
[ "def test_no_tag_create_tag_false(self):\n datatagger = DataTagger.objects.get(pk=2)\n actual = datatagger._get_tag('newtag')\n expected = None\n self.assertEqual(actual, expected)\n self.assertFalse(Tag.objects.filter(name='newtag').exists())", "def fixture_non_existent_tag_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for Tags containing a single token.
def test_single_token_tag(self): datatagger = DataTagger.objects.get(pk=3) datatagger._tag_partial_match(self.alert, 'this is some text about wild cats.') actual = self.alert.associated_tags[0] expected = Tag.objects.get(name='cat') self.asse...
[ "def test_multi_token_tag(self):\n datatagger = DataTagger.objects.get(pk=3)\n topic = Topic.objects.get_by_natural_key('Animals')\n Tag.objects.create(name='wild cats', topic=topic)\n datatagger._tag_partial_match(self.alert,\n 'this is some text abo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for Tags containing omultiple tokens.
def test_multi_token_tag(self): datatagger = DataTagger.objects.get(pk=3) topic = Topic.objects.get_by_natural_key('Animals') Tag.objects.create(name='wild cats', topic=topic) datatagger._tag_partial_match(self.alert, 'this is some text about wild ca...
[ "def test_two_tags(self):\n entries = self.parse_lines(\n '2018-01-14 12 My description mytag1,mytag2')\n self.assertEqual(2, len(entries))\n self.assertEqual('mytag1', entries[0].tag)\n self.assertEqual('mytag2', entries[1].tag)", "def test_parse_token_multi_element_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert F to C.
def f_to_c(temp_f): return (temp_f - 32) * 5 / 9
[ "def f2c(t):\n\treturn int(round(float(5*(t-32))/9))", "def CtoFtoC_Conversion(inputTemp, outputTempType, isReturn):\n if outputTempType == 1:\n outputTemp = (inputTemp - 32) * 5 / 9;\n else:\n outputTemp = (9 * inputTemp / 5) + 32;\n if isReturn:\n return outputTemp;\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert mph to kph.
def mph_to_kph(mph): return mph * 1.609
[ "def ms_to_kmh(in_ms):\n return in_ms * 3.600", "def kmh_to_ms(in_kmh):\n return in_kmh * 0.2777778", "def kmh_to_mph(speed_kmh):\n velocity = speed_kmh * 1.60934\n return velocity", "def kphToMps(self, kph):\n return ((kph * 1000) / 60) / 60", "def ms_to_htk(ms_time):\n if type(ms_tim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
db_searcher method uses SimpleSearchEngineAlgorithm that searches mzML file against fasta database of protein sequences
def db_searcher(self) ->pd.DataFrame: # OpenMS Peptide Query protein_ids = [] peptide_ids = [] #SimpleSearchEngineAlgorithm compares mzML file against fasta file, and it gives an output that contains the number of peptides and the proteins in the database and how many spectra wer...
[ "def find(self):\n sql_cols = \"tokenid, token, lemma, pos, feat, head, deprel, align_id, id, sentence_id, text_id, contr_deprel, contr_head\"\n sqlq = \"SELECT {0} FROM {1} WHERE align_id in ({2}) order by align_id, id\".format(sql_cols, Db.searched_table, self.subquery)\n wordrows = Db.con.di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extract file with specific mime
def extractBro(mimes): cnt = 0 target = mimes.keys() if not os.path.exists("extract"): os.mkdir("extract") for f in os.listdir("extract_files"): mime = magic.from_file("./extract_files/%s" % f, mime=True) if mime in target: ext = mimes[mime] if not os.pa...
[ "def extractXMPFromURI(uri) :\n\timport urllib2\n\tobj = urllib2.urlopen(uri)\n\tinf = obj.info()\n\tftype = inf[\"content-type\"].split(\";\")[0].strip()\n\tif ftype == \"image/jpeg\" or ftype == \"application/pdf\" :\n\t\tlength = int(inf[\"content-length\"])\n\t\tp = obj.read(length)\n\t\treturn _searchXMLConte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the closest matches to E from EE in terms of l_2 norm
def find_endmember(EE,E): n1=EE.shape[1]; n2=E.shape[1]; error=np.zeros((1,n1)) index=np.zeros((n2)) for i in range(n2): for j in range(n1): error[0,j]= np.linalg.norm(E[:,i]-EE[:,j],2) b=np.argmin(error,axis=1) index[i] = b E_est = EE[:,index[0:n2]....
[ "def closest(self):\n boxes = [[i, j] for i in range(len(self.grid)) for j in range(len(self.grid[i])) if\n (self.grid[i][j] == '$')]\n tot_min = 0\n for b in boxes:\n minim = 100\n for p in self.placement:\n minim = min(minim, abs(b[0] - p[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the description of the room based on if it has objects that interact with it, or if those objects have been removed
def print_description(self,rooms): if self.obj_removed: data_printer.word_wrap(self.description_no_objects) else: data_printer.word_wrap(self.description_with_objects)
[ "def look_around(self):\n if self.current_room.light is True:\n print(self.current_room.description + '\\n')\n if len(self.current_room.items) == 1:\n print(f'You can see a {self.current_room.items[0]}.\\n')\n elif len(self.current_room.items) > 1:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets Twitter authenticated Stream API object
def _set_twitter_stream_api(self): auth = self._set_oauth() stream = Stream(auth, self) return stream
[ "def setup_twitter(self):\n # Setup Twitter connection.\n #self.logprint(\"consumer key/secret:\", self.cfg.get('twitter_consumer_key'), self.cfg.get('twitter_consumer_secret'))\n #self.logprint(\"ouath token/secret:\", self.cfg.get('twitter_oauth_token'), self.cfg.get('twitter_oauth_token_secr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Program's text pool (REPS).
def text_pool(self): return self.__text_pool
[ "def main():\n\t\n\t# create argument parser\n\tparser = argparse.ArgumentParser(description=\"Pre-processor for reddit corpus dumps. Parses text and stores it in a DocumentDatabase inventory.\")\n\t\n\t# add arguments\n\tparser.add_argument(\"--documents_path\", help=\"The path to the documents directory.\", defau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an estimate of the number of messages sent in the last day. If it has been significantly less or more than one day since the last call to this function, it will return None.
async def count_daily_messages(self) -> int: def _count_messages(txn: LoggingTransaction) -> int: sql = """ SELECT COUNT(*) FROM events WHERE type = 'm.room.message' AND stream_ordering > ? """ txn.execute(sql, (self.stream_ord...
[ "def calculate_delay(self, current_timestamp, previous_timestamp):\n if current_timestamp is None or previous_timestamp is None:\n return 0\n delay = current_timestamp - previous_timestamp\n if delay < 0:\n # It's not possible for the current server to receive the email be...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Counts the number of users who used this homeserver in the last 24 hours.
async def count_daily_users(self) -> int: yesterday = int(self._clock.time_msec()) - (1000 * 60 * 60 * 24) return await self.db_pool.runInteraction( "count_daily_users", self._count_users, yesterday )
[ "def hourCount(self):\n self._shiftOldEvents(time())\n return self.hour_count", "def _count_users(self, txn: LoggingTransaction, time_from: int) -> int:\n sql = \"\"\"\n SELECT COUNT(*) FROM (\n SELECT user_id FROM user_ips\n WHERE last_seen > ?\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Counts the number of users who used this homeserver in the last 30 days. Note this method is intended for phonehome metrics only and is different from the mau figure in synapse.storage.monthly_active_users which, amongst other things, includes a 3 day grace period before a user counts.
async def count_monthly_users(self) -> int: thirty_days_ago = int(self._clock.time_msec()) - (1000 * 60 * 60 * 24 * 30) return await self.db_pool.runInteraction( "count_monthly_users", self._count_users, thirty_days_ago )
[ "async def count_daily_users(self) -> int:\n yesterday = int(self._clock.time_msec()) - (1000 * 60 * 60 * 24)\n return await self.db_pool.runInteraction(\n \"count_daily_users\", self._count_users, yesterday\n )", "def _count_users(self, txn: LoggingTransaction, time_from: int) -> ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of users seen in the past time_from period
def _count_users(self, txn: LoggingTransaction, time_from: int) -> int: sql = """ SELECT COUNT(*) FROM ( SELECT user_id FROM user_ips WHERE last_seen > ? GROUP BY user_id ) u """ txn.execute(sql, (time_from,)) # Mypy...
[ "def count( cls, user, subject, limit, life_hours ):\n q = cls.query( cls.user == str( user ), cls.subject == subject )\n tokens = q.order( -cls.created ).fetch( limit,\n projection=[ cls.created ] )\n res = 0\n for token in tokens:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates daily visit data for use in cohort/ retention analysis
async def generate_user_daily_visits(self) -> None: def _generate_user_daily_visits(txn: LoggingTransaction) -> None: logger.info("Calling _generate_user_daily_visits") today_start = self._get_start_of_day() a_day_in_milliseconds = 24 * 60 * 60 * 1000 now = self....
[ "def extract_daily_dataset(\n work_dict,\n scrub_mode='sort-by-date'):\n return extract_dataset('daily', work_dict, scrub_mode=scrub_mode)", "def generate_daily_transactions_df(users, transactions, analysis_end_date):\n\n # Filter data by time\n analysis_end_date = pd.to_datetime(analysis_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the layer tab bar and layout function
def get_layer_tabs(self, previous_active: str = None): return tabs.make('bottom-layer', {'info': 'Info', 'weights': 'Weights', 'grads': 'Gradients'}, previous_active)
[ "def GetAdditionalBorderSpace(*args, **kwargs):\n return _aui.AuiTabArt_GetAdditionalBorderSpace(*args, **kwargs)", "def create_tabs(self):\n\n # Tabs\n self.create_setup_tab()\n self.create_part_location_tab()\n self.create_order_tab()\n self.create_challenge_tab()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the activation map plot
def get_activation_map(self, activation_mapper: AbstractActivationMapper, input_img, unit_idx): activation = activation_mapper.get_activation(input_img, self) hover_text = self._get_unit_labels() fig = go.Figure(data=[go.Bar(x=activation, hovertext=hover_text, hoverinfo='text', ...
[ "def show_heatmap(self):\n plt.show()", "def plot_from_tc_mapping():\n from target_calib import CameraConfiguration\n c = CameraConfiguration(\"1.1.0\")\n m = c.GetMapping()\n camera = CameraImage.from_tc_mapping(m)\n image = np.zeros(m.GetNPixels())\n image[::2] = 1\n camera.image = i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To update the attribute of passed form field
def update_attr(field, attr, value): field.widget.attrs.update({ attr: value })
[ "def update_field(self, ab, field, is_int=False):\n field_value = self.request.get(field)\n if not field_value or field_value=='':\n setattr(ab, field, None)\n else:\n if is_int:\n setattr(ab, field, int(field_value))\n else:\n setattr(ab, field, field_value)", "def update_at...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a part of the surname matches with given names in block. For example, ``SanchezGomez, Juan`` can appear on a signature as ``Gomez, Juan Sanchez``. This function checks if there is a match between surnames like ``Sanchez`` and the given names in the block. In this case, a signature like ``Gomez, J. Sanchez`` wi...
def compare_tokens_from_last(self, first_surnames, last_surname): if last_surname in self._content: for given_names in six.iterkeys(self._content[last_surname]): given_names_left = len(given_names) for reversed_index, name in \ enumerate(revers...
[ "def is_real_name(full_name):\n\n # split the full name into tokens\n tokens = tokenizer.tokenize(full_name)\n\n # 1. consider empty names fake\n if not tokens:\n return False\n\n # 2. if 3-grams can't be created consider fake\n # ngrams is a generator so if list(ngrams(full_name, 3)) = [] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if there is at least one signature with given surnames.
def contains(self, surnames): return surnames in self._content
[ "def is_signature(signature):\n\n try:\n return check_signature(signature)\n except:\n return False", "def single_surname_signatures(self):\n return self._single_surname_signatures", "def checkAuthorList (\n\n self,\n names = None\n ) :\n\n if utilities.isE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the number of signatures with only one surname. The only exception is that when the block was created by a signature which consisted of more than one surname, the result will be increased by one, so that the result can be used as a denominator. Returns
def single_surname_signatures(self): return self._single_surname_signatures
[ "def get_number_of_photos_to_save(self):\n photo_list = self.get_photos()\n count = photo_list['response']['count']\n print(f'Всего фотографий у пользователя: {count}')\n user_response = input('Введите количество фотографий, которое хотите сохранить, либо нажмите '\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Block the signatures. This blocking algorithm takes into consideration the cases, where author has more than one surname. Such a signature can be assigned to a block for the first author surname or the last one. The names are preprocessed by ``dm_tokenize_name`` function. As a result, here the algorithm operates on ``D...
def block_double_metaphone(X, threshold=1000): # Stores all clusters. It is the only way to access them. # Every cluster can be accessed by the token that was used to create it. # It is the last token from the surnames tokens passed to the constructor. id_to_block = {} # List of tuples. Used as the...
[ "def get_s2_blocks(self) -> Dict[str, List[str]]:\n block: Dict[str, List[str]] = {}\n for signature_id, signature in self.signatures.items():\n block_id = signature.author_info_block\n if block_id not in block:\n block[block_id] = [signature_id]\n else:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Blocking function using last name and first initial as key. The names are normalized before assigning to a block.
def block_last_name_first_initial(X): def last_name_first_initial(name): names = name.split(",", 1) try: name = "%s %s" % (names[0], names[1].strip()[0]) except IndexError: name = names[0] name = normalize_name(name) return name blocks = [] ...
[ "def test_block_creation_with_name_empty(self):\n CommonTestCases.admin_token_assert_in(\n self,\n block_mutation_query_without_name,\n \"name is required field\"\n )", "def _normalize_block_name(block_name):\n block_name = ''.join(block_name.split())\n block_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates inventory by subtracting products from the order to be processed
def updateInventory(order_food, stock): stock[7]=int(stock[7])-order_food["nBurgers"] stock[8]=int(stock[8])-order_food["nLettuce"] stock[9]=int(stock[9])-order_food["nTomato"] stock[10]=int(stock[10])-order_food["nVeggie"] stock[11]=int(stock[11])-order_food["nBacon"]
[ "def update_inventory(products, order_type=ORDER_TYPE_PLACED):\n\n if order_type == ORDER_TYPE_PLACED:\n # For placing an order, item is removed from inventory. i.e.,\n # New inventory quantity = Old inventory quantity - order quantity\n # = New inventory quantity = Old inventory quantity + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the most stingy result as a list of LAMB payments. The most stingy result is to make sure that the sum of the payments to the next two subordinate henchman is equal to their senior. This satisfies condition 3 on the README file whilst using the least amount of LAMBS. Essentially this gives the fibonacci sequ...
def get_stingy_result(lambs): sti_result = [] this_payment = 1 while(sum(sti_result) <= lambs): sti_result.append(this_payment) if(len(sti_result) > 1): this_payment = sum(sti_result[-2:]) return sti_result
[ "def get_generous_result(lambs):\n # Gives 2*n sequence\n gen_result = []\n this_payment = 1\n while(sum(gen_result) <= lambs):\n gen_result.append(this_payment)\n this_payment *= 2\n\n return gen_result", "def test_fib(self):\n from boto.sdb.db.sequence import fib\n # J...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates most generous result as a list of LAMB payments. The most generous case is to pay every new senior henchman double the amount of LAMBS as their subordinate. Keep appending payments that double until the total amount of lambs used is more than the amount available.
def get_generous_result(lambs): # Gives 2*n sequence gen_result = [] this_payment = 1 while(sum(gen_result) <= lambs): gen_result.append(this_payment) this_payment *= 2 return gen_result
[ "def get_stingy_result(lambs):\n sti_result = []\n this_payment = 1\n while(sum(sti_result) <= lambs):\n sti_result.append(this_payment)\n if(len(sti_result) > 1):\n this_payment = sum(sti_result[-2:])\n\n return sti_result", "def get_generous_next_payout(lambs_given):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the wave value variation goes outside of what's supported, then we snap that value to the floor or ceiling. For example, if the next value to generate was between 59 and 69, then if we allowed values of 5905, then a value between 0 and 5 would heavily distort the waveform.
def wrapWaveValue(self, wave_value): if 0 > wave_value: return 0 elif self.wave_length <= wave_value: return 64 else: return wave_value
[ "def clip(val):\n return max(min(val, 4.0), -4.0)", "def _normalize_reading(self, value):\n return value / float(self.max_sensor_val)", "def clamp(inclusive_lower_bound: int,\n inclusive_upper_bound: int,\n value: int) -> int:\n if value <= inclusive_lower_bound:\n return i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format the FDS instrument modifications required by FamiTracker in such a way that is recognised by the importer. The first list item defines the FDS wave itself and the other items modify the waveform values and add any pitch modulation required.
def getInstrument(self): return [ 'INSTFDS 0 1 0 0 0 ' + '"' + self.getName() + '"', 'FDSWAVE 0 : ' + ' '.join([str(s) if 10 <= s else ' ' + str(s) for s in self.getWave()[1]]), 'FDSMOD 0 : ' + ' '.join('0' for i in range(32)) ]
[ "def _format_sample(self, index, diagnostics):\n # Get attributes\n filename = diagnostics.loc[index, 'FileName']\n rhythm = diagnostics.loc[index, 'Rhythm']\n beats = diagnostics.loc[index, 'Beat'].split(' ')\n age = diagnostics.loc[index, 'PatientAge']\n sex = diagnostics...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an Emperor scatter plot from a Pandas DataFrame
def scatterplot(df, x=None, y=None, z=None, remote=True): if not isinstance(df, pd.DataFrame): raise ValueError("The argument is not a Pandas DataFrame") for col in [z, y, x]: if col is None: continue if col not in df.columns: raise ValueError("'%s' is not a co...
[ "def scatter_plot(df, col):\n fig, ax = plt.subplots(figsize=(16, 8))\n ax.scatter(df[col], df['Income in EUR'])\n ax.set_xlabel(col)\n ax.set_ylabel('Income in EUR')\n plt.show()", "def dotplot(df: pd.Series, fig = None, axes = None, custom_order: list = None, sizescaler = 50, alphascaler = 1, fix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return CSV file path given ticker symbol.
def symbol_to_path(symbol): return "data/{}.csv".format(str(symbol))
[ "def get_url_for_ticker(self, ticker):\n current_directory = os.path.dirname(os.path.realpath(__file__))\n funds_csv_file_path = abspath(os.path.join(current_directory, '..', 'offline', 'ishares_funds.csv'))\n with open(funds_csv_file_path, mode='r', encoding='utf-8') as funds_file:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We use allocations and df with relevant stock data to find sharpe ratio, this is the function to minimize We'll a assume daily sampling and rfr of 0 Further, the df should be of normalized price returns for the symbols
def sharpe_ratio(allocs, normed): alloced = normed*allocs port_val = alloced.sum(axis=1) #gets total normalized returns for the portfolio as a whole daily_returns = compute_daily_returns(port_val) sddr = daily_returns.std() sr = ((daily_returns).mean()/sddr)*(252.**(1./2)) #computes sr return sr...
[ "def sharpe_ratio(allocs):\n normed = prices_all / (prices_all.iloc[0])\n\n # calculating \"each stock in syms\"'s portfolio by multipling 'normalized stock price' with allocs\n alloced = normed[syms] * allocs\n port_val = alloced.sum(axis=1)\n\n # calculating daily return by divi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wraps function requesting data to allow safe errors and retry.
def safe_request(fun): def wrapped_f(*args, **kwargs): try: a = fun(*args, **kwargs) return a except urllib.error.HTTPError as e: if e.code in (429, 502): time.sleep(5) print("Sending too many requests, sleeping 5sec and retrying....
[ "async def wrapper(*args: Tuple[Any, ...], **kwds: Dict[str, Any]) -> Any:\n key = CacheKey.make(args, kwds)\n value = cache[key]\n # cache miss/expired\n if value is None:\n result = await fn(*args, **kwds)\n cache[key] = CacheValue(expired=time.monotonic() + expir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a refseq db in fasta format and a list of incomplete query refseq ID, extract the queried genomes into a new fasta file by matching the IDs.
def retrieve_refseq_ids(in_ids, db, out_fa): query_ids = open(in_ids).read().splitlines() found = [] with open(out_fa, "w") as genomes: for query_rec in SeqIO.parse(db, "fasta"): if re.search("|".join(query_ids), query_rec.id): query_rec.id = re.search(r"[^\.]*", query_re...
[ "def hits_to_fasta(query,gbk_multi_fasta,hits_sseqid_list):\n\thits_fasta = \"blast_hits.fasta\"\n\toutput_handle = open(hits_fasta, \"w\")\n\t# Add query to fasta for muscle alignement\n\twith open(query) as f_query:\n\t for line in f_query:\n\t output_handle.write(line.replace(\"#\",\"\"))\n\t# Add hits...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries genbank record for an input ID and retrieves the genome annotations in GFF format. Amino acid sequences are included in the GFF.
def retrieve_id_annot(id, out_gff, mode="w", email="someone@email.com"): handle = Entrez.efetch( id=id, db="nucleotide", email=email, rettype="gbwithparts", retmode="full" ) record = SeqIO.parse(handle, "genbank") with open(out_gff, mode) as gff_handle: GFF.write(record, gff_handle, incl...
[ "def parse_gff(filename):\n Annotation_info = namedtuple(\"Annotation\", [\"accno\", \"geneID\", \"startpos\", \"endpos\", \"strand\"])\n geneID_regex = re.compile(r'GeneID:(\\d+)')\n with open(filename) as gff_file:\n if not gff_file.readline().startswith(\"##gff-version 3\"):\n logging....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts sequence from the attributes of CDS in a GFF into a fasta file. The fasta headers are in the format >chrom_id|prot_id
def gff_seq_extract(gff, fa): with open(gff, "r") as gff_in, open(fa, "w") as fa_out: for line in gff_in: seq_ok, id_ok = False, False fields = line.split("\t") if fields[2] == "CDS" and not fields[0].startswith("#>"): desc = fields[-1].split(";") ...
[ "def GFFParse(gff_file):\n\n genes, transcripts, exons, utr3, utr5, cds = {}, {}, {}, {}, {}, {}\n gff_handle = open(gff_file, \"rU\")\n for gff_line in gff_handle:\n gff_line = gff_line.strip('\\n\\r').split('\\t')\n if not gff_line:continue\n if re.match(r'#', gff_line[0]) or re.matc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the queryset based on the format as fahrenheit or celsius
def filter_temp_format(queryset, name, value): return queryset
[ "def filterFormat(self):\n \n pass", "def convert_celsius_to_fahrenheit(self):\n value = self.get_valid_temperatures()\n fahrenheit = value * 9.0 / 5 + 32\n self.root.ids.output_label.text = str(fahrenheit)", "def celsius_fahrenheit():\n f = int(input(\"Ingrese un valor de grad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a date object returns start of week and month
def get_start_of_week_and_month(date_object): return ( (date_object - timedelta(days=date_object.weekday())).strftime('%Y-%m-%d'), (date_object.replace(day=1)).strftime('%Y-%m-%d') )
[ "def week_start(date):\r\n return utils.get_week_start(date)", "def week_of_month(datetime):\n dom = datetime.day\n return int(ceil(dom/7.0))", "def start_date(date):\n if date.month < 12:\n return datetime.date(date.year - 1, date.month + 1, 1)\n else:\n return date...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the total min and max temperatures for each week or month.
def get_total_min_and_max_temps(data, frequency): dates_and_temps = defaultdict(lambda: (0, 0, 0, 0)) for row in data: current_date, tmax, tmin = row['date'], row['tmax'], row['tmin'] start_of_week, start_of_month = \ WeatherDetailViewSet.get_start_of_week_and_mo...
[ "def get_avg_min_and_max_temps(self, dates_and_temps):\n data = []\n\n for key in dates_and_temps:\n total_tmax, total_tmin, max_days, min_days = dates_and_temps[key]\n data.append({\n \"date\": key,\n \"tmax\": round(total_tmax / max_days) if max_da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the average min and max temperatures for each week or month.
def get_avg_min_and_max_temps(self, dates_and_temps): data = [] for key in dates_and_temps: total_tmax, total_tmin, max_days, min_days = dates_and_temps[key] data.append({ "date": key, "tmax": round(total_tmax / max_days) if max_days else "N/A", ...
[ "def get_total_min_and_max_temps(data, frequency):\n dates_and_temps = defaultdict(lambda: (0, 0, 0, 0))\n\n for row in data:\n current_date, tmax, tmin = row['date'], row['tmax'], row['tmin']\n start_of_week, start_of_month = \\\n WeatherDetailViewSet.get_start_of...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Based on the frequency passed updates the API response accordingly.
def update_for_frequency(self, response, request): frequency = request.query_params.get('frequency', 'daily') return response.data if frequency == 'daily' else self.get_updated_response(response.data, frequency)
[ "def update_frequency(self, update_frequency):\n\n self._update_frequency = update_frequency", "def update_frequency(self):\n return self.timer.update_frequency", "def __refreshFrequencies(self):\n self.__historyFilterModel.recalculateFrequencies()\n self.__startFrequencyTimer()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build the TsurgeonRequest object
def build_request(trees, operations): if isinstance(trees, Tree): trees = (trees,) request = TsurgeonRequest() for tree in trees: request.trees.append(build_tree(tree, 0.0)) if all(isinstance(x, str) for x in operations): operations = (operations,) for operation in operation...
[ "def build_replica_request(self) -> Request:\n request = Request()\n\n # Details\n request.version = self.request.version\n request.remoteIp = self.request.remote_ip\n request.protocol = self.request.protocol\n request.host = self.request.host\n request.hostName = se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }