query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Capture whole display to file ``file_path``
def capture_display(file_path): pyscreenshot.grab(childprocess=True).save(file_path) BuiltIn().log("Saved current display to file `%s`" % file_path)
[ "def show_text(self):\n\t\topen_file = open(self.file_name, 'r')\n\t\tprint()\n\t\tprint('================================')\n\t\tprint(self.file_name)\n\t\tprint('================================')\n\t\tprint()\n\t\tprint(open_file.read())", "def dump_file(file):\n if file is not None:\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a CSV file with headers defined by a list `header` The CSV file is opend with `UTF8` encoding mode
def csv_create(pathname, *header): if sys.version_info[0] > 2: with open(pathname, 'w', encoding='utf-8') as f: f.write(','.join(header)) else: with codecs.open(pathname, 'w', 'utf-8') as f: f.write(','.join(header)) BuiltIn().log('Create an empty CSV file `%s`' % pat...
[ "def file_with_header():\n file_name = 'file_with_header.csv'\n file = open(file_name, 'w')\n writer = csv.writer(file)\n writer.writerow(['name', 'email'])\n writer.writerow(['abc', 'abc@def.com'])\n file.close()\n yield open(file_name, 'r')\n os.remove(file_name)", "def create_csv_from_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add more data define by a list `items` to a existed CSV file
def csv_add(pathname, *items): if sys.version_info[0] > 2: with open(pathname, 'a', encoding='utf-8') as f: f.write("\r\n") f.write(','.join(items)) else: with codecs.open(pathname, 'a', 'utf-8') as f: f.write("\r\n") f.write(','.join(items)) B...
[ "def create_csv_from_item_list(headers, items):\n\n file_body = headers + '\\n'\n header_list = headers.split(',')\n for item in items:\n csv_item = ''\n for header in header_list:\n csv_item += str(item.get(header, '')) + ','\n csv_item = csv_item[:-1] + '\\n'\n file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends bytes of `data` by socket `sock` and reicve the response When `recv_buffer_size` is zero, the function does not execpt a response from the remote.
def send(sock,data,recv_buffer_size=1024,encode='utf-8'): if (sys.version_info > (3, 0)): data_buffer = bytes(data,encode) sock.send(data_buffer) if recv_buffer_size != 0: recv_buffer = sock.recv(recv_buffer_size) return recv_buffer.decode(encode) else: so...
[ "def sock_send(self, data):\n\n self.sock.send(data)", "def send_data_to_socket(self):\r\n if not self.connected:\r\n self.throw_exception(message='disconnected')\r\n\r\n if not self._outgoing_buffer:\r\n return 0\r\n\r\n while True:\r\n try:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts XML by using XLS stylesheet Predefined stylesheets are store in `tools/xls` under current active RENAT folder
def convert_xml(style,src,dst): output = subprocess.check_output(['xsltproc',style,src]) with open(dst,'w') as f: if (sys.version_info > (3, 0)): f.write(output.decode('utf-8').strip("\n")) else: f.write(output.strip("\n")) BuiltIn().log('Converted from `%s` to `%s` u...
[ "def _load_export_xsl(self):\n try:\n return self.DEFAULT_XSL_STYLESHEET\n except AttributeError:\n raise # do something more intelligent here, not all exporter plugins may use XSL", "def transform(stylesheet,infile,outfile,parameters={},validate=True,xinclude=False,keep_uncha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns multiple lines from text data using `index` `index` uses python rule.
def get_multi_lines(data,index): tmp = data.splitlines() result = eval('\'\\n\'.join(tmp[%s])' % index) return result
[ "def _index_text(self):\n self._lines = []\n\n start = 0\n newline = self._text.find('\\n')\n while newline != -1:\n self._lines.append((start, newline))\n start, newline = newline + 1, self._text.find('\\n', newline + 1)\n self._lines.append((start, len(self._text)))", "def linenum(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stops next run (specified by n) using a .stop file with reason
def stop_next_run(msg=u'Case run was stopped by user'): with open(os.getcwd() + '/.stop','w') as file: file.write(msg + newline) BuiltIn().log("Do not run the test on next round")
[ "def stop(self, iterations):\n self.stop_count += iterations", "def test_stop_runs(self):\n pass", "def test_stop_run(self):\n pass", "def setStopFittingN(fileNumString,stopFittingN,resetFitAllDone=True):\n fitProbData = lockAndLoadFitProbData(fileNumString)\n for pMultiple in list(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns IP list from a prefix
def get_ip_list(prefix): return list(map(lambda x: str(x),ipaddress.ip_network(prefix).hosts()))
[ "def get_ip_prefixes(self, **kwargs):\n return self.netbox_con.get('/ipam/prefixes/', **kwargs)", "def get_prefix_list(username, password, host) -> Tuple[list, Any]:\r\n\r\n xml_filter = \"\"\"<filter xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns IP network from a prefix
def get_ip_network(prefix): return str(ipaddress.ip_network(prefix,False))
[ "def network_from_wif_prefix(prefix: bytes) -> str:\n index = _WIF_PREFIXES.index(prefix)\n return _NETWORKS[index]", "def network_from_p2pkh_prefix(prefix: bytes) -> str:\n index = _P2PKH_PREFIXES.index(prefix)\n return _NETWORKS[index]", "def network_from_p2sh_prefix(prefix: bytes) -> str:\n in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns IP address with increment add to prefix
def get_ip_address_increment(prefix,increment): return str(ipaddress.ip_address(prefix) + int(ipaddress.ip_address(increment)))
[ "def increment_ip(ip):\n return int_to_ip(ip_to_int(ip) + 1)", "def with_prefix(self, prefix):\n return addr_convert(self.address, prefix)", "def get_ip_network(prefix):\n return str(ipaddress.ip_network(prefix,False))", "def _rewrite_old_prefix(ipprefix):\n count = ipprefix.count('.')\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a mail with attached file or image
def send_mail_with_embeded_data(mail_from,send_to,subject,txt,img_path=None,file_path=None): smtp_info = GLOBAL['default']['smtp-server'] smtp_server,smtp_port = smtp_info.split(':') msg = MIMEMultipart('related') msg['Subject'] = subject msg['From'] = mail_from msg['To'] = COMMASPACE.join([sen...
[ "def sendEmail(sendTo,textfile,logfile,img):\r\n # Open a plain text file for reading\r\n msg = MIMEMultipart()\r\n\r\n # Read the text file <-- Error msg from OCR module\r\n if(textfile!=\"\"):\r\n fp = open(textfile, 'rb')\r\n text = MIMEText(fp.read())\r\n fp.close()\r\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate a file and returns the result The keyword returns a tupple with 2 values. The 1st one is a bool value indicats if the file_path exists or not. The second value is the value that is evaluated from file_path. In case the file does not exists or could not be evaluated, a `default` value is returned.
def eval_file(file_path=u'.eval',default=None): result = default exist = os.path.exists(file_path) if exist: with open(file_path) as f: code = f.read() try: result = eval(code) except: result = default BuiltIn().log("Evaluat...
[ "def get_value(self, resultpath, default=None):\n fname = os.path.join(resultpath, self.filename)\n with open(fname) as f:\n for line in f:\n m = re.search(self.regex, line)\n if m:\n return self.parser(m.group('value'))\n return defau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs keyword if exists
def run_keyword_if_exist(keyword,*args, **kwargs): try: e = BuiltIn().keyword_should_exist(keyword) if e: BuiltIn().log("Found keyword `%s`" % keyword) BuiltIn().run_keyword(keyword, *args, **kwargs) else: BuiltIn().log("WRN: Keyword `%s` not found" % keyw...
[ "def keyphrase_function(keyword):\n print(\"Keyword %s detected!\"%(keyword))", "def keyword(token, kw=None):\n return isA(token, tt=\"KEYWORD\", tv=kw)", "def is_keyword(self, *keywords):\r\n if self.token is None:\r\n self.get_next()\r\n return self.token == 'identifier' and sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that an event has a city
def test_city(db): query = db.query(Event) query = query.filter(Event.year == 2013) query = query.filter(Event.month == 12) query = query.filter(Event.day == 4) event = query.one() assert event.city.name == 'Ostrava'
[ "def test_cities(db):\n query = db.query(City)\n query = query.filter(City.name == 'Ostrava')\n city = query.one()\n assert city.slug == 'ostrava'\n assert city.events\n assert any(e.name == 'Ostravské KinoPyvo' for e in city.events)\n assert not any(e.name == 'Brněnské Pyvo' for e in city.even...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that a city has events
def test_cities(db): query = db.query(City) query = query.filter(City.name == 'Ostrava') city = query.one() assert city.slug == 'ostrava' assert city.events assert any(e.name == 'Ostravské KinoPyvo' for e in city.events) assert not any(e.name == 'Brněnské Pyvo' for e in city.events)
[ "def test_city(db):\n query = db.query(Event)\n query = query.filter(Event.year == 2013)\n query = query.filter(Event.month == 12)\n query = query.filter(Event.day == 4)\n event = query.one()\n assert event.city.name == 'Ostrava'", "def test_search_events(self):\n pass", "def test_event...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that an event has a venue
def test_venue(db): query = db.query(Event) query = query.filter(Event.year == 2013) query = query.filter(Event.month == 12) query = query.filter(Event.day == 4) event = query.one() assert event.venue.name == 'Sport Club' assert event.venue.slug == 'sport-club'
[ "def test_venues(db):\n query = db.query(Venue)\n query = query.filter(Venue.name == 'Na Věnečku')\n query = query.filter(Venue.city_slug == 'praha')\n venue = query.one()\n assert venue.events\n assert any(e.name == 'Pražské PyVo' for e in venue.events)\n assert not any(e.name == 'Brněnské Pyv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that a venue has events
def test_venues(db): query = db.query(Venue) query = query.filter(Venue.name == 'Na Věnečku') query = query.filter(Venue.city_slug == 'praha') venue = query.one() assert venue.events assert any(e.name == 'Pražské PyVo' for e in venue.events) assert not any(e.name == 'Brněnské Pyvo' for e in ...
[ "def test_venue(db):\n query = db.query(Event)\n query = query.filter(Event.year == 2013)\n query = query.filter(Event.month == 12)\n query = query.filter(Event.day == 4)\n event = query.one()\n assert event.venue.name == 'Sport Club'\n assert event.venue.slug == 'sport-club'", "def test_sear...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that an event has URLs
def test_urls(db): query = db.query(Event) query = query.filter(Event.year == 2013) query = query.filter(Event.month == 12) query = query.filter(Event.day == 4) event = query.one() [link] = event.links assert link.url == 'http://lanyrd.com/2013/ostravske-pyvo-druhe/'
[ "def _assert_parsed_urls(self, event_url, urls_to_parse):\n if 'edit' not in event_url:\n\n # checking URLs after event creation/edition\n response = self.client.get(\n event_url\n )\n for url in urls_to_parse:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query a sequence region in the fasta.
def query_region(self, chrom, pstart, pend): sequence = None if chrom not in self.fai_data: print('*Warning* query chrom "{}" is not found in fasta {}' .format(chrom, self.fa_name), file=sys.stderr, flush=True) return sequence if not pstart: ...
[ "def main():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-f', '--fasta', metavar=\"fasta\",\n help=\"input FASTA file\",\n type=argparse.FileType('r'), required=True)\n parser.add_argument('-c', '--chrom', metavar=\"chrom_name\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper of function fasta.query_region() with command line inputs.
def main(): parser = argparse.ArgumentParser() parser.add_argument('-f', '--fasta', metavar="fasta", help="input FASTA file", type=argparse.FileType('r'), required=True) parser.add_argument('-c', '--chrom', metavar="chrom_name", help=...
[ "def cli_region(\n usage_help: str = \"Image region in the whole slide image to read from. \"\n \"default=0 0 2000 2000\",\n) -> callable:\n return click.option(\n \"--region\",\n type=int,\n nargs=4,\n help=usage_help,\n )", "def parse_region(contig=None, start=None, stop=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the center coordinate from the given region file
def get_center(regfile): regions = open(regfile).readlines() regions = list(filter(lambda x: re.match(r"^(circle|annulus|pie).*", x, re.I), regions)) xc, yc = map(float, re.split(r"[(,)]", regions[0])[1:3]) return (xc, yc)
[ "def calculate_region_center(x_min, x_max, y_min, y_max):\n return x_min + (x_max - x_min) / 2, y_min + (y_max - y_min) / 2", "def find_centre(path_file):\n #Open MTD_TL.xml file\n xml_data = minidom.parse(os.path.join(path_file, \"MTD_TL.xml\"))\n root = xml_data.documentElement\n Sun_Angles_Grid_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The local reachability density (LRD) The LRD of a sample is the inverse of the average reachability distance of its knearest neighbors.
def _local_reachability_density(self, distances_X, neighbors_indices): dist_k = self._distances_fit_X_[neighbors_indices, self.n_neighbors_ - 1] reach_dist_array = np.maximum(distances_X, dist_k) # 1e-10 to avoid `nan' when nb of duplicates > n_neighbors_: return 1. / (np.mean(reach_dist...
[ "def _compute_update_ld_metric(self):\n metrics_d = self._metrics_dict\n if metrics_d['ld_count'] == 0:\n ld_metric = np.nan\n else:\n ld_metric = metrics_d['ld_dist_sum'] / metrics_d['ld_count']\n metrics_d['ld_metric'] = ld_metric\n return ld_metric", "def calculate_ldtsd(self):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for equilateral triangles
def testequilateraltriangles(self): self.assertEqual(classify_triangle(1, 1, 1), 'Equilateral', '1,1,1 should be equilateral')
[ "def test_degenerate_triangle_2(self):\n self.assertEqual(square_of_triangle([1, 1, 0, 0, -1, -1]), 0.0)", "def test_generic_triangle(sideOne=1,sideTwo=2,sideThree=3):\n assert tri_check(sideOne,sideTwo,sideThree) == True # should return true", "def using_triangle():\r\n return HAS_TRIANGLE", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for invalid triangles
def testinvalidtriangle(self): self.assertEqual(classify_triangle(5, 1, 2), 'NotATriangle', 'NotATriangle')
[ "def test_valid_triangle(self):\n self.assertEqual(triangle.classify_triangle(0, 2, 3), 'Not Valid')\n self.assertEqual(triangle.classify_triangle(4, 0, 3), 'Not Valid')\n self.assertEqual(triangle.classify_triangle(9, 10, 0), 'Not Valid')\n self.assertEqual(triangle.classify_triangle(-3...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for right scalene triangles
def testrightscalene(self): self.assertEqual(classify_triangle(3, 4, 5), 'Right Scalene', '3,4,5 should be scalene')
[ "def test_degenerate_triangle_2(self):\n self.assertEqual(square_of_triangle([1, 1, 0, 0, -1, -1]), 0.0)", "def testequilateraltriangles(self):\n self.assertEqual(classify_triangle(1, 1, 1), 'Equilateral', '1,1,1 should be equilateral')", "def test_generic_triangle(sideOne=1,sideTwo=2,sideThree=3)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a new session.
def new(self): return self.session_class({}, self.generate_key(), True)
[ "def start_new_session(self):\n self._session = SessionManager.instance().create_session(close_callback=self.on_session_closed)\n self._builder.set_header(token=self._session.session_token)", "def create_session(self):\n\n self.session = self.opentok.create_session(\n media_mode=Me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save if a session class wants an update.
def save_if_modified(self, session): if session.should_save: self.save(session)
[ "def save(self, must_create=False):\n self._session_key = self._get_session_key()\n self.modified = True", "def auto_update(self) -> bool:\n return self.persist.get(ATTR_AUTO_UPDATE, super().auto_update)", "def save(self):\n if self.sw_update_obj is not None:\n self.sw_upd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the stream consumer that collects row identifier and rows.
def test_row_collector(): consumer = Collector().open([]) consumer.consume(3, [1, 2, 3]) consumer.consume(2, [4, 5, 6]) consumer.consume(1, [7, 8, 9]) rows = consumer.close() assert len(rows) == 3 assert rows[0] == (3, [1, 2, 3]) assert rows[1] == (2, [4, 5, 6]) assert rows[2] == (1,...
[ "def test_row_intuition_rowgen(self):\n from csv import DictReader\n\n with open(df('rowgen_sources.csv')) as f:\n for e in DictReader(f):\n print(e['name'])\n gen = get_generator(e['url'])\n\n rows = list(gen)\n\n self.assertEqual...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a post_id, return a page where you see a list of groups, and can view the group members and add people to groups
def groups_for_posts(): post_id = request.args.get('post_id', 0) post = (db_session.query(Post) .filter(Post.id == post_id) .first()) return render_template('post_groups.html', groups=post.groups)
[ "def group_posts(request, slug):\n group = get_object_or_404(Group, slug=slug)\n posts = group.posts.all()\n paginator = Paginator(posts, 10)\n page_number = request.GET.get('page')\n page = paginator.get_page(page_number)\n return render(\n request,\n \"group.html\",\n {\"gro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a group_id, show a page where users can be added
def add_group_users(): group_id = request.args.get('group_id', 0) group = (db_session.query(Group) .filter(Group.id == group_id) .first()) return render_template('add_group_users.html', group=group)
[ "def view_group(request, groupid):\n\n try:\n group = models.BookiGroup.objects.get(url_name=groupid)\n except models.BookiGroup.DoesNotExist:\n return pages.ErrorPage(request, \"errors/group_does_not_exist.html\", {\"group_name\": groupid})\n except models.BookiGroup.MultipleObjectsReturned:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show a tensor as image
def show_tensor(tensor): import matplotlib.pyplot as plt plt.imshow(tensor.permute(1, 2, 0)) plt.show()
[ "def show_tensor(tensor):\n to_image(tensor).show()", "def imshow(tensor, title=None, figsize=None):\n image = _IMAGE_UNLOADER(tensor)\n\n plt.figure(figsize=figsize)\n plt.title(title)\n plt.axis('off')\n plt.imshow(image)", "def tensorToImage(tensor):\n arr = np.transpose(np.array(tensor.detach()),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select an option from a multiselect widget.
def select_for_kth_multiselect( page: Page, option_text: str, k: int, close_after_selecting: bool ) -> None: multiselect_elem = page.locator(".stMultiSelect").nth(k) multiselect_elem.locator("input").click() page.locator("li").filter(has_text=option_text).first.click() if close_after_selecting: ...
[ "def update_multi_select_option(self):\n if self.ui.multiCheckBox.isChecked():\n self.setup_multi_select()\n else:\n self.setup_single_select()", "def allow_multi_select(self, flag):\n self._multi_select = flag", "def select_option_by_index(self, index):\n selec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete an option from a multiselect widget.
def del_from_kth_multiselect(page: Page, option_text: str, k: int): multiselect_elem = page.locator(".stMultiSelect").nth(k) multiselect_elem.locator( f'span[data-baseweb="tag"] span[title="{option_text}"] + span[role="presentation"]' ).first.click()
[ "def delete_option(self, index1, index2=None):\n self.menu.delete(index1, index2)", "def remove(self, option):\n self.options.remove(option)", "def delete_selected_row(self):\n pass", "def remove_selected(self):\n\n if not self.selected:\n required_field_empty_warning(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Screenshot test to check that values are shown in dropdown.
def test_multiselect_show_values_in_dropdown( app: Page, assert_snapshot: ImageCompareFunction ): multiselect_elem = app.locator(".stMultiSelect").nth(0) multiselect_elem.locator("input").click() dropdown_elems = app.locator("li").all() assert len(dropdown_elems) == 2 for idx, el in enumerate(dr...
[ "def test_specialty_dropdown(self):\n\n specialty_dropdown = driver.find_elements_by_xpath(\"//*[@id='id_registrants-0-specialty']/option\")\n specialty_list = [specialty_dropdown[i].text for i in xrange(41)]\n assertEqual(specialty_list,\n [u'---------', u'Anesthesiology', u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should show long values correctly (with ellipses) in the dropdown menu.
def test_multiselect_long_values_in_dropdown( app: Page, assert_snapshot: ImageCompareFunction ): multiselect_elem = app.locator(".stMultiSelect").nth(4) multiselect_elem.locator("input").click() dropdown_elems = app.locator("li").all() for idx, el in enumerate(dropdown_elems): assert_snapsh...
[ "def _set_display_options(length, cols=True):\n if cols:\n pd.set_option(\"display.max_columns\", length)\n else:\n pd.set_option(\"display.max_rows\", length)", "def generate_item_dropdown(self, e):\n self.items_df = self.df.query(\"types == @self.food_type_dropdown.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should apply max selections when used in form.
def test_multiselect_max_selections_form(app: Page): select_for_kth_multiselect(app, "male", 8, False) expect(app.locator("li")).to_have_text( "You can only select up to 1 option. Remove an option first.", use_inner_text=True, )
[ "def max_selection_count(self) -> int:\n return self._max_selection_count", "def test_multiselect_option_over_max_selections(app: Page):\n app.locator(\".stCheckbox\").first.click()\n expect(app.locator(\".element-container .stException\")).to_contain_text(\n \"Multiselect has 2 options select...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should show an error when more than max_selections got selected.
def test_multiselect_option_over_max_selections(app: Page): app.locator(".stCheckbox").first.click() expect(app.locator(".element-container .stException")).to_contain_text( "Multiselect has 2 options selected but max_selections\nis set to 1" )
[ "def test_multiselect_max_selections_form(app: Page):\n select_for_kth_multiselect(app, \"male\", 8, False)\n expect(app.locator(\"li\")).to_have_text(\n \"You can only select up to 1 option. Remove an option first.\",\n use_inner_text=True,\n )", "def max_selection_count(self) -> int:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over all files in a year, for a certain brightness
def pages(year, brightness='70', basepath='/scratch/summit/diga9728/Moodys/Industrials/'): logging.basicConfig(level=logging.DEBUG) logging.debug( "Looking for day files from year %s, at brightness %s, in %s", year, brightness, basepath) # find all dirs that might contain .day file...
[ "def filter_raster_filenames_by_year(\n self, filenames: list,\n start_year: int,\n end_year: int\n ):\n new_list = []\n years = [str(year) for year in range(start_year, end_year+1)]\n for f in filenames:\n date_match = re.searc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create all relations on the artifact object as described in props.
def build_relations(self, props, override_tags): self._set_full_tags(props, override_tags) if props.get("team_id") is not None: self._connect_relation(self.neo.team, Team.find(props["team_id"])) if props.get("user_id") is not None: self._connect_relation(self.neo.user, Us...
[ "def _construct_one_to_many_relationship_artifacts(required=False):\n return schemas_artifacts.types.OneToManyRelationshipPropertyArtifacts(\n type=types.PropertyType.RELATIONSHIP,\n schema={}, # type: ignore\n sub_type=types.RelationshipType.ONE_TO_MANY,\n parent=\"RefModel\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds an artifact and saves it to this Connector
def find(cls, uid, force=True): artifact = ArtifactConnector() artifact.neo = Artifact.find(uid, force=force) return artifact
[ "def save_artifact(self, artifact):\n raise NotImplementedError", "def save_artifact(self, artifact):\n # TODO: Check if the file exists. If it does, skip writing it out.\n if artifact.item is None or artifact.item.payload is None:\n raise ArtifactMissingPayloadError(stage=artifact...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes a web request and handles result appropriately with retries. Returns the content of the web request if successfull.
def process_request(url, method, user, password, headers, payload=None, secure=False, binary=False): if payload != None and binary == False: payload = json.dumps(payload) elif payload != None and binary == True: payload = payload #configuring web request behavior if binary == True: ...
[ "def http_request(self, url):\n logging.debug(f\"Performing http_request for: {url}\")\n try:\n response = requests.get(url)\n return response.content\n except Exception as e:\n logging.error(f\"Error: {e}\")\n raise", "def retry_request():\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a factorlist reflecting evidence. Adjust all distributions in self.factorlist for the evidence given, and return the resulting new factorlist.
def condition(self, evidence: "A dictionary of {node name: value} mappings", in_place: "If True, write the changes back to self.factorlist." = False, reset_before: "If True, reset all evidence before adding this, otherwise keep old evidence." = False ) -> "the r...
[ "def add_factors(factors): \n global p_factors\n for (d,c) in factors:\n add(d,c)", "def addEvidence(self, evidence):\n\t\tfor key, value in evidence.items():\n\t\t\tnode = self.fg.bn.idFromName(key)\n\t\t\tneighbors = self.fg.neighbors[(node, 'children')] + self.fg.neighbors[(node, 'parents')]\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates text file containing directory description if the description doesn't exist
def create_file(textfile): try: err_text = '"This directory doesn\'t have description.' +\ 'Would you like to create one now?"' subprocess.check_call([ 'zenity', '--error', '--text=' + err_te...
[ "def create_description(description_path):\n description = open(description_path, 'w')\n description.write(\"No Description\")\n description.close()\n os.popen('attrib +h ' + description_path)", "def file_generate(path, content):\n if not os.path.exists(os.path.dirname(path)):\n os.makedirs(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return Python regular expression matching function based on Javascript style regexp.
def js_to_py_re_find(reg_exp): pattern, options = reg_exp[1:].rsplit("/", 1) flags = re.I if "i" in options else 0 def find(text): if "g" in options: results = re.findall(pattern, text, flags=flags) else: results = re.search(pattern, text, flags=flags) i...
[ "def compile_response_regex(regexp):\n return re.compile(regexp, re.IGNORECASE | re.DOTALL)", "def _getregex(self):\n return JSON_REGEX[os.name]", "def perlReToPythonRe(s):\n opener = closer = _getSep(s, True)\n if opener in '{[(<':\n closer = _closers[_openers.index(opener)]\n opener ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Born at the given position.
def born(self, i, j): box = self.grid[i][j] box.born()
[ "def bonfire():\n\n bf = Bonfire()\n bf.reparentTo(render)\n bf.setPos(localAvatar, 0, 0, 0)\n bf.startLoop()\n\n message = 'bonfire at %s, %s' % (localAvatar.getPos(), localAvatar.getHpr())\n print(message)\n return message", "def __init__(self, name, x, y, coins, world):\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes the box to determine its new state.
def process_box(self, box:Box): # Get the number of living boxes around this box n = 0 for i, j in box.get_pos_neighbours(): # Noth west if i >= 0 and j >= 0 and \ i < self.size[0] and j < self.size[1]: n += self.grid[i][j].living ...
[ "def update_box(self, box):\n self.box = box", "def update_boxes(self, action):\n\n # Unpack action\n r, c, o = action\n\n if o == 'h':\n try:\n self.completeBoxes[self.f(r, c)] += 1\n try:\n self.completeBoxes[self.f(r, c) - ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a generator that lists all the boxes in the grid.
def gen_boxes(self): for line in self.grid: for box in line: yield box
[ "def get_boxes(rows, cols):\n return [s + t for s in rows for t in cols]", "def boxs(board):\n boxes = []\n for grouped in group(board, 3):\n triple = [group(row, 3) for row in grouped]\n zipped = list(zip(*triple))\n rows = [flatten(row) for row in zipped]\n boxes.extend(rows...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the damage produced by a flood event of a specified mangitude. Returns a float representing the damage magnitude.
def estimate_damage(self, event): if event < self.dmg_thr: return 0. else: return 1. - np.exp(-((event - self.dmg_thr) / self.dmg_shape))
[ "def _calculate_damage(self, attack: int) -> int:\n adjusted_def = MAX_STATS_VAL - self.stats.defense\n def_buff = (attack - adjusted_def * attack / MAX_STATS_VAL)\n damage = attack - DamageMultiplier.NORMAL.value * def_buff\n return math.floor(damage)", "def calculate_damage(self, uni...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the residual damage given a specific disaster damage magnitude and preparedness level. Returns a float representing the residual damage magnitude
def estimate_residual_damage(self, damage, preparedness): dmg_fun = np.log(1 / self.res_dmg) return damage * np.exp(- dmg_fun * preparedness)
[ "def wavelength_rel(self) -> float:\n wavelength_rel = (\n sc.h\n / np.sqrt(\n 2 * sc.m_e * sc.e * 1000 * self.voltage * (1 + (sc.e * 1000 * self.voltage) / (2 * sc.m_e * sc.c**2))\n )\n * (10**10)\n )\n return wavelength_rel", "def r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the floodrelated losses (damage + costs) for the different warning outcomes after a flood event has taken place. Returns a float representing the loss magnitude.
def get_warning_loss(self, event, warning_outcome, preparedness): damage = self.estimate_damage(event) if warning_outcome == 'true positive': residual_damage = self.estimate_residual_damage(damage, preparedness) return residual_damage + event * self.mit_cst elif warning...
[ "def loss_cost(self):\n return round(self.bom_cost() * self.loss_rate / 100, 2)", "def loss(self) -> float:\n\n rews = self.transform_rewards()\n value_loss = self.value_loss(rews)\n return torch.cat(value_loss).sum()", "def gain_loss_calc(self):\r\n\t\ttotal_cost = self.purchase_pri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the number of occurrences of each warning outcome in the time series. Returns a float for each warning outcome.
def count_warning_outcomes(self, outcome_ls): count = Counter(outcome_ls) self.tn = count['true negative'] self.fn = count['false negative'] self.fp = count['false positive'] self.tp = count['true positive']
[ "def totalMissRate(self):\n sumRelease = 0\n sumMisses = 0\n for idx in range(self.n):\n sumRelease += self.statusTable[idx][1]\n sumMisses += self.statusTable[idx][2]\n return sumMisses / sumRelease", "def count_outcomes(self):\r\n counts = np.zeros(self.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the frequency of occurrence of flood events. Returns a float representing the disaster frequency [0, 1]
def flood_frequency(self): return (self.tp + self.fn) / (self.tn + self.fn + self.fp + self.tp)
[ "def freq_per_day_of_the_week(self):\n feat = [int(log.split('\\t')[4]) for log in self.userdata[1:]]\n freq = collections.Counter(feat)\n for i in range(1, 8):\n if freq.has_key(i) is False:\n freq[i] = 0\n return freq", "def recoilfreq(self):\n\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the return period of flood events. Returns a float representing the return period in years.
def return_period(self): if self.tp + self.fn == 0.: # raise ValueError('No flood events recorded in the time series.') return None else: return (self.tn + self.fn + self.fp + self.tp + 1) / (self.tp + self.fn)
[ "def death_growth(self):\n\t\tdeath_year_growth = (60/self.death_rate)*60*24*365\n\n\t\treturn death_year_growth", "def yearly_calculation(self):\n\t\tyears_to_calculate = self.year_to_calculate - self.current_year\n\n\t\tyearly_population = 0\n\n\t\tfor years in range(1,years_to_calculate):\n\t\t\tyearly_populat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the false alarm rate (probability of false detection) for the warning system. Returns a float representing the false alarm rate [0, 1]
def false_alarm_rate(self): if self.tn + self.fp == 0.: # raise ValueError('No normal events recorded in the time series.') return None else: return self.fp / (self.tn + self.fp)
[ "def false_alarm_ratio(self):\n if self.fp + self.tp == 0.:\n # raise ValueError('No alarms were raised during these period.')\n return None\n\n else:\n return self.fp / (self.fp + self.tp)", "def false_alarm_rate(self, keywords=None):\n\n if keywords is None:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the false alarm ratio for the warning system. Returns a float representing the false alarm ratio [0, 1]
def false_alarm_ratio(self): if self.fp + self.tp == 0.: # raise ValueError('No alarms were raised during these period.') return None else: return self.fp / (self.fp + self.tp)
[ "def false_alarm_rate(self):\n if self.tn + self.fp == 0.:\n # raise ValueError('No normal events recorded in the time series.')\n return None\n\n else:\n return self.fp / (self.tn + self.fp)", "def false_alarm_ratio(contingency, yes_category=2):\n \n no_catego...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
write the statistics to the output file
def save_statistics(self, statfile, mode='single_run'): path_out = os.getcwd() + '\\..\\output\\' + mode + '\\' if not os.path.exists(path_out): os.makedirs(path_out) if mode == 'single_run': df = pd.DataFrame.from_dict(self.stats, orient='index') df.to_csv(p...
[ "def write_results(filename):", "def exportStatistics(self, filename):\n\t\ttimepoint = scripting.visualizer.getTimepoint()\n\t\tself.writeToFile(filename, self.dataUnit, timepoint)", "def write_results(self, output):\n\t\t\t# First write counts for emissions\n\t\t\tfor line in self.results: \n\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of dictionaries representing all the rows in the area table.
def get_all_areas(): con = connect('measures.sqlite') cur = con.cursor() cur.execute("select * from area") results = [] for row in cur.fetchall(): results.append(row) con.close() return results
[ "def get_rows(self) -> List[dict]:\n\n return self.source.rows", "def get_locations_for_area(area_id):\n con = connect('measures.sqlite')\n cur = con.cursor()\n cur.execute('select * from location where location_area = ?', (area_id,))\n return_table = []\n \n for row in cur:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of dictionaries giving the locations for the given area.
def get_locations_for_area(area_id): con = connect('measures.sqlite') cur = con.cursor() cur.execute('select * from location where location_area = ?', (area_id,)) return_table = [] for row in cur: return_table.append(row) con.close() return return_table
[ "def __list_area_locs(self, top_left_location, width, height):\n\n # Get all locations in the rectangle\n xs = list(range(top_left_location[0], top_left_location[0] + width))\n ys = list(range(top_left_location[1], top_left_location[1] + height))\n locs = list(itertools.product(xs, ys))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of dictionaries giving the measurement rows for the given location.
def get_measurements_for_location(location_id): con = connect('measures.sqlite') cur = con.cursor() cur.execute('select * from measurement where measurement_location = ?', (location_id,)) results = cur.fetchall() con.close() return results
[ "def results_by_location(results, metric):\n data = {}\n metric_indexes = {\"median\": 0, \"mean\": 2, \"min\": 3, \"max\": 4}\n if metric not in metric_indexes:\n raise ValueError(f\"{metric} is not valid metric name. Valid names: 'median', 'mean', 'min', 'max'\")\n\n stat = metric_indexes[metri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of rows from the category table that all contain the given area.
def get_categories_for_area(area_id): con = connect('measures.sqlite') cur = con.cursor() cur.execute('select category.* from category,category_area where category.category_id = category_area.category_id and category_area.area_id = ?', (area_id,)) return_table = [] for row in cur: return_tab...
[ "def get_all_areas():\n con = connect('measures.sqlite')\n cur = con.cursor()\n cur.execute(\"select * from area\")\n results = []\n for row in cur.fetchall():\n results.append(row)\n\n con.close()\n\n return results", "def get_locations_for_area(area_id):\n con = connect('measures....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Legacy stored samples that are missing a status value should be treated as UNSET when finding the sample status time for participant summary
def test_sample_time_with_missing_status(self): participant = self._insert(Participant(participantId=1, biobankId=11)) confirmed_time = datetime.datetime(2018, 3, 1) sample = self.data_generator.create_database_biobank_stored_sample( biobankId=participant.biobankId, test...
[ "def test_skipped_status(self):\n job_set = self._jm.run([self._qc]*2, backend=self.fake_api_backend,\n max_experiments_per_job=1)\n jobs = job_set.jobs()\n jobs[1]._job_id = 'BAD_ID'\n statuses = job_set.statuses()\n self.assertIsNone(statuses[1])", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that a participant that has achieved CORE_MINUS_PM status isn't downgraded from it
def testDowngradeCoreMinusPm(self): sample_time = datetime.datetime(2019, 3, 1) self.mock_ehr_interest_ranges.return_value = [] summary = ParticipantSummary( participantId=1, biobankId=2, consentForStudyEnrollment=QuestionnaireStatus.SUBMITTED, nu...
[ "def CheckPowerFailure(self):\n\t\tPowerFailure_bit = self.readRegister(DAY); #Read meridian bit\t\n\t\tPowerFail = 0\n\t\n\t\tif((PowerFailure_bit & PWRFAIL) == PWRFAIL):\n\t\t\tPowerFail = 1\n\t\telse:\n\t\t\tPowerFail = 0\n\t\t\n\t\tPowerFailure_bit &= ~PWRFAIL\t\t\t#Clear Power failure bit\n\t\tself.writeR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a new BiobankOrder (same values every time) with valid/complete defaults. Kwargs pass through to BiobankOrder constructor, overriding defaults.
def _make_biobank_order(self, **kwargs): for k, default_value in ( ("biobankOrderId", "1"), ("created", clock.CLOCK.now()), ("participantId", self.participant.participantId), ("sourceSiteId", 1), ("sourceUsername", "fred@pmi-ops.org"), ("co...
[ "def __init__(self, species, qty, country_code):\n\n #also initializes the __init__ method from the parent class\n super(InternationalMelonOrder,self).__init__(species, qty)\n #set International order class specific attributes to order for country code,\n #order_type and tax\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a new PhysicalMeasurements (same values every time) with valid/complete defaults. Kwargs pass through to PM constructor, overriding defaults.
def _make_physical_measurements(self, **kwargs): for k, default_value in ( ("physicalMeasurementsId", 1), ("participantId", self.participant.participantId), ("createdSiteId", 1), ("finalized", TIME_3), ("finalizedSiteId", 2), ): if ...
[ "def _make_physical_measurements(self, **kwargs):\n resource = json.loads(self.measurement_json)\n\n if 'resource' in kwargs:\n resource = json.loads(kwargs.pop('resource'))\n\n for k, default_value in (\n (\"physicalMeasurementsId\", 1),\n (\"participantId\", s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Goes through all matches and calculates new elo for teams with each map causing a new elo shift, rather than an overall bo3 / bo5
def calculate_matches( match_urls: List[str], teams: Dict[int, Team], lut: Dict[int, int]=None) \ -> Dict[int, Match]: matches = {} for match in match_urls: print("Scraping", match) team_1id, results, team_2id \ = TCS_Scraper.scrape_match(match, teams, lut=lut)...
[ "def handleMatchResults(players, winner, average_mmr):\n \n #-If Team 1 won\n \n if (winner == 2):\n \n # -Runs through the teams, going through the winners 0-4\n #-then runs through losers 5-9\n \n for i in range(TEAM_SIZE * 2):\n if (i < TEAM_SIZE):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of tenants required by resource. Important for the filtering feature.
def required_tenants(self): return []
[ "def tenants(self):\n self.auth_token\n request = Request(\n method='get',\n endpoint='/tenants',\n )\n\n def response_handler(resp):\n if not resp.is_success:\n raise TenantListError(resp, request)\n retval = []\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the words in the line are comments or code
def _is_comment(line): code_counter = 0 code_word = keyword.kwlist for word in line: if word == code_word: code_counter += 1 return code_counter < num_max_of_python_word_for_comment
[ "def _is_comment_line(self, line):\r\n return line[0] in self.comment_chars", "def is_comment(self, line):\r\n return line.startswith(self.comment_chars) or not line", "def _is_comment(self,line: str) -> bool:\n if line[0].isdigit():\n return False\n else:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the line is the start of a multi line comment
def _is_start_comment(line): line = line.strip(' \t\n\r') return bool(line.startswith("'''") or line.startswith('"""'))
[ "def _is_comment_line(self, line):\r\n return line[0] in self.comment_chars", "def is_comment(self, line):\r\n return line.startswith(self.comment_chars) or not line", "def is_line_comment(self, token):\n t1, t2, t3, t4, t5 = token\n kind = token_module.tok_name[t1].lower()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the line is the end of a multi line comment
def _is_end_comment(line): return bool((line.endswith("'''") or line.endswith('"""')))
[ "def is_comment(self, line):\r\n return line.startswith(self.comment_chars) or not line", "def _is_comment_line(self, line):\r\n return line[0] in self.comment_chars", "def _is_comment(self,line: str) -> bool:\n if line[0].isdigit():\n return False\n else:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function informs user (via messages) about existing hashes (MD5, SHA1, SHA256) when creating or updating artifacts this may legit or even interesting for the analyst or because of an error during workflow
def check_existing_hashes(self, request): # check for md5 for this artifact if self.artifact_md5: # exclude this artifact, only check all others artifacts = Artifact.objects.filter(artifact_md5=self.artifact_md5).exclude( artifact_id=self.artifact_id ...
[ "def test_compute_hashes(self):\n sha, md5 = file_hash.compute_hashes('/hello_world')\n self.assertEqual(hashlib.sha256(self._test_contents.encode('utf-8')).hexdigest(), sha)\n self.assertEqual(hashlib.md5(self._test_contents.encode('utf-8')).hexdigest(), md5)", "async def sha1cmd(self, messa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do these nums have same frequencies of digits? >>> same_frequency(551122, 221515) True >>> same_frequency(321142, 3212215) False >>> same_frequency(1212, 2211) True
def same_frequency(num1, num2): num_1 = list(str(num1)) num_2 = list(str(num2)) digits = set(str(num1)) & set(str(num2)) for digit in digits: digit1 = num_1.count(digit) digit2 = num_2.count(digit) if digit1 != digit2: return False return True
[ "def same_frequency(num1, num2):\n \n return sort_num_List(num1) == sort_num_List(num2)", "def related_by_digit_permutation(num_a, num_b):\n from collections import Counter\n\n return Counter(str(num_a)) == Counter(str(num_b))", "def test_assertSimilarFreqs_true(self):\n observed = [2,2,3,2,1,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for create_token
def test_create_token(self): pass
[ "def test_user_create_token(self):\n pass", "def test_create_token_exchange_using_post(self):\n pass", "def test_generate_token_service_account(self):\n pass", "def test_1_generate_token(self):\n SpotifyTest.token = spotify.generate_token()\n self.assertIsNotNone(SpotifyTest...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for delete_customer_token
def test_delete_customer_token(self): pass
[ "def test_delete_token_service_account(self):\n pass", "def test_get_customer_token(self):\n pass", "def test_delete_customer(self):\n logger.info('-- Testing delete an existing customer. --')\n bo.delete_customer(5)\n the_customer = bo.search_customer(5)\n expect_res =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for delete_token
def test_delete_token(self): pass
[ "def test_delete_customer_token(self):\n pass", "def test_user_delete_access_token(self):\n pass", "def test_delete_token_service_account(self):\n pass", "def delete_token(self, token):\n raise NotImplementedError", "def test_delete_ok(self, fake_logger, fake_strict_redis):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for delete_token_service_account
def test_delete_token_service_account(self): pass
[ "def test_delete_customer_token(self):\n pass", "def test_user_delete_access_token(self):\n pass", "def test_generate_token_service_account(self):\n pass", "def test_delete_service_key(self):\n pass", "def test_delete_account_permission_using_delete(self):\n pass", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for generate_token_service_account
def test_generate_token_service_account(self): pass
[ "def test_get_tokens_service_account(self):\n pass", "def test_user_create_token(self):\n pass", "def test_delete_token_service_account(self):\n pass", "def test_create_service_key(self):\n pass", "def test_update_token_name_service_account(self):\n pass", "def test_get_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_all_tokens
def test_get_all_tokens(self): pass
[ "def test_user_get_tokens(self):\n pass", "def test_get_customer_tokens(self):\n pass", "def _get_tokens(self):\n return new_tokens", "def test_tokenstores_get(self):\n pass", "def get_all_tokens(cls) -> FrozenSet[str]:\n return cls.SPECIAL.union(\n cls.AGGR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_customer_token
def test_get_customer_token(self): pass
[ "def test_get_customer_tokens(self):\n pass", "def test_delete_customer_token(self):\n pass", "def test_generate_token_service_account(self):\n pass", "def test_get_tokens_service_account(self):\n pass", "def test_user_get_tokens(self):\n pass", "def test_user_create_tok...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_customer_tokens
def test_get_customer_tokens(self): pass
[ "def test_get_customer_token(self):\n pass", "def test_user_get_tokens(self):\n pass", "def test_get_tokens_service_account(self):\n pass", "def test_delete_customer_token(self):\n pass", "def test_generate_token_service_account(self):\n pass", "def test_get_all_tokens(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_tokens_service_account
def test_get_tokens_service_account(self): pass
[ "def test_generate_token_service_account(self):\n pass", "def test_delete_token_service_account(self):\n pass", "def get_serviceaccount_tokens():\n gqlapi = gql.get_api()\n return gqlapi.query(SERVICEACCOUNT_TOKENS_QUERY)[\"namespaces\"]", "def test_get_service_key(self):\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for update_token_name
def test_update_token_name(self): pass
[ "def test_update_token_name_service_account(self):\n pass", "def test_update_name_expired_token(self):\n self.user.token = 'expired'\n server.db.session.commit()\n\n request = {'name': 'New test group'}\n rv = self.put('/group/{group_id}/'.format(group_id=self.group.id),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for update_token_name_service_account
def test_update_token_name_service_account(self): pass
[ "def test_update_token_name(self):\n pass", "def test_generate_token_service_account(self):\n pass", "def test_update_service_key(self):\n pass", "def test_get_tokens_service_account(self):\n pass", "def test_delete_token_service_account(self):\n pass", "def test_update_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the host and service from a line of text
def getHost(textLine): host = '' service = '' regexServiceHost = re.compile(r'(\w+):\s*(\d+[.]\d+([.]([*]|\d+)){2})') matches = regexServiceHost.match(textLine) if matches != None: service = matches.group(1) host = matches.group(2) return (service, host)
[ "def getHost(anHTTPmsg):\n try:\n for line in anHTTPmsg.splitlines():\n words = line.split()\n if (words[0] == \"Host:\") and (len(words)>1):\n return words[1]\n raise ValueError, \"cannot find 'Host:' keyword in HTTP message\"\n except Exception:\n raise ValueError, \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the task index
def get_task_index(self): return self.task_index
[ "def get_num_tasks(self):\n cursor = self.db_connection.cursor()\n cursor.execute('SELECT COUNT(*) FROM task_list')\n num = cursor.fetchone()\n\n return num[0]", "def get_index(self) -> int:\n return self._index", "def activity_index(self):\n return self._activity_index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of display modes.
def getDisplayModes(self,obj): return []
[ "def getViewModeDisplayList(self):\n return VIEW_MODES", "def modes(self):\n return self.get_attr_set('modes')", "def preset_modes(self) -> list:\n try:\n return list(self._ctrl_params['mode'].keys())\n except KeyError:\n return []", "def modes(self) -> Set[st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the name of the property that has changed
def onChanged(self, vp, prop): App.Console.PrintMessage("Change property: " + str(prop) + "\n")
[ "def on_property_change(self, name, old_value, new_value):\n pass", "def _get_name(self) -> \"std::string\" :\n return _core.Property__get_name(self)", "def _propertyname(self, property, actual):\n if self.prefs.defaultPropertyName and not self.prefs.keepAllProperties:\n return p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publication has been found and is being parsed so we store its tag and its key
def startElement(self, tag, attributes): self.current_field = tag for publicationTag in publications: if tag == publicationTag: self.isPublication = True self.tag = tag self.key = str(attributes['key'])
[ "def extract_pub_info(elem):\n pub_info_dict = dict()\n pub_info_dict.update({'wos_id': extract_wos_id(elem)})\n\n pub_info = elem.find('.static_data/summary/pub_info').attrib\n for key in ['sortdate', 'has_abstract', 'pubtype', 'pubyear', 'pubmonth', 'issue']:\n if key in pub_info.keys():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate posterior using grid approximation
def posterior(self): # create a grid over which we will calculate the likelihood self.p_grid = np.linspace(0, 1, num = self.g) # calculate the probability of observing the data self.likelihood = stats.binom.pmf(self.k,self.n,p = self.p_grid) # multiply with prior unst_po...
[ "def posteriorLikelihood(self, step):", "def get_posterior(self, x):\n N = x.shape[0]\n n_component = self._n_components\n z_ik = np.zeros((N,n_component))\n conditional = self.get_conditional(x)\n marginal = self.get_marginals(x)\n for i in range(n_component):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process System Details worksheet
def process(workbook: Any, content: str) -> None: worksheet = workbook.get_sheet_by_name('System Details') headers = get_parser_header(SYSTEM_DETAILS_TMPL) RowTuple = namedtuple('RowTuple', headers) # pylint: disable=invalid-name build_header(worksheet, headers) system_details_out = run_parser_...
[ "async def systeminfo(self, ctx):\r\n\r\n\t\tres = f\"[OS Type][{sys.platform}]\"\r\n\t\tinfo = cpuinfo.get_cpu_info()\r\n\t\tres += f\"\\n[CPU][{psutil.cpu_count(logical=False)} Cores / {psutil.cpu_count()} Threads]\"\r\n\t\tres += f\"\\n[CPU Usage][%{str(psutil.cpu_percent())}]\"\r\n\t\tvmem = psutil.virtual_memo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> Function you need to write >>> check whether centroids1==centroids >>> add proper code to handle infinite loop if it never converges
def converged(centroids1, centroids2): pass
[ "def _updateCentroids(self) -> None:\n self.centroids_OLD = self.centroids_NEW[self.centroids_NEW[:, 2] >= 0, :2]\n self.centroids_NEW = None", "def __should_stop(self, old_centroids, centroids, iterations):\n if iterations > self.__max_iterations:\n return True\n return old_centroids == ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates age field when birth_date is changed
def _onchange_birth_date(self): if self.doctor_dob: d1 = datetime.strptime(str(self.doctor_dob), "%Y-%m-%d") d2 = datetime.today() self.doctor_age = relativedelta(d2, d1).years
[ "def setBirthday(self, birthdate):\n self.birthday = birthdate", "def set_age(self, age=0):\r\n self.age = age", "def set_age(self, new_age: int):\n self.__age = new_age", "def age_calc(self):\n if self.professor_dob is not False:\n self.age = (datetime.today().d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A reception report, consisting of time (seconds), location (numpy array), rssi (Watts), and bearing (bearing)
def __init__(self,time,location,rssi,bearing,tx_identity): self.time=time self.location=np.array(location) # Note: creates a copy! self.rssi=rssi self.bearing=bearing self.tx_identity=tx_identity
[ "def reception(self,rx_time,rx_location,rx_noise_level=None,rx_antenna_beamwidth=None):\n dist=np.linalg.norm(rx_location-self.location)\n \n if rx_noise_level is not None:\n rssi_gen=scipy.stats.rice(np.sqrt(self.power / (2.0*np.pi*rx_noise_level*dist**2)),scale=np.sqrt(rx_noise_lev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produce a reception report for the transmitter from a rx_location (3slot numpy array) given rx_noise_level (Watts) and rx_antenna_beamwidth (degrees)
def reception(self,rx_time,rx_location,rx_noise_level=None,rx_antenna_beamwidth=None): dist=np.linalg.norm(rx_location-self.location) if rx_noise_level is not None: rssi_gen=scipy.stats.rice(np.sqrt(self.power / (2.0*np.pi*rx_noise_level*dist**2)),scale=np.sqrt(rx_noise_level/2.0)) ...
[ "def __init__(self,rx_noise_level=None,rx_antenna_beamwidth=None,name=None):\n self.rx_noise_level=rx_noise_level\n self.rx_antenna_beamwidth=rx_antenna_beamwidth\n self.name=None\n self.reception_reports=[]", "def add_reception(self,time,location,transmitter):\n self.reception_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A receiver with a name and a fixed set of equipment and possibly variable location. The equipment has a background noise level and antenna beamwidth. Locations get paired with the reception reports of the receiver, not in this constructor
def __init__(self,rx_noise_level=None,rx_antenna_beamwidth=None,name=None): self.rx_noise_level=rx_noise_level self.rx_antenna_beamwidth=rx_antenna_beamwidth self.name=None self.reception_reports=[]
[ "def reception(self,rx_time,rx_location,rx_noise_level=None,rx_antenna_beamwidth=None):\n dist=np.linalg.norm(rx_location-self.location)\n \n if rx_noise_level is not None:\n rssi_gen=scipy.stats.rice(np.sqrt(self.power / (2.0*np.pi*rx_noise_level*dist**2)),scale=np.sqrt(rx_noise_lev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Have this receiver make a report of a given Transmitter at a given time and location
def add_reception(self,time,location,transmitter): self.reception_reports.append(transmitter.reception(time, location, self.rx_noise_level, ...
[ "def reception(self,rx_time,rx_location,rx_noise_level=None,rx_antenna_beamwidth=None):\n dist=np.linalg.norm(rx_location-self.location)\n \n if rx_noise_level is not None:\n rssi_gen=scipy.stats.rice(np.sqrt(self.power / (2.0*np.pi*rx_noise_level*dist**2)),scale=np.sqrt(rx_noise_lev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Courtesy function for plotting the bearings in this Reeiver's reception reports
def plot_bearings(self): plt.plot([r.bearing for r in self.reception_reports])
[ "def plot_residual_distributions(ax, radar, results, flight, shapes=None):\n style_file = Path(__file__).parent / \"..\" / \"misc\" / \"matplotlib_style.rc\"\n plt.style.use(style_file)\n if shapes is None:\n shapes = [\"LargePlateAggregate\", \"LargeColumnAggregate\", \"8-ColumnAggregate\"]\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Courtesy function for plotting the Received Signal Strength Indications (RSSI) in this Reeiver's reception reports
def plot_rssis(self): plt.plot([r.rssi for r in self.reception_reports])
[ "def rssi_values(self):\n return _raw_util.raw_message_sptr_rssi_values(self)", "def plot_power_spectrum_density(self):\n center_freq = self.get_sdr_centerfreq()\n\n plt.ion() # turn interactive mode on\n fig = plt.figure()\n ax = fig.add_subplot(111)\n # init x and ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Courtesy function for plotting the locations in this Reeiver's reception reports
def plot_locations(self): plt.plot([r.location[0] for r in self.reception_reports], [r.location[1] for r in self.reception_reports])
[ "def dispersion_diagram(data, p1, p2, qual, lat, long, show_axes):\n u = data[qual].unique()\n fig, ax = plt.subplots(figsize=(lat, long))\n for i in range(len(u)):\n x = data.loc[data[qual] == u[i]][p1]\n y = data.loc[data[qual] == u[i]][p2]\n ax.scatter(x, y)\n # ax.set_xlabel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write this Receiver's reception reports to a CSV file
def write_csv(self,filename): with open(filename,'wt') as fp: for r in self.reception_reports: fp.write(repr(r)+'\n')
[ "def writeCSV(self):\n\n with open(self.output_filename, mode='w') as output_file:\n order_output_str = \"ORDER_ID,TYPE,ITEM_1,QTY_1,EXGST_1,ITEM_2,QTY_2,EXGST_2,ITEM_3,QTY_3,EXGST_3,ITEM_4,QTY_4,EXGST_4,CUPS,GST,TAX,ORDER_TOTAL,AMT_TENDERED,CHANGE\"\n output_writer = csv.DictWriter(out...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a CSV file containing reception reports. These are appended to this Receiver's reception reports
def read_csv(self,filename): with open(filename,'rt') as fp: for row in csv.reader(fp): self.reception_reports.append(ReceptionReport(time=float(row[0]), location=np.array([float(row[1]),float(row[2])]), ...
[ "def read_csv(self, filename):\n\n self.response.read_csv(filename)", "def write_csv(self,filename):\n with open(filename,'wt') as fp:\n for r in self.reception_reports:\n fp.write(repr(r)+'\\n')", "def get_report():\n response = requests.get(REPORT_URL)\n return cs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }