query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Returns list of IDs of tags for specified model name by (code, name) pair
def get_tag_ids(self, cr, uid, model, code=None, name=None, context=None): assert bool(code) or bool(name), "code or name must not be None! (code=%s;name=%s)" % (code, name) tag_domain = [('model_id.model', '=', model)] if code is not None: tag_domain.append(('code', '=', code)) ...
[ "def get_model_specific_tags(model_name: str) -> djm.QuerySet:\n return tgm.Tag.objects.filter(\n taggit_taggeditem_items__content_type__model=model_name,\n )", "def _getTagIDs(self):\n paths = self._criteria.get('paths')\n if paths:\n store = getMainStore()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if all of supplied objects have tag with specified code and/or name Return True if all object ids has specified tags
def check_tag(self, cr, uid, ids, code=None, name=None, context=None): assert bool(code is None) or bool(name is None), "code or name must not be None" tag_domain = [('id', 'in', ids)] if code is not None: tag_domain.append(('tag_ids.code', '=', code)) if name is not None: ...
[ "def tagsAre(self,tags):\n\t\treturn all([x in self.tags for x in tags])", "def has_tag(*tags: str):\n\n @trigger\n def ret(track, p, d):\n return any(t in track.tags for t in tags)\n\n return ret", "def tagged(self, entities, tags):\n return any((entities & self.state.entities_by_tag(tag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the path to a raw json asset and convert it to target directory.
def processed_json_dir(path): return os.path.dirname(path.replace(RAW_ASSETS_PATH, ASSETS_PATH))
[ "def processed_json_path(path):\n return path.replace(RAW_ASSETS_PATH, ASSETS_PATH).replace('.json', '.bin')", "def copy_json():\n sourcePath = 'contents/external/'\n targetPath = 'build/external/'\n for base,subdirs,files in os.walk(sourcePath):\n for file in files:\n orig = os.path.j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes this object's schema, input_files and output_path.
def __init__(self, schema, input_files, output_path): self.schema = schema self.input_files = input_files self.output_path = output_path
[ "def __init__(self, config):\n self.schemas = {}\n self.config = config\n\n full_schema_dir = f\"{config.main_directory}/{config.schema_directory}/\"\n\n files = find_files(\n file_extensions=[\".yaml\", \".yml\", \".json\"],\n search_directories=[full_schema_dir],\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the path to a raw png asset and convert it to target webp path.
def processed_texture_path(path): return path.replace(RAW_ASSETS_PATH, ASSETS_PATH).replace('png', 'webp')
[ "def img2webp(path):\n file, ext = os.path.splitext(path)\n image = Image.open(path).convert(\"RGBA\")\n image = ImageOps.expand(image, 75)\n image.save(file + \".webp\", \"WEBP\")\n os.remove(path)", "def image_webp():\n data = resource(\"images/wolf_1.webp\")\n return Response(data, headers...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the flatbuffer compiler on the given json file and schema.
def convert_json_to_flatbuffer_binary(json, schema, out_dir): command = [FLATC, '-o', out_dir, '-b', schema, json] run_subprocess(command)
[ "def run(\n self,\n input_file=sys.stdin,\n output_file=sys.stdout,\n schema_map=None,\n ):\n schema_map, error_logs = self.deduce_schema(\n input_file, schema_map=schema_map\n )\n\n for error in error_logs:\n logging.info(\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the webp converter on the given png file.
def convert_png_image_to_webp(png, out, quality=80): command = [CWEBP, '-q', str(quality), png, '-o', out] run_subprocess(command)
[ "def img2webp(path):\n file, ext = os.path.splitext(path)\n image = Image.open(path).convert(\"RGBA\")\n image = ImageOps.expand(image, 75)\n image.save(file + \".webp\", \"WEBP\")\n os.remove(path)", "def generate_webp_textures():\n input_files = PNG_TEXTURES['input_files']\n output_files = PNG_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the source file needs to be rebuilt.
def needs_rebuild(source, target): return not os.path.isfile(target) or ( os.path.getmtime(source) > os.path.getmtime(target))
[ "def _build_must_rebuild(product, sources):\n if not product.exists():\n return True\n plast = product.stat().st_mtime\n if _build_self_time >= plast:\n return True\n for source in sources:\n if source.stat().st_mtime >= plast:\n return True\n return False", "def _has_code_changes(self) -> bool...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the path to a raw json asset and convert it to target bin path.
def processed_json_path(path): return path.replace(RAW_ASSETS_PATH, ASSETS_PATH).replace('.json', '.bin')
[ "def processed_json_dir(path):\n return os.path.dirname(path.replace(RAW_ASSETS_PATH, ASSETS_PATH))", "def processed_texture_path(path):\n return path.replace(RAW_ASSETS_PATH, ASSETS_PATH).replace('png', 'webp')", "def texture_copy(self, project, asset, path):\n from pypeapp import execute\n\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the flatbuffer compiler on the all of the flatbuffer json files.
def generate_flatbuffer_binaries(): for element in FLATBUFFERS_CONVERSION_DATA: schema = element.schema output_path = element.output_path if not os.path.exists(output_path): os.makedirs(output_path) for json in element.input_files: target = processed_json_path(json) if needs_rebuild(...
[ "def main():\n for json_file in os.listdir('json'):\n json_pathfile = os.path.join('json', json_file)\n if os.path.isfile(json_pathfile):\n print(json_pathfile)\n json_data = load_json(json_pathfile)\n if len(json_data['results']) > 0:\n conversation ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the webp converter on off of the png files.
def generate_webp_textures(): input_files = PNG_TEXTURES['input_files'] output_files = PNG_TEXTURES['output_files'] if not os.path.exists(TEXTURE_PATH): os.makedirs(TEXTURE_PATH) for png, out in zip(input_files, output_files): if needs_rebuild(png, out): convert_png_image_to_webp(png, out, WEBP_QU...
[ "def main():\n argvs = sys.argv\n argc = len(argvs)\n if argc == 1:\n print('usage: convert2png.py <path/to/*.ppm> ...')\n sys.exit(1)\n\n os.makedirs('result/convert2png', exist_ok=True)\n\n for i in range(1, argc):\n img = cv2.imread(argvs[i])\n\n # root, ext = os.path.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all the processed webp textures.
def clean_webp_textures(): for webp in PNG_TEXTURES['output_files']: if os.path.isfile(webp): os.remove(webp)
[ "def clearTextures(self):\r\n GL.glDeleteTextures(1, self._texID)\r\n GL.glDeleteTextures(1, self._maskID)", "def destroy(self):\n\t\tglDeleteTexture((self.index,))\n\t\tdel self.index", "def destroy(self):\n\n self.cmapTexture.destroy()\n\n for tex in (self.modulateTexture,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all the processed flatbuffer binaries.
def clean_flatbuffer_binaries(): for element in FLATBUFFERS_CONVERSION_DATA: for json in element.input_files: path = processed_json_path(json) if os.path.isfile(path): os.remove(path)
[ "def clean(self):\n # Delete vertices / faces / colors / normals :\n self._vert_buffer.delete()\n self._index_buffer.delete()\n self._normals_buffer.delete()\n self._xrange_buffer.delete()\n self._math_buffer.delete()", "def flush_data(): \n files = glob.glob(DATA_D...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints an error message to stderr for BuildErrors.
def handle_build_error(error): sys.stderr.write('Error running command `%s`. Returned %s.\n' % ( ' '.join(error.argv), str(error.error_code)))
[ "def error(message):\n print(message, file=sys.stderr)", "def print_error(msg):\n print_message(color_string('ERROR', 'FAIL'), 'EXITING: [%s] failed to execute properly.' % msg)", "def err(msg):\n if VERBOSE: sys.stderr.write(msg)", "def print_error(message):\n from sys import stderr\n print(\"\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots the color mapping together with the fixed points. Creates a movie file.
def tracer_movie(datadir = 'data/', tracerFile = 'tracers.dat', fixedFile = 'fixed_points.dat', zlim = [], head_size = 3, hm = 1, imageDir = './', movieFile = 'fixed_points.mpg', fps = 5.0, bitrate = 1800): import pylab as plt # read the ...
[ "def plot_skymap(self):\n ra = np.array(self.data_table[\"RA\"])\n dec = np.array(self.data_table[\"Dec\"])\n rs = np.log(np.array(self.data_table[\"Redshift\"]))\n\n plt.figure()\n plt.subplot(111, projection=\"aitoff\")\n\n cm = plt.cm.get_cmap('RdYlGn_r')\n sc = p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots an image and the projections (sums) of it on the x, y axes.
def plot_image_and_proj(image, title="", **kwargs): fig = plt.figure() gs = gridspec.GridSpec(3, 2, width_ratios=[3, 1], height_ratios=[0.2, 3, 1]) ax0 = plt.subplot(gs[1,0]) plt.title(title) ims = plt.imshow(image, aspect="auto", **kwargs) ax2 = plt.subplot(gs[2,0], sharex=ax0, ) plt....
[ "def plot_projected_image(imgs):\n if not isinstance(imgs, xarray.DataArray):\n raise TypeError(\"Please pass in one image wavelength at a time\")\n\n cmap = {\"0428\": \"Blues\", \"0558\": \"Greens\", \"0630\": \"Reds\"}\n\n for img in imgs:\n fg = figure()\n if cartopy is None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request data for a list of block hashes.
def send_get_data(self, block_hashes): msg = msg_getdata() for x in block_hashes: msg.inv.append(CInv(MSG_BLOCK, x)) self.send_message(msg)
[ "async def get_block_records_by_hash(self, header_hashes: List[bytes32]):\n if len(header_hashes) == 0:\n return []\n\n all_blocks: Dict[bytes32, BlockRecord] = {}\n if self.db_wrapper.db_version == 2:\n async with self.db_wrapper.read_db() as conn:\n async ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test whether the last headers announcements received are right. Headers may be announced across more than one message.
def check_last_headers_announcement(self, headers): test_function = lambda: (len(self.recent_headers_announced) >= len(headers)) self.wait_until(test_function) with p2p_lock: assert_equal(self.recent_headers_announced, headers) self.block_announced = False sel...
[ "def has_bad_headers(self):\n\n headers = [self.sender, self.reply_to] + self.recipients\n for header in headers:\n if _has_newline(header):\n return True\n\n if self.subject:\n if _has_newline(self.subject):\n for linenum, line in enumerate(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test whether the last announcement received had the right inv. inv should be a list of block hashes.
def check_last_inv_announcement(self, inv): test_function = lambda: self.block_announced self.wait_until(test_function) with p2p_lock: compare_inv = [] if "inv" in self.last_message: compare_inv = [x.hash for x in self.last_message["inv"].inv] ...
[ "def has_invites(self):\r\n return self.invite_ct > 0", "def test_invited(self) -> None:\n\n self._perform_background_initial_update()\n\n u1 = self.register_user(\"u1\", \"pass\")\n u1token = self.login(\"u1\", \"pass\")\n r1 = self.helper.create_room_as(u1, tok=u1token)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mine count blocks and return the new tip.
def mine_blocks(self, count): # Clear out block announcements from each p2p listener [x.clear_block_announcements() for x in self.nodes[0].p2ps] self.generatetoaddress(self.nodes[0], count, self.nodes[0].get_deterministic_priv_key().address) return int(self.nodes[0].getbestblockhash(), ...
[ "def nblocks(self):\n return count(self)", "def num_blocks(self): # -> int:\n ...", "async def tip(self, ctx):\n index = random.randrange(len(self.tips))\n await ctx.send(f\"**Tip #{index+1}:** {self.tips[index]}\")", "def calculate_tip(meal_base, tip_rate):", "def tip(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mine a reorg that invalidates length blocks (replacing them with length+1 blocks).
def mine_reorg(self, length): # make sure all invalidated blocks are node0's self.generatetoaddress(self.nodes[0], length, self.nodes[0].get_deterministic_priv_key().address) for x in self.nodes[0].p2ps: x.wait_for_block_announcement(int(self.nodes[0].getbestblockhash(), 16)) ...
[ "def simple_reorg(self, height, shift=0):\n hashes = []\n fee_delta = 1000000\n orig_len = self.rpc.getblockcount()\n old_hash = self.rpc.getblockhash(height)\n if height + shift > orig_len:\n final_len = height + shift\n else:\n final_len = 1 + orig_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs only the lyrics search.
def run_lyrics(self): if self._GUI: self._run_lyrics_gui() else: self._run_lyrics_nogui()
[ "async def lyrics(self, ctx, *args):\n state = self.get_state(ctx.guild)\n extract = Song_Lyrics(self.config[\"search_key\"], self.config[\"search_id\"])\n messages = []\n title = None\n lyrics = None\n if len(args) == 0: # now playing lyrics\n if ctx.voice_clie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs only lyrics search with specifics of the GUI mode.
def _run_lyrics_gui(self): self._log.info("Searching for lyrics") self.save_lyrics(find=True) Action("load", load=True) self._log.info("Done")
[ "def run_lyrics(self):\n if self._GUI:\n self._run_lyrics_gui()\n else:\n self._run_lyrics_nogui()", "def lyricsCmd(bot, update,args):\n print ('I\\'m here')\n searchName = ' '.join(args)\n update.message.text=searchName\n print (update.message.text)\n lyrics(bot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs check of Batch Job Definition container properties.
def _validate_container_properties(container_properties, prefix=None): if not prefix: prefix = 'container_properties' container_config = [ { 'field_name': 'image', 'field_value': container_properties.get('image'), 'prefix': prefix, 'required_type'...
[ "def check_required_job_ad_attrs(self):\n required_job_ad_attrs = {'CRAB_UserRole': {'allowUndefined': True},\n 'CRAB_UserGroup': {'allowUndefined': True},\n 'CRAB_AsyncDest': {'allowUndefined': False},\n 'CRAB_DB...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new DB table for the DataFrame
def create_db_dataframe(self, df, table_name): try: print("-I- Writing " + table_name + " with DataFrame") df.to_sql(name=table_name, con=self.engine, if_exists='replace', index=True) print("-I- Write complete.") except Exception as e: print("-W- " + str(e...
[ "def _insert_table(df, table_name):\r\n with sqlite_connection(DATABASE_FILE) as conn:\r\n df.to_sql(table_name, conn, if_exists='replace', index=False,\r\n chunksize=5000)", "def make_table(db, table, **kwargs):\n execute_only(_CT_QUERY(db, table, **kwargs))", "def create_table_in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Appends DataFrame to the specified table
def append_db_dataframe(self, df, table_name): try: print("-I- Appending " + table_name + " with DataFrame") df.to_sql(name=table_name, con=self.engine, if_exists='append', index=True) print("-I- Append complete.") except Exception as e: print("-W- " + str...
[ "def append_table(self, table):\n if not table:\n return\n\n indexes = []\n for idx in table.index:\n index = self.size + idx\n indexes.append(index)\n\n self.set(indexes=indexes, columns=table.columns, values=table.data)", "def add_df(self, df):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test_save_contact test case to test if the contact object is saved into the contact list
def test_save_contact(self): # .save_contact() is the save to contact function. # Test would check if an addition has been made to our contact list self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1)
[ "def test_save_contact(self):\n self.new_contact.save_contact() # saving the new contact\n self.assertEqual(len(Contact.contact_list), 1)", "def test_save_multiple_contacts(self):\n self.new_contact.save_contact() # saving the new contact\n test_contact = Contact(\"Test\", \"User\", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
def test_save_multiple_contact to check if we can save multiple contacts to our contact_list
def test_save_multiple_contact(self): self.new_contact.save_contact() # new contact test_contact = Contact("Test", "user", "0798765432", "test@user.com") test_contact.save_contact() self.assertEqual(len(Contact.contact_list), 2)
[ "def test_save_multiple_contacts(self):\n self.new_contact.save_contact() # saving the new contact\n test_contact = Contact(\"Test\", \"User\", 254712345678, \"test@user.com\") # new user\n test_contact.save_contact() # saving the new contact\n self.assertEqual(len(Contact.contact_lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test_delete_contact to test if we can remove a contact from our contact list
def test_delete_contact(self): self.new_contact.save_contact() # new contact test_contact = Contact("Test", "user", "0745639300", "test@usr.com") # new contact saved test_contact.save_contact() # For deleting the new contact self.new_contact.delete_contact() ...
[ "def test_destroy_contact(self):\n pass", "def test_delete_a_contact(self):\n email = self.test_contact_json['properties'][0]['value']\n contact = self.client.create_or_update_a_contact(email, data=self.test_contact_json)['vid']\n\n response = self.client.delete_a_contact(contact)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test to check if we can return a Boolean if we cannot find the contact.
def test_contact_exists(self): self.new_contact.save_contact() # Test user test_contact = Contact("Test", "user", "0722334455", "test@user.com") # We save test_contact.save_contact() # variable that stores what we expect contact_exists = Contact.contact_exist("07...
[ "def isValid(self):\n return _yarp.Contact_isValid(self)", "def test_get_contact_empty(self):\n self.assertFalse(self.phone.get_contact(\"Kenneth\"))\n self.phone.add_contact(\"Andreas\", \"079-244 07 80\")\n self.assertFalse(self.phone.get_contact(\"Kenneth\"))", "def get_is_worksho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test to confirm that we are copying the email address from a found contact
def test_copy_email(self): self.new_contact.save_contact() Contact.copy_email("0712345678") self.assertEqual(self.new_contact.email, pyperclip.paste()) # Below we are simply stating that if the module being tested is running we collect the test methods and execute them.
[ "def test_copy_email(self):\n self.new_contact.save_contact()\n Contact.copy_email(254719702373)\n\n self.assertEqual(self.new_contact.email, pyperclip.paste())", "def test_copy_email(self):\n\n\n self.new_credential.save_credential()\n Credential.copy_email(\"Chris\")\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
partial_distance_covariance_test(x, y, z, num_resamples=0, exponent=1, random_state=None) Test of partial distance covariance independence. Compute the test of independence based on the partial distance covariance, for two random vectors conditioned on a third. The test is a permutation test where the null hypothesis i...
def partial_distance_covariance_test(x, y, z, **kwargs): # pylint:disable=too-many-locals random_state = _random_state_init(kwargs.pop("random_state", None)) # B num_resamples = kwargs.pop("num_resamples", 0) _check_kwargs_empty(kwargs) # Compute U-centered matrices u_x = _dcor_internals....
[ "def test_coeffvar(self):\n self.assertEqual(coeffvar(list1, sample=False), np.std(list1) /\n np.mean(list1))\n self.assertEqual(coeffvar(list1), np.std(list1, ddof=1) /\n np.mean(list1))", "def test_exact_two_qubit_cnot_decompose_random(self, seed):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an SSL keyfile and returns the path.
def CreateKeyFile(): keyfile = tempfile.mkstemp()[1] cmd = [ 'openssl', 'genrsa', '-out', keyfile, '2048' ] _RunCommand(cmd) return keyfile
[ "def _keypath(self) -> pathlib.Path:\n home = pathlib.Path.home()\n keyfile = home / \".cmdc\" / \"apikey\"\n keyfile.parent.mkdir(parents=True, exist_ok=True)\n return keyfile", "def CreateCsrFile(keyfile):\n csrfile = tempfile.mkstemp()[1]\n cmd = [\n 'openssl',\n 'req',\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an SSL CSR file and returns the path.
def CreateCsrFile(keyfile): csrfile = tempfile.mkstemp()[1] cmd = [ 'openssl', 'req', '-new', '-key', keyfile, '-out', csrfile, '-subj', '/C=NA/ST=NA/L=NA/O=Chromium/OU=Test/CN=chromium.org' ] _RunCommand(cmd) return csrfile
[ "def CreateCrtFile(keyfile, csrfile):\n crtfile = tempfile.mkstemp()[1]\n cmd = [\n 'openssl',\n 'x509',\n '-req',\n '-days', '1',\n '-in', csrfile,\n '-signkey', keyfile,\n '-out', crtfile\n ]\n _RunCommand(cmd)\n return crtfile", "def create_csr(\n ca_name,\n bi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an SSL CRT file and returns the path.
def CreateCrtFile(keyfile, csrfile): crtfile = tempfile.mkstemp()[1] cmd = [ 'openssl', 'x509', '-req', '-days', '1', '-in', csrfile, '-signkey', keyfile, '-out', crtfile ] _RunCommand(cmd) return crtfile
[ "def ca_file(tmpdir):\n key = rsa.generate_private_key(public_exponent=65537, key_size=2048)\n public_key = key.public_key()\n\n builder = x509.CertificateBuilder()\n builder = builder.subject_name(\n x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, \"pyopenssl.org\")])\n )\n builder = bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an SSL PEM file and returns the path.
def CreatePemFile(): keyfile = CreateKeyFile() csrfile = CreateCsrFile(keyfile) crtfile = CreateCrtFile(keyfile, csrfile) pemfile = tempfile.mkstemp()[1] with open(keyfile) as k: with open(crtfile) as c: with open(pemfile, 'wb') as p: p.write('%s\n%s' % (k.read(), c.read())) return pemfile
[ "def ca_file(tmpdir):\n key = rsa.generate_private_key(public_exponent=65537, key_size=2048)\n public_key = key.public_key()\n\n builder = x509.CertificateBuilder()\n builder = builder.subject_name(\n x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, \"pyopenssl.org\")])\n )\n builder = bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform from one radial coordinate to another. Note that this coordinate conversion is only strictly valid inside of the LCFS.
def rad_coord_transform(x,name_in,name_out, geqdsk): if name_in == name_out: return x if 'r_V' not in geqdsk['fluxSurfaces']['geo']: R0 = geqdsk['RMAXIS'] eq_vol = geqdsk['fluxSurfaces']['geo']['vol'] r_V = np.sqrt(eq_vol/(2*np.pi**2*R0)) geqdsk['fluxSurfaces']['geo']['r...
[ "def normalize(self):\n\n # first unwind positions, i.e. make sure that:\n # [0 <= alpha < 2pi] and [-pi < delta <= pi]\n\n # normalise longitude\n while self.longitude < 0:\n self.longitude += lal.TWOPI\n while self.longitude >= lal.TWOPI:\n self.longitude -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transformation to apply on each notebook. You should return modified nb, resources. If you wish to apply your transform on each cell, you might want to overwrite transform_cell method instead.
def call(self, nb, resources): self.log.debug("Applying transform: %s", self.__class__.__name__) try : for worksheet in nb.worksheets: for index, cell in enumerate(worksheet.cells): worksheet.cells[index], resources = self.transform_cell(cell, resources, i...
[ "def _preprocess(self, nb, resources):\n\n # Do a copy.deepcopy first,\n # we are never safe enough with what the preprocessors could do.\n nbc = copy.deepcopy(nb)\n resc = copy.deepcopy(resources)\n\n # Run each preprocessor on the notebook. Carry the output along\n # to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Overwrite if you want to apply a transformation on each cell. You should return modified cell and resource dictionary.
def transform_cell(self, cell, resources, index): raise NotImplementedError('should be implemented by subclass') return cell, resources
[ "def call(self, nb, resources):\n self.log.debug(\"Applying transform: %s\", self.__class__.__name__)\n try :\n for worksheet in nb.worksheets:\n for index, cell in enumerate(worksheet.cells):\n worksheet.cells[index], resources = self.transform_cell(cell, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publish flow to OpenML server. Returns
def publish(self): xml_description = self._generate_flow_xml() file_elements = {'description': xml_description} return_code, return_value = _perform_api_call( "flow/", file_elements=file_elements) self.flow_id = int(xmltodict.parse(return_value)['oml:upload_flow']['oml:id'])...
[ "def publish(self, raise_error_if_exists: bool = False) -> \"OpenMLFlow\":\n # Import at top not possible because of cyclic dependencies. In\n # particular, flow.py tries to import functions.py in order to call\n # get_flow(), while functions.py tries to import flow.py in order to\n # in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a flow exists for the given model and possibly creates it. If the given flow exists on the server, the flowid will simply be returned. Otherwise it will be uploaded to the server. Returns
def _ensure_flow_exists(self): import sklearn flow_version = 'sklearn_' + sklearn.__version__ _, _, flow_id = _check_flow_exists(self._get_name(), flow_version) # TODO add numpy and scipy version! if int(flow_id) == -1: return_code, response_xml = self.publish() ...
[ "def flow_exists(name, external_version):\n if not (isinstance(name, six.string_types) and len(name) > 0):\n raise ValueError('Argument \\'name\\' should be a non-empty string')\n if not (isinstance(name, six.string_types) and len(external_version) > 0):\n raise ValueError('Argument \\'version\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the data in from xyz.csv add two new columns, one to calculate dollar flux, and the other to calculate percentage flux return as a list of tuples
def calculate_flux(XYZ: str) -> list: df = pd.read_csv(XYZ) df['Dollar Flux'] = df['12/31/20'] - df['12/31/19'] df['Percentage Flux'] = df['12/31/20'] / df['12/31/19'] - 1 return list(tuple(df.loc[i]) for i in range(df.shape[0]))
[ "def calculate_flux(XYZ: str) -> list:\n\n\n data = pd.read_csv(XYZ,dtype={'12/31/2020': int,'12/31/2019': int})\n\n data['dollar_flux'] = data.iloc[:,1].sub(data.iloc[:,2])\n data['pct_flux'] = data.iloc[:,[-2,1]].pct_change(axis=1).dropna(axis=1)\n\n\n return list(data.to_records(index=False))", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run gdal_merge using an external process.
def run_merge(*src, argv=None): tmpdir = tempfile.mkdtemp() inputs = [] for i, drv in enumerate(src): if type(drv) != str: tmppath = os.path.join(tmpdir, "input_%s.tif" % i) drv.write(tmppath) inputs.append(tmppath) else: inputs.append(src) ...
[ "def call_gdal_util(util_name,\n gdal_path=None,\n src_files='',\n src_band=None,\n dst_file=None,\n options={}):\n # define specific options\n _opt_2b_in_quote = [\"-mo\", \"-co\"]\n\n # get the gdal installed path i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create inital launcher with angle 45 degrees and velocity 40 win is the GraphWin to draw the launcher in.
def __init__(self, win): # draw the base shot of the launcher base = Circle(Point(0,0), 3) base.setFill("red") base.setOutline("red") base.draw(win) # save the window and create initial angle and velocity self.win = win self.angle = radians(45.0)...
[ "def __init__(self, win): \r\n\r\n # draw the base shot of the launcher \r\n base = Circle(Point(0,0), 3) \r\n base.setFill('red')\r\n base.setOutline('red')\r\n base.draw(win) \r\n\r\n # save the window and create initial angle and velocity\r\n self.win = win \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
undraw the arrow and draw a new one for the current values of angle and velocity.
def redraw(self): self.arrow.undraw() pt2 = Point(self.vel*cos(self.angle), self.vel*sin(self.angle)) self.arrow = Line(Point(0,0), pt2).draw(self.win) self.arrow.setArrow("last") self.arrow.setWidth(3)
[ "def redraw(self): \r\n\r\n self.arrow.undraw() \r\n pt2 = Point(self.vel*cos(self.angle), self.vel*sin(self.angle))\r\n self.arrow = Line(Point(0,0), pt2).draw(self.win) \r\n self.arrow.setArrow('last')\r\n self.arrow.setWidth(3)", "def _draw_arrow(self):\n self.painter....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change angle by amt degrees
def adjAngle(self, amt): self.angle = self.angle+radians(amt) self.redraw()
[ "def adjAngle(self, amt): \r\n\r\n self.angle = self.angle + radians(amt)\r\n self.redraw()", "def rotateDegrees(angle):\n rotate(angle *2*math.pi / 360)", "def rotation(angle, pas):\n\n return (angle + pas) % 360", "def rotate(self,amount):\n self.angle += amount\n if self.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
win is the GraphWin to display the shot, angle, velocity, and height are initial projectile parameters.
def __init__(self, win, angle, velocity, height): self.proj = Projectile(angle, velocity, height) self.marker = Circle(Point(0,height), 3) self.marker.setFill("red") self.marker.setOutline("red") self.marker.draw(win)
[ "def draw(self, win):\n # draw top\n win.blit(self.PIPE_TOP, (self.x, self.top))\n # draw bottom\n win.blit(self.PIPE_BOTTOM, (self.x, self.bottom))", "def __init__(self, win):\n \n # draw the base shot of the launcher\n base = Circle(Point(0,0), 3)\n base.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing eratosthenes function in task 559
def test_task559_eratosthenes(number, expected_value): assert algo.Task559.eratosthenes(number) == expected_value
[ "def eratosthenes(limit):\n if isinstance(limit, (int, float)) and limit == int(limit):\n limit = int(limit)\n else:\n raise ValueError\n primes = []\n mask = [1]*(limit+1)\n for i in range(2, limit+1):\n if mask[i]:\n primes.append(i)\n for j in range(i*i, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing mersen_numbers function in task 559
def test_task559_mersen_number(number, expected_value): assert algo.Task559.mersen_numbers(number) == expected_value
[ "def test_numbers(self):\n \n result = gen_expansion(sym.pi, 2)\n self.assertEqual(result, '14')\n result = gen_expansion(sym.exp(1), 2)\n self.assertEqual(result, '72')", "def test_anglicize100to999():\n print('Testing anglicize100to999')\n\n result = funcs.anglicize100to9...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
treq should be lazy imported since importing treq will install reactor. twisted.web.client.HTTPConnectionPool is patched here too.
def get_treq(): patch_twisted_http_connection_pool_bug() import treq return treq
[ "def http_open(self, req):\n return self.do_open(TimeoutHTTPConnection, req)", "def _mock_request():\r\n return _MockRequestClient().request()", "def fake_twisted_request(*args, **kwargs):\n kwargs.setdefault(\n 'Request', lambda channel: Request(channel=channel, queued=False))\n request = fa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an instance retrieve the expected test configurations for instance's datastore.
def expected_instance_datastore_configs(instance_id): instance = instance_info.dbaas.instances.get(instance_id) datastore_type = instance.datastore['type'] datastore_test_configs = CONFIG.get(datastore_type, {}) return datastore_test_configs.get("configurations", {})
[ "def test_get_registration_instance_configuration(self):\n pass", "def expected_default_datastore_configs():\n default_datastore = CONFIG.get('dbaas_datastore', None)\n datastore_test_configs = CONFIG.get(default_datastore, {})\n return datastore_test_configs.get(\"configurations\", {}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the expected test configurations for the default datastore defined in the Test Config as dbaas_datastore.
def expected_default_datastore_configs(): default_datastore = CONFIG.get('dbaas_datastore', None) datastore_test_configs = CONFIG.get(default_datastore, {}) return datastore_test_configs.get("configurations", {})
[ "def expected_instance_datastore_configs(instance_id):\n instance = instance_info.dbaas.instances.get(instance_id)\n datastore_type = instance.datastore['type']\n datastore_test_configs = CONFIG.get(datastore_type, {})\n return datastore_test_configs.get(\"configurations\", {})", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test create configurations with invalid values.
def test_configurations_create_invalid_values(self): values = '{"this_is_invalid": 123}' try: instance_info.dbaas.configurations.create( CONFIG_NAME, values, CONFIG_DESC) except exceptions.UnprocessableEntity: resp, body = i...
[ "def test_configuration_errors_on_init_of_invalid_confdata(testname,\n invalid_confdata):\n with pytest.raises(makefixtures.ConfigError):\n makefixtures.Configuration(invalid_confdata[testname])", "def test_configurations_create_invalid_value_type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test create configuration with invalid value type.
def test_configurations_create_invalid_value_type(self): values = '{"key_buffer_size": "this is a string not int"}' assert_unprocessable(instance_info.dbaas.configurations.create, CONFIG_NAME, values, CONFIG_DESC)
[ "def test_configurations_create_invalid_values(self):\n values = '{\"this_is_invalid\": 123}'\n try:\n instance_info.dbaas.configurations.create(\n CONFIG_NAME,\n values,\n CONFIG_DESC)\n except exceptions.UnprocessableEntity:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test create configuration with value out of bounds.
def test_configurations_create_value_out_of_bounds(self): expected_configs = self.expected_default_datastore_configs() values = json.dumps(expected_configs.get('out_of_bounds_over')) assert_unprocessable(instance_info.dbaas.configurations.create, CONFIG_NAME, values,...
[ "def test_init_minimum_gap_field_below_range(self):\n test_config = TestConfig(minimum_gap=-1)\n with self.assertRaises(ValidationError):\n test_config.clean_fields()", "def test_configurations_create_invalid_value_type(self):\n values = '{\"key_buffer_size\": \"this is a string no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test assigning a configuration to an instance
def test_assign_configuration_to_valid_instance(self): print("instance_info.id: %s" % instance_info.id) print("configuration_info: %s" % configuration_info) print("configuration_info.id: %s" % configuration_info.id) config_id = configuration_info.id instance_info.dbaas.instances....
[ "def test_set_registration_instance_configuration(self):\n pass", "def test_assign_configuration_to_instance_with_config(self):\n config_id = configuration_info.id\n assert_raises(exceptions.BadRequest,\n instance_info.dbaas.instances.modify, instance_info.id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test assigning a configuration to an instance conflicts
def test_assign_configuration_to_instance_with_config(self): config_id = configuration_info.id assert_raises(exceptions.BadRequest, instance_info.dbaas.instances.modify, instance_info.id, configuration=config_id)
[ "def test_assign_configuration_to_valid_instance(self):\n print(\"instance_info.id: %s\" % instance_info.id)\n print(\"configuration_info: %s\" % configuration_info)\n print(\"configuration_info.id: %s\" % configuration_info.id)\n config_id = configuration_info.id\n instance_info....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test that a new instance will apply the configuration on create
def test_start_instance_with_configuration(self): global configuration_instance databases = [] databases.append({"name": "firstdbconfig", "character_set": "latin2", "collate": "latin2_general_ci"}) databases.append({"name": "db2"}) configuration_instance...
[ "def test_set_registration_instance_configuration(self):\n pass", "def test_create(self):\n pass", "def test_assign_configuration_to_valid_instance(self):\n print(\"instance_info.id: %s\" % instance_info.id)\n print(\"configuration_info: %s\" % configuration_info)\n print(\"co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
wait for the instance created with configuration
def test_instance_with_configuration_active(self): def result_is_active(): instance = instance_info.dbaas.instances.get( configuration_instance.id) if instance.status in CONFIG.running_status: return True else: assert_equal("BU...
[ "def wait_for_delete_initialized_instance(self):\n self.instance_create_runner.run_wait_for_init_delete()", "def wait_for_resource_creation(self) -> None:\n self._wait_for_resource_creation()", "def __create(self):\n pass\n\n # create at cluster-provider\n # get kubeconfig\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test to unassign configuration from instance
def test_unassign_configuration_from_instances(self): instance_info.dbaas.instances.update(configuration_instance.id, remove_configuration=True) resp, body = instance_info.dbaas.client.last_response assert_equal(resp.status, 202) instance_inf...
[ "def test_delete_registration_instance_configuration_setting(self):\n pass", "def tearDown(self):\n # set the config module level variables back to None\n config.config._conf_parser = None\n config.config._user_config_file = None", "def discard_config(self):\n raise NotImpleme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test that after restarting the instance it becomes active
def test_restart_service_should_return_active(self): instance_info.dbaas.instances.restart(instance_info.id) resp, body = instance_info.dbaas.client.last_response assert_equal(resp.status, 202) def result_is_active(): instance = instance_info.dbaas.instances.get( ...
[ "def test_v1_restart(self):\n pass", "def test_v1alpha3_restart(self):\n pass", "def test_workflows_restart(self):\n pass", "def test_restart(self):\n an_container = models.Container.get(self.client, 'an-container')\n\n an_container.restart()", "def test_update_instances_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a given noise sim. Provide either 'psa' or all of 'season', 'pa', and 'patch' . Will return a stack of enmaps with shape [n_freqs, 3, Ny, Nx], where the second element has the elements (T, Q, U). n_freqs will be 1 for pa1 and pa2.
def getActpolSim(iterationNum = 0, patch = 'deep5', season = 's13', \ array = 'pa1', \ psa = None,\ noiseDictFile = 'templateInputsMr3c.dict', \ noiseDictFilePath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'../inputPara...
[ "def gen_session(self,num_episodes,pr_shift):\n environment = self.gen_env()\n env_flavorL = [i for i in range(self.num_pas)]\n flavors = []\n locations = []\n for ep_num in range(num_episodes):\n # generate a session where sample order is randomized\n np.random.shuffle(env_flavorL)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The relative weight is used to determine how much we want to see the data of this VM.
def update_relative_weight(self): self.relative_weight = 1 # Add up all of the historical cpu datapoints (higher CPU = more weight) for i in self.cpu_datapoints: self.relative_weight += i # Multiply by the status value (so VMs with red alarm have most weight) self.rel...
[ "def get_weight(self):\n pass", "def weight(self):\n return self._weight - self.tare_offset", "def weight(self):", "def get_weight(self):\n return self.weight", "def weight(self):\n counters = [\n (\"total_mhz\", self.dominfo.vms_online + self.dominfo.cpus_online / 4.0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exchange the authorization code for an access token.
def exchange_token(self, code): access_token_url = OAUTH_ROOT + '/access_token' params = { 'client_id': self.client_id, 'client_secret': self.client_secret, 'redirect_uri': self.redirect_uri, 'code': code, } resp = requests.get(access_token...
[ "def authorize(self, code):\n if self._authenticator.redirect_uri is None:\n raise InvalidInvocation('redirect URI not provided')\n self._request_token(code=code, grant_type='authorization_code',\n redirect_uri=self._authenticator.redirect_uri)", "def getAccessT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Optimise & Modifiy s3xml etree to and produce s3ocr etree
def s3ocr_etree(self): s3xml_etree = self.resource.struct(options=True, references=True, stylesheet=None, as_json=False, as_tree=True) # xml tags ITEXT = "...
[ "def transform_s3_xsl(**kwargs):\n access_id = kwargs.get(\"access_id\")\n access_secret = kwargs.get(\"access_secret\")\n bucket = kwargs.get(\"bucket\")\n dest_prefix = kwargs.get(\"destination_prefix\")\n source_prefix = kwargs.get(\"source_prefix\")\n if kwargs.get(\"dag\"):\n run_id = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update custom fieldtype specific settings into the etree
def __update_custom_fieldtype_settings(self, eachfield, #field etree ): # xml attributes TYPE = "type" READABLE = "readable" WRITABLE = "writable" LABEL = "label" HINT = "comment" DEFAU...
[ "def __update_custom_field_settings(self,\n eachfield, #field etree\n resourcetablename,\n fieldname\n ):\n\n # xml attributes\n TYPE = \"type\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update custom field specific settings into the etree
def __update_custom_field_settings(self, eachfield, #field etree resourcetablename, fieldname ): # xml attributes TYPE = "type" READABLE = ...
[ "def __update_custom_fieldtype_settings(self,\n eachfield, #field etree\n ):\n\n # xml attributes\n TYPE = \"type\"\n READABLE = \"readable\"\n WRITABLE = \"writable\"\n LABEL = \"label\"\n HINT = \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper to trim off any enclosing paranthesis
def __trim(self, text): if isinstance(text, str) and \ text[0] == "(" and \ text[-1] == ")": text = text[1:-1] return text
[ "def remove_parentheses(self):\n split_speaker = self.component_text.split(\"(\", maxsplit=1)\n self.component_text = split_speaker[0].strip()", "def strip_all_unbalanced_parens(s):\n c = strip_unbalanced_parens(s, '()')\n c = strip_unbalanced_parens(c, '<>')\n c = strip_unbalanced_parens(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate barcode of uuid
def barcode(self, uuid): barcode = code128.Code128(str(uuid), barWidth=1, barHeight=20) barcode.drawOn(self.canvas, self.lastx, self.lasty) self.lasty = self.lasty - 20 self.y = self.lasty
[ "def generate_barcode(length=6):\n return generate_nucleotide_sequence(seq_length=length)", "def test_generate_barcode_upce(self):\n pass", "def generate_barcode(receipt, receipt_model):\n barcode_number = randint(100000000000, 999999999999)\n image = barcode.get_barcode_class('upca')\n recei...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes one character on canvas
def writechar(self, char=" "): font=self.selectfont(char) t = self.canvas.beginText(self.x, self.y) t.setFont(font, self.fontsize) t.setFillGray(self.gray) t.textOut(char) self.canvas.drawText(t) return t
[ "def writechar(self, char: int, /) -> None:", "def _put_char_ex(self, x, y, char, color=colors.white, bgcolor=colors.black):\n if self.con is None:\n # Do nothing if we don't have a console\n return\n\n if x < 0 or x >= self.width or y < 0 or y >= self.height:\n # Ig...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select font according to the input character
def selectfont(self, char): charcode = ord(char) for font in fontchecksequence: for fontrange in fontmapping[font]: if charcode in xrange(fontrange[0], fontrange[1]): return font return "Helvetica" # fallback, if no thirdparty font is installed
[ "def askfont(font=None, **options):\r\n fc = Fontchooser(font=font, **options)\r\n fc.show()\r\n return(fc.font() if fc.selected() else None)", "def selectFont():\n font,ok = QtGui.QFontDialog.getFont()\n if ok:\n return font\n else:\n return None", "def setFont(text: unicode, co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to draw check boxes default no of boxes = 1
def draw_check_boxes(self, boxes=1, completeline=0, lines=0, seek=0, continuetext=0, fontsize=15, gray=0, style="", ...
[ "def create_checkboxes(self):\n self.create_y_crop_box()", "def add_N_Graphiques(self,n):\n self.checkBoxesD=[]\n for i in range(n):\n self.checkBoxesD.append(QtWidgets.QCheckBox(self.horizontalLayoutWidget))\n self.checkBoxesD[i].setObjectName(\"checkBox_\"+str(i+1))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate ``model``specific synthesis script.
def generate_yosys_script(summary, renderer, ostream, model, model_sources, template = "synth.specific.tmpl.ys"): renderer.add_generic( ostream, template, model = model, model_sources = model_sources, yosys_script = summary.yosys["script"], iteritems = iteritems, itervalues = itervalues )
[ "def gen_script(model: onnx.ModelProto, output_file: str = None) -> str:\n current_dir = os.path.dirname(os.path.realpath(__file__))\n env = jinja2.Environment(loader=jinja2.FileSystemLoader(current_dir + '/templates/'))\n model_header_render = gen_model_header(env, model)\n imports, main_function, sub_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adapt a CWL job object to the Galaxy API. CWL derived tools in Galaxy can consume a job description sort of like CWL job objects via the API but paths need to be replaced with datasets and records and arrays with collection references. This function will stage files and modify the job description to adapt to these chan...
def galactic_job_json(job, test_data_directory, upload_func, collection_create_func): datasets = [] dataset_collections = [] def upload_file(file_path): if not os.path.isabs(file_path): file_path = os.path.join(test_data_directory, file_path) _ensure_file_exists(file_path) ...
[ "def galactic_job_json(\n job, test_data_directory, upload_func, collection_create_func, tool_or_workflow=\"workflow\"\n):\n\n datasets = []\n dataset_collections = []\n\n def upload_file(file_path, secondary_files, **kwargs):\n file_path = abs_path_or_uri(file_path, test_data_directory)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert objects in a Galaxy history into a CWL object. Useful in running conformance tests and implementing the cwlrunner interface via Galaxy.
def output_to_cwl_json(galaxy_output, get_metadata, get_dataset): def element_to_cwl_json(element): element_output = GalaxyOutput( galaxy_output.history_id, element["object"]["history_content_type"], element["object"]["id"], ) return output_to_cwl_json(ele...
[ "def convert_skill_history(apps, schema_editor):\n Attribute = apps.get_model(\"typeclasses\", \"Attribute\")\n Trait = apps.get_model(\"traits\", \"Trait\")\n TraitPurchase = apps.get_model(\"traits\", \"TraitPurchase\")\n qs = Attribute.objects.filter(db_key=\"skill_history\")\n total = len(qs)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the EM algorithm.
def run_em(self, maxiter=400, tol=1e-4, verbose=True, regularization=0.0): self.means = self.means.T L = None for i in xrange(maxiter): newL = self._expectation() if i == 0 and verbose: print("Initial NLL =", -newL) self._maximization(regular...
[ "def run(self, simulation):", "def EM_algorithon(num_epoch, test_length):\n Y = Genrating_observation_data(test_length)\n PA, PB, PC = 0.5, 0.5, 0.5\n print(\"Begin....\")\n msg = \"Coin {}: Positive probability : {:.2f}\"\n for i in range(num_epoch):\n\n # Step E\n PB_Y_list = [calcu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The decorator method to be called on the class object. This method will set the proper `discoverable` type to the class. It should return the class passed in, according to the decorator spec.
def discoverable(_class): # Set the attribute to the class name, to prevent subclasses from also # being discoverable. setattr(_class, _get_discoverable_attribute(_class), True) return _class
[ "def is_class_discoverable(_class, default_discoverability=False):\n return bool(getattr(_class, _get_discoverable_attribute(_class),\n default_discoverability))", "def not_discoverable(_class):\n\n # Set the attribute to the class name, to prevent subclasses from also\n # being no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The decorator method to be called on the class object. This method will set the proper `not discoverable` type to the class. It should return the class passed in, according to the decorator spec.
def not_discoverable(_class): # Set the attribute to the class name, to prevent subclasses from also # being not discoverable. setattr(_class, _get_discoverable_attribute(_class), False) return _class
[ "def discoverable(_class):\n\n # Set the attribute to the class name, to prevent subclasses from also\n # being discoverable.\n setattr(_class, _get_discoverable_attribute(_class), True)\n return _class", "def checktype(type):\n def decorator(klass):\n register_type(type, klass)\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the class is marked discoverable
def is_class_discoverable(_class, default_discoverability=False): return bool(getattr(_class, _get_discoverable_attribute(_class), default_discoverability))
[ "def _get_discoverable_attribute(_class):\n return \"__{}_is_discoverable\".format(_class.__name__)", "def discoverable(_class):\n\n # Set the attribute to the class name, to prevent subclasses from also\n # being discoverable.\n setattr(_class, _get_discoverable_attribute(_class), True)\n return _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an attribute to set on a class to consider it discoverable
def _get_discoverable_attribute(_class): return "__{}_is_discoverable".format(_class.__name__)
[ "def discoverable(_class):\n\n # Set the attribute to the class name, to prevent subclasses from also\n # being discoverable.\n setattr(_class, _get_discoverable_attribute(_class), True)\n return _class", "def __getattribute__(self, s):\n try:\n # I call parent __getattribute...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert file to raw file.
def convert_to_raw(file): img = Image.open(file) img = img.convert('L') # convert to 8 bits per pixels (x, y) = img.size pixels = bytearray(list(img.getdata())) filename, file_extension = os.path.splitext(file) file2 = file.replace(file_extension, '.dat') file_name = str(x) + 'x' + str(y...
[ "def read_raw(file_path):\n file = open(file_path, 'rb')\n content = file.read()\n file.close()\n return content", "def encode_file(self):\n return base64.b64encode(self.file.encode()).decode()", "def raw(self):\n\t\tview = core.BNGetFileViewOfType(self.handle, \"Raw\")\n\t\tif view is None:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a raw file to jpg file.
def convert_to_jpg(raw_file): match = re.match('(\d+)x(\d+)x(\d+)x(\d+)_(\w+)', raw_file) if match: # print(match.group(1)) # print(match.group(2)) # print(match.group(3)) # print(match.group(4)) # print(match.group(5)) x = int(match.group(1)) y = int(mat...
[ "def convert_to_jpg_then_compress(self):\n\t\tself._compressed_file_name = 'c_' + self.file_name\n\t\tself._compressed_save_path = self.full_path.replace(self.file_name, self._compressed_file_name).replace('.png', '.jpg')\n\n\t\timage = Image.open(self.full_path)\n\t\timage.save(self._compressed_save_path)\n\n\t\ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper function on top of the interpolation executable. It is also a benchmarking function, it returns the name of the output image and the time needed to do all the iterations
def interpolate(file_in, file_out, device, iterations, interpolation_type, new_width, new_height): command_string = './Interpolate ' + device + ' ' + str(iterations) + ' ' + interpolation_type + ' ' + file_in + ' ' + file_out + ' ' + str(new_width) + ' ' + str(new_height) program_out = str(subprocess.check_ou...
[ "def interpolating(output_dir, resize=None):\r\n model = get_model(weight_path)\r\n if args.num_output == 3:\r\n for position in sorted(os.listdir(output_dir)):\r\n position_path = Path(output_dir / position)\r\n print(f'Interpolating {position}')\r\n image_paths = (Pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Benchmark cpu vs gpu time wise.
def benchmark_cpu_vs_gpu(input_raw_file): nb_iterations = 20 (cpu1, f1) = interpolate(input_raw_file, 'cpu_nn_lena.dat', 'cpu', nb_iterations, 'nn', 4000, 2000) (gpu1, f2) = interpolate(input_raw_file, 'gpu_nn_lena.dat', 'gpu', nb_iterations, 'nn', 4000, 2000) (cpu2, f3) = interpolate(input_raw_file, ...
[ "def cpu_benchmark():\n global cpu_test_running\n cpu_test_running = True\n for i in range(250):\n for x in range(1, 1000):\n math.pi * 2 ** x\n for x in range(1, 100000):\n float(x) / math.pi\n # for x in range(1, 10000):\n # math.pi / x\n cpu_test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check bit exactness on interpolation executable between Gpu vs Cpu with various parameters.
def check_bit_exactness(input_raw_file): (t1, f1) = interpolate(input_raw_file, 'cpu_nn_lena.dat', 'cpu', 1, 'nn', 8000, 4000) (t2, f2) = interpolate(input_raw_file, 'gpu_nn_lena.dat', 'gpu', 1, 'nn', 8000, 4000) (t3, f3) = interpolate(input_raw_file, 'cpu_bl_lena.dat', 'cpu', 1, 'bl', 8000, 4000) (t4, ...
[ "def test_cpu_gpu_result(self, precision=1e-1):\n res1 = run_infer(self.model, CASE_ROOT + \"/resnet_fluid_gpu.yaml\",\n self.input_data)\n res2 = run_infer(self.model, CASE_ROOT + \"/resnet_fluid_cpu.yaml\",\n self.input_data)\n result1 = res1[0]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup an example users generator instance so can use the record
def setUp(self): gen = UsersGenerator({}) gen.generate_adt_user() self.record = gen.class_data.findall('record')[0]
[ "def create_users(self):\n self.test_runner.run_users_create()", "def setUp(self):\n patientgen = PatientsGenerator(0, 1, 0, 'a')\n self.record = patientgen.data.find('record')\n self.gender_sex = patientgen.gender_sex_list\n self.ethnicities = patientgen.ethnicity_list\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch organization details from the API.
def fetch_details_from_api(self, org_names=None): logger.debug('Fetching org details from API...') details = {} if org_names is None: org_names = self._all_page_names(without_namespace=True) for org in org_names: code = self._code_by_name(org) if code ...
[ "def fetch_organization(organization):\n return fetch_json(organization_url, organization)", "def __fetch_org(self):\n try:\n resp = requests.get(\"https://api.github.com/orgs/{}\".format(self.name), auth=(username, password))\n\n if resp.status_code != 200:\n if res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new organization category tree and pages.
def recreate_tree(self, fetch_from_api=False): logger.debug('Creating organization category tree and pages...') for parent, children in self._hierarchy( fetch_from_api=fetch_from_api).items(): self._create_pages(parent) parent_category = f'[[Category:{parent}]]' ...
[ "def create_category_pages(app):\n env = app.builder.env\n\n template = \"category.html\"\n\n categories = env.categories\n for name, category in categories.iteritems():\n context = {}\n context[\"title\"] = category.name\n context[\"subcategories\"] = category.subcategories\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nuke organization category tree and pages.
def nuke_tree(self): logger.debug('Nuking organization category tree and pages...') def recurse_delete(page): if page.exists: page_is_category = True try: page_members = page.members() except AttributeError: ...
[ "def recreate_tree(self, fetch_from_api=False):\n logger.debug('Creating organization category tree and pages...')\n for parent, children in self._hierarchy(\n fetch_from_api=fetch_from_api).items():\n self._create_pages(parent)\n parent_category = f'[[Category:{pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update organization pages from apografi API.
def update_pages(self, fetch_from_api=False, details=None, force_create=False): logger.debug('Updating organization pages...') def template_text(org_details): te = TemplateEditor(self.TEMPLATE) template = te.templates[self.TEMPLATE_NAME][0] # Add...
[ "def _update_page(self, pageId, body: Body):", "def updatePage(self, oEnXMLPage):\r\n\t\tKeyList = oEnXMLPage.getKeyList()\r\n\t\txPath = 'PageXML'\r\n\t\ti = 0\r\n\t\twhile i != len(KeyList):\r\n\t\t\toEnXMLKey = KeyList[i]\r\n\t\t\tkeyNodeName = oEnXMLKey.getNodeName()\r\n\t\t\tkeyName = oEnXMLKey.getName()\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the status, the owner, the project name and the number of cart items.
def __str__(self): return _( "cart (status: %(status)s, owner: %(owner)s, project name: " "%(project_name)s, number of cart items: %(nb_cart_items)d, " "total amount: %(total_amount)d)" ) % { 'status': self.CART_STATUSES[self.status][1], 'owner...
[ "def show_cart():\n \n order_id = session['order_id']\n \n data = db.session.query(Cart.id, Cart.quantity, Item.name, Item.price).filter\\\n (and_(Item.id == Cart.item_id, Cart.order_id == order_id)).all() \n total = 0\n for items in data:\n total = tota...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves all cart items for a given cart.
def get_cart_items(self): return CartItem.objects.filter(cart=self)
[ "def get_cart_items(request):\n return CartItem.objects.filter(cart_id = get_cart_id_session(request))", "def all(cls):\n cls.logger.info(\"Processing all Shopcart Items\")\n return cls.query.order_by(cls.id).all()", "def get_cart_ingredients(cls, cartid):\n\n cart_ings = Cart_Ingredient...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the number of distinct cart items for a given cart.
def nb_cart_items(self): return CartItem.objects.filter(cart=self).count()
[ "def get_cart_item_count(self):\n cart_id = self.get_cart_id()\n return CartItem.objects.filter(cart_id=cart_id).count()", "def num_carts(self):\n return self._num_carts", "def total_items(collection):\n result = collection.distinct('items')\n return len(list(result))", "def __len__...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the total amount of cart items for a given cart.
def total_amount(self): total_amount = 0 for cart_item in self.get_cart_items(): total_amount += cart_item.total_price return total_amount
[ "def get_total_of_cart(session_id):\n cart_items = CartItem.objects.filter(cart_id=session_id)\n cart_total_list = [cart_item.total() for cart_item in cart_items]\n return sum(cart_total_list)", "def cart_subtotal(request):\n cart_total = decimal.Decimal('0.00')\n cart_products = get_ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if this cart is empty.
def is_empty(self): return self.id is None or self.nb_cart_items == 0
[ "def is_cart_empty(self: object) -> bool:\n empty_cart_text = self.driver.find_element(*CartPageLocators.EMPTY_CART_TEXT)\n if empty_cart_text:\n logging.info(\"Your cart is empty!\")\n return True\n return False", "def is_empty(self):\n return len(self.inventory)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs experiment using DP, QL or both. Creates new directory automatically Save result summary to summary file
def run_Experiment(DP = None, QL = None): # Path information output_path, exp_num = create_new_dir() #dirs Exp/1, Exp/2, ... DP_path = join(output_path,'DP') #dirs Exp/1/DP QL_path = join(output_path,'QL') #dirs Exp/1/QL print("************ Exp ", exp_num, ...
[ "def run_test(self):\n\n # populate *_ps sets\n self.enter_project_file()\n\n # populate *_dir sets\n self.enter_directories()\n\n # The files in the directories makes up the largest possible set of files\n self.result_files = self.result_files_dir\n self.design_file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
start point of scraping use urls, pass soup tag to Unvs return a list of 100 unvs(university) object
def scrape(): url_base='https://www.usnews.com/best-colleges/rankings/national-universities' unvss=[] for page in range(N_PAGE): url=url_base+'?_page={}'.format(page+1) soup=get_soup(url) unvs_tags=soup.find_all('li',id=re.compile(r'^view-.*'),class_='block-normal block-loose-for-lar...
[ "def get_national_university_data(univ_url):\n f_name = 'national_university_html.json'\n base_url = 'https://www.usnews.com'\n html_cache = load_cache(f_name)\n\n if univ_url not in html_cache:\n resp = requests.get(base_url + univ_url, headers=agent)\n html_cache[univ_url] = resp.text\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
use the url to scrape detailed info
def scrape_detail(self,url): soup=get_soup(url) self.zip=soup.find('p',class_='block-normal hide-for-small-only text-small hero-ranking-data-contact').stripped_strings.__next__()[-5::1] if self.zip in zips: #print('DUPLICATE!') zips.append(self.zip) info_tags=soup.fin...
[ "def the_scrape(url):\n\n req = requests.get(url)\n url_list = parse_urls(req.text)\n email_list = parse_email_addresses(req.text)\n phone_list = parse_phone_numbers(req.text)\n\n print_list('Emails', email_list)\n print_list('Phone Numbers', phone_list)\n print_list('Urls', url_list)", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Swap the byteordering in a packet with N=4 bytes per word
def byteswap(data, word_size=4): return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '')
[ "def byte_swap(data, word_size):\n \n bs_data = [0]*len(data)\n for ii in range(0, len(data), word_size):\n bs_data[ii:ii+word_size] = data[ii:ii+4][::-1]\n return(bytes(bs_data))", "def swapNibbles(inputByte):\n return (inputByte << 4 | inputByte >> 4) & 0xff", "def swap(byte):\r\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if response is HTML
def is_good_response(self, resp): content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1)
[ "def is_good_response(self, resp):\r\n\t\tcontent_type = resp.headers['Content-Type'].lower()\r\n\t\treturn (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1)", "def is_html(self):\r\n return self.__content_type == html_ctype", "def is_html(self):\n return se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }