query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Set or show the User Role. Members with this role can create polls and manage their own polls.
async def userrole(self, ctx, *, role=None): server = ctx.message.guild if not role: result = await self.bot.db.config.find_one({'_id': str(server.id)}) if result and result.get('user_role'): await ctx.send(f'The user role restricts which users are able to create...
[ "def __setRole(self, session):\r\n self.__role = session.role\r\n if self._config.has_key('purpose'):\r\n co_role = ccm.get_role_for_purpose(session, self._config['purpose'])\r\n _logger.info(\"Switching user to role: %s\" % co_role)\r\n session.role = co_role\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fuse this track estimates with the current estimates from argument track.
def fuse_estimates(self, tracks): # compile states and covariances mu = [] sigma = [] s, t = self.state_estimator.state(get_fused=False) p = self.state_estimator.P mu.append(s[0]) sigma.append(p[-1]) for track in tracks: s, t = track.state_est...
[ "def estimate(self, estimate):\n\n self._estimate = estimate", "def update(self):\n imp_x = pd.concat(\n [\n self.dataset.complete[self.dataset.get_sf_names()],\n self.dataset.complete[self.dataset.get_y_name()],\n ],\n axis=1,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pass a new message onto the state estimator and update state of the Track to reflect this.
def store(self, new_msg, track_list): self.state_estimator.store(new_msg, ts.TimeStamp(new_msg['h'], new_msg['m'], new_msg['s'])) self.received_measurement = True self.n_consecutive_measurements += 1 self.n_consecutive_missed = 0 self.lane = new_msg['lane'] if se...
[ "def update(self, message):\n\n #TODO: we have to later think of its implementation and format.\n super(StateDriver, self).update(message)", "def _state_message_received(self, msg: ReceiveMessage) -> None:\n try:\n self._state = int(msg.payload)\n self.async_write_ha_sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the labels of a 2D grid to file
def write_grid2d(grid_file, grid2d): with grid_file.open('w') as f: for row in grid2d['label']: f.write('\t'.join(row) + '\n')
[ "def write_labels():\n with open('../data/labels.txt', 'w') as labels_file:\n labels = generate_labels()\n labels_file.write('\\n'.join(labels))", "def write_output(labels):\n with open('./nboutput.txt', 'w', encoding='latin1') as f:\n for path, label in labels.items():\n f.w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the labels of a 2D grid to file
def read_grid2d(grid_file): labels = [] with grid_file.open('r') as f: for row in f.readlines(): labels.append([x.strip() for x in row.split('\t')]) labels = array(labels) grid2d = make_grid(labels.shape[0], labels.shape[1]) grid2d['label'] = labels return grid2d
[ "def write_grid2d(grid_file, grid2d):\n with grid_file.open('w') as f:\n for row in grid2d['label']:\n f.write('\\t'.join(row) + '\\n')", "def load_label(self, idx):\n im = open('{}/GTTXT/{}.txt'.format(root_dir, idx))\n\t#print(type(im.readlines()[0].rstrip(\"\\n\")))\n rgb_lab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write electrode position to tsv
def write_tsv(labels, positions, elec_file): labels = labels.reshape(-1, order='F') positions = positions.reshape(-1, 3, order='F') elec_file = elec_file.with_suffix('.tsv') with elec_file.open('w') as f: f.write('name\tx\ty\tz\n') for i in range(labels.shape[0]): f.write(f'...
[ "def write_towhee_coord(self, filename):\n with open(filename, 'w') as f:\n df = self.contents[['X', 'Y', 'Z']].copy()\n np.savetxt(f, df.values, fmt=\" %20.15f\"*3)", "def writeTraj(self, filename):\n f = open(filename + '.csv', 'w')\n log_writer = csv.writer(f, delimi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export tkRAS transformation to a transform file.
def export_transform(offset, transform_file, format='slicer'): assert format == 'slicer' transform_file = Path(transform_file) transform_file = transform_file.with_suffix('.tfm') # use ITK convertion ("ITK's convention is to use LPS coordinate system as opposed to RAS coordinate system in Slicer") ...
[ "def exportButtonAction(self):\r\n var = self.UI.fileAppend_lineEdit.text()\r\n # world = self.UI.worldSpaceBake_checkBox.isChecked()\r\n fp = self.ExImFuncs.exportAnim(var)\r\n\r\n if fp:\r\n self.UI.outputPath_label.setText('<a href=\"%s\">%s</a>' % (str(\"/\".join(fp.split(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read 3D volume. You can also apply threshold to the data
def read_volume(volume_file, threshold=-Inf): volume = nload(str(volume_file)) data = volume.get_fdata() if threshold is not None: i = data >= threshold else: i = abs(data) > 0.001 # exclude small values output = zeros(i.sum(), dtype=DTYPE_VOLUME) output['pos'] = apply_affine(...
[ "def test_volume_3d(self):\n # generate voronoi mesh \n mesh = Mesh3d(self.particles, self.bound)\n print(\"building mesh...\")\n mesh.build_geometry()\n print(\"mesh complete\")\n\n # calculate voronoi volumes of all real particles \n real_indices = self.particles[\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes openio CLI command.
def openio(cls, cmd, coverage="--coverage ", **kwargs): return execute("openio " + coverage + cmd, **kwargs)
[ "def openio_admin(cls, cmd, coverage=\"--coverage \", **kwargs):\n return execute(\"openio-admin \" + coverage + cmd, **kwargs)", "def _oc_command(self, args):\n oc_command_exists()\n return [\"oc\"] + args", "def os_system(command):\n os.system(command)", "def execute(command):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute several commands in the same openio CLI process.
def openio_batch(cls, commands, coverage="--coverage", **kwargs): script = "\n".join(commands) try: return execute("openio " + coverage, stdin=script, **kwargs) except CommandFailed: print("Stdin was:\n\n%s" % (script,)) raise
[ "def openio_admin_batch(cls, commands, coverage=\"--coverage\", **kwargs):\n return execute(\"openio-admin \" + coverage, stdin=\"\\n\".join(commands), **kwargs)", "def run(self):\n for command in CUSTOM_COMMANDS:\n self.run_custom_command(command)", "def local_launcher(commands):\n for cmd in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes openioadmin CLI command.
def openio_admin(cls, cmd, coverage="--coverage ", **kwargs): return execute("openio-admin " + coverage + cmd, **kwargs)
[ "def openio_admin_batch(cls, commands, coverage=\"--coverage\", **kwargs):\n return execute(\"openio-admin \" + coverage, stdin=\"\\n\".join(commands), **kwargs)", "async def admin(ctx):\n if ctx.invoked_subcommand is None:\n await ctx.send(\"Invalid Command\")", "def _oc_command(self, args):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute several commands in the same openioadmin CLI process.
def openio_admin_batch(cls, commands, coverage="--coverage", **kwargs): return execute("openio-admin " + coverage, stdin="\n".join(commands), **kwargs)
[ "def openio_admin(cls, cmd, coverage=\"--coverage \", **kwargs):\n return execute(\"openio-admin \" + coverage + cmd, **kwargs)", "def run(self):\n for command in CUSTOM_COMMANDS:\n self.run_custom_command(command)", "def register_commands(app):\n for command in [create_db, drop_db, create_use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get formatting options for OpenIO CLIs, to make them output the specified fields in the specified format.
def get_format_opts(cls, format_="value", fields=[]): return " -f {0} {1}".format(format_, " ".join(["-c " + it for it in fields]))
[ "def format_parser(format, Genotype_data,ln, format_field):\n temp_format = []\n format_field_pos = -9\n if len(format.split(':')) > 1 :\n for k,x in enumerate(format.split(':')):\n if x == format_field:\n format_field_pos = k\n if format_field_pos == -9:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the horizon angles given a terrain profile. Derived from ITM hzns() routine as specified in R2SGN21.
def _GetHorizonAnglesLegacy(its_elev, height_cbsd, height_rx, refractivity): num_points = int(its_elev[0]) step = its_elev[1] dist = num_points * step # Find the refractivity at the average terrain height start_avg = int(3.0 + 0.1 * num_points) end_avg = num_points - start_avg + 6 zsys = np.mean(its_elev...
[ "def zenithazimuth_to_horizontal(zenith, azimuth):\n# altitude = norm_angle(pi / 2. - zenith)\n# Azimuth = norm_angle(pi / 2. - azimuth)\n altitude = norm_angle_copy(pi / 2. - zenith)\n Azimuth = norm_angle_copy(pi / 2. - azimuth)\n\n return altitude, Azimuth", "def horiz_angle(time, data):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Repeats a message multiple times.
async def repeat(ctx, times: int, content='repeating...'): for i in range(times): await ctx.send(content)
[ "async def repeat(ctx, times: int, *, message):\n for i in range(times):\n await ctx.send(message)", "async def repeat(self,ctx, times: int, content='repeating...'):\n for i in range(times):\n await ctx.send(content)", "async def repeat(times : int, content='repeating...'):\r\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Says if a user is cool. In reality this just checks if a subcommand is being invoked.
async def cool(ctx): if ctx.invoked_subcommand is None: await ctx.send('No, {0.subcommand_passed} is not cool'.format(ctx))
[ "async def cool(ctx):\r\n if ctx.invoked_subcommand is None:\r\n await bot.say('No, {0.subcommand_passed} is not cool'.format(ctx))", "async def cool(ctx):\n if ctx.invoked_subcommand is None:\n await bot.say('No, {0.subcommand_passed} is not cool'.format(ctx))", "async def appcheck(self, ct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is the bot cool?
async def _bot(ctx): await ctx.send('Yes, the bot is cool.')
[ "def is_bot(self) -> bool:", "async def _bot():\r\n await bot.say('Yes, the Poker is cool.')", "async def best():\n await bot.say('Nargacuga is the best Monster. Are you casual?')", "async def is_bear(ctx):\n return ctx.message.author.id == 353730886577160203 or ctx.message.author.id == 715048392408...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns normalized explicit bolean flags for `absl.flags` compatibility.
def normalize_flags(argv: List[str]) -> List[str]: bolean_flag_patern = re.compile(r'--[\w_]+=(true|false)') def _normalize_flag(arg: str) -> str: if not bolean_flag_patern.match(arg): return arg if arg.endswith('=true'): return arg[: -len('=true')] # `--flag=true` -> `--flag` elif arg.end...
[ "def _normflags(flags):\n if isinstance(flags, (list, tuple, set)):\n flags = \" \".join(flags)\n elif isinstance(flags, dict):\n flags = \" \".join(\n [\n (\"-\" + k if not k.startswith(\"-\") else k) + \" \" + v\n for k, v in flags.items()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get request data from NASA APOD API
def get_requests(): global response #Set the parameters fot the request url = "https://api.nasa.gov/planetary/apod" api_key = "DEMO_KEY" #Use your own key date = calender.get_date() querystring = {'api_key':api_key, 'date':date} #Call the request and turn it into a python usable format ...
[ "def get_apod_data(api_key: str, download: bool = False, path: str = \".\") -> dict:\n url = \"https://api.nasa.gov/planetary/apod\"\n return requests.get(url, params={\"api_key\": api_key}).json()", "def get_data_api_onpe():\n\tresponse = {}\n\theaders = {\n\t 'authority': 'api.resultadossep.eleccionesg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the desired photo
def save_photo(): save_name = filedialog.asksaveasfilename(initialdir="10.APOD Viewer/", title="Save Image", filetype=(("JPEG", "*.jpg"), ("All Files", "*.*"))) img.save(save_name + ".jpg")
[ "def savePhoto(self, path):\n if self.original_image and path:\n cv2.imwrite(path, self.original_image)", "def action_save(self, *args):\n\t\treturn self.saving_manager.save_current_image(False, False, False, True)", "def save_image_action(self):\n self.view.save_image(self.settings.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method that invokes "It's Always Sunny In Philadelphia" title card generation from ImageUtils.
async def iasip_title_card(self, ctx: Context, *, title: str) -> None: async with ctx.channel.typing(): if not title.startswith('"'): title = '"' + title if not title.endswith('"'): title += '"' buffer = await image_utils.title_card_generato...
[ "def titlegen(symbol, title):\r\n print(f\"{symbol}\"*60)\r\n print(\" \"*25+title)\r\n print(f\"{symbol}\"*60)", "def make_title(words):", "def new_title():\n title_len = random.randint(3,26)\n title = \"\".join(random.sample(ALPHA,title_len))\n return title", "def generate_finding_title(title):\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper method to get integer input from user in certain range
def _int_input_in_range(self, print_out, range_): try: i = int(input(print_out)) assert range_[0] <= i <= range_[1] return i except AssertionError: print('Please, enter a vaild number') return None except ValueError: print('...
[ "def ask_number (question,low,high):\n response = None\n while response not in range(low,high):\n response = int(input(question))\n return response", "def get_integer_value(prompt, low, high):\n\n while True:\n try:\n value = int(input(prompt))\n except ValueError:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints out logging options to the user
def logging_page(self): print('-=' * 12 + " Logging Page " + '-=' * 12) options = {1: self.sign_up, 2: self.log_in, 3: self.delete_account, 4: self.exit} print_out = "(1) Sign up \n (2) Log in \n (3) Delete Account \n (4) Exit" return self._take_option(options, print_out)
[ "def print_user_options():\n print(\"\\n******************* USER'S MENU *****************\"\n \"\\n\\nChoose a number from 1 to 2 from the below options:\"\n \"\\n\\n# 1: Show all teachers\\n\\n# 2: Quit\"\n \"\\n*************************************************\")", "def print_login...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints out homepage options to the user
def homepage(self): print('-=' * 12 + " Home Page " + '-=' * 12) self._user.list_contacts() options = {1: self.add_contact, 2:self.remove_contact ,3: self.view_contact_chat, 4: self.sign_out, 5: self.exit} print_out = "(1) Add new contact \n (2) Remove Contact \n (3) View my chats \n (4)...
[ "def display_other_options():\n print(\"> - Next Song page.\")\n print(\"< - Previous song page.\")\n print(\"q - to quit\")", "def print_user_options():\n print(\"\\n******************* USER'S MENU *****************\"\n \"\\n\\nChoose a number from 1 to 2 from the below options:\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use Authenticator object to sign out user's account
def sign_out(self): self.auth.log_out(self._user) self._user = None print("Signed out successfully") return self.logging_page()
[ "def signout(self):\r\n return self.app.get('/account/signout', follow_redirects=True)", "async def sign_out(self) -> None:\n await self._api.call('system', 'sign_out')", "def logout_user():\n pass", "def signout(self):\n session_terminated = auth.invalidate_session(self)\n if s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a contact to a user account by contact's username
def add_contact(self): contact_mob_num = self._input_mob_num("-=" * 30 + "\n" + "Please enter contact's mobile number to be added: ") if contact_mob_num == self._user.mob_num: print("You can't add yourself, IDIOT!!") return self.homepage() found_contact = self.au...
[ "def add_contact(self, username):\n if self.check_contact(username):\n return\n new_contact = self.Contacts(username)\n self.session.add(new_contact)\n self.session.commit()", "def add_contact(contacts):\n username = input(\"Enter the username: \")\n email = input(\"En...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
print all chats usernames then view one of the contact's chat
def view_contact_chat(self): if self._user.chats == {}: print("No chats to be viewed yet") self.homepage() print('-=' * 30) chats = self._user.list_chats() user_choice = self._int_input_in_range("Pick whose contact chat to be viewed: " ...
[ "def list_contacts(self):\n print('List of contancts: ')\n if self.contacts == []:\n print('-- Empty --')\n else:\n for i, contact in enumerate(self.contacts):\n new_msg_flag = self.chats[contact.mob_num][0].new_msg == self\n if new_msg_flag:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
uses Users's send_msg method to send a msg to a certain contact
def _send_msg(self, contact): msg_content = input('{} :'.format(self._user.username)) if msg_content == '0': return self.homepage() self._user.send_msg(contact, msg_content) return self._send_msg(contact)
[ "def send_message(contact, message):\n try:\n print('5 seconds to navigate to slack app..')\n time.sleep(5)\n\n # Use JumpTo slack feature\n pyautogui.hotkey('command', 'k')\n time.sleep(1)\n # Enter contact name in search box, click enter\n pyautogui.typewrite(co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Endpoint to receive new device datapoint, updates top devices cache.
def devicedata(): data = request.get_json() dd = DeviceData(**data) db.session.add(dd) db.session.commit() # update cache when write is confirmed, updates corresponding maxheaps num_top_devices = int(environ.get('NUM_TOP_DEVICES')) for feature in DeviceData.features(): # negate fea...
[ "def update(self):\n self.device = self._api.device_query(self._hardware_address, {})", "def _publish_device_metric_updates(self):\n for device_id, device_state in self._devices.items():\n if device_state.device.icpw_is_birth_certificate_fresh:\n device_payload = self._crea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve top devices per feature over interval
def dashboard(): features = request.args.get('features', None) interval = request.args.get('interval', "all_time") features = DeviceData.features() if features is None else features.split(",") if interval == "past_minute": cutoff_time = dt.now() - timedelta(minutes=1) elif interval == "past...
[ "def test_ten_most_popular_devices(self):\n devices = DeviceFactory.create_batch(15)\n dates = create_dates_in_range(0, 2, '2017-05-01T00:{}:40Z')\n create_occurrences(devices[0], dates)\n\n dates = create_dates_in_range(0, 6, '2017-05-01T00:{}:40Z')\n create_occurrences(devices[1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this runs the script to ask for a zip code and then print out the town location and population
def run_script(): var=raw_input("Enter a Zipcode: ") address='http://www.uszip.com/zip/'+var conn=urllib.urlopen(address) t=[] for line in conn.fp: line=line.strip() if '<title>' in line: line.split() print line[7:-16] if 'Total population' in line: line=line.strip('z') loc=li...
[ "def main(postalcode):\n places = postalcodes_mexico.places(postalcode)\n click.echo(places)\n return 0", "def database():\n\n zip_to_tuple, town_to_zip = query()\n\n l = ''\n\n while l != quit:\n\n l = input(\"Type in a zip code, a town name, or quit:\\n\")\n\n if l == 'quit':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert that source_files are installed in install_path and selected source files are obfuscated.
def assert_source_files_are_installed_and_obfuscated(install_path, source_files, source_files_without_obfuscate_path=None): assert os.path.isdir(install_path), "%s does not exist" % install_path for source_file, op, version, check_obfuscation in source_files:...
[ "def test_idea_missing_sources(self):\n self._idea_test(['testprojects/src/java/org/pantsbuild/testproject/missing_sources'])", "def test_bad_installs_allowed_from_path(self):\n self.data[\"installs_allowed_from\"].append(\"foo/bar\")\n self.analyze()\n self.assert_failed(with_errors=True)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert that files are installed in GAC_MSIL.
def assert_assembly_files_are_installed(assembly_source_files, microsoft_assembly_source_files): for assembly_file in assembly_source_files: assert is_file_in_subdirectory("%s.dll"% assembly_file, WINDOWS_ASSEMBLY_GAC_MSIL_PATH + assembly_file), \ "%s file not found in directory %s" % (assembly_...
[ "def test_network_lic_file_present(self):\n\n str_matlab_bin_path = self.host.check_output(\"readlink -f $(which matlab)\")\n matlab_dir = Path(str_matlab_bin_path).parents[1]\n network_lic_path = matlab_dir / \"licenses\" / \"network.lic\"\n self.assertTrue(self.host.file(str(network_li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simply apply the value_counts function to every column in a dataframe
def pandas_value_counts(df): return df.apply(pd.value_counts).fillna(0)
[ "def obj_value_counts(df):\n df_obj = obj_df(df)\n for col in df_obj.columns:\n print(df_obj[col].value_counts())\n print('-'*100)", "def count(df):\r\n\r\n\tdf_count_dict = dict()\r\n\r\n\tfor i, col in enumerate(df.columns):\r\n\t\tdf_count_dict[col] = df[col].count()\r\n\r\n\tdf_count = pd....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a path based on url.
def generate_path(url, output_path='', site_root=''): path = [] if not site_root else [site_root.replace('/', '')] for item in url.split('/'): if item: path.append(item) if '.' not in path[-1] and path[-1].split('.'): path.append('index.html') return os.path.join(output_path,...
[ "def urlToPath(url):", "def path_for(self, url, pagename):\n parts = pagename.split('/')[:-1]\n if len(parts) == 0:\n return url[1:]\n return os.path.relpath(url, '/%s' % '/'.join(parts))", "def _url(path: str) -> str:\n return urlparse.urljoin(API_ROOT, path)", "def pathToU...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize a new contest with country name and db cursor.
def __init__(self, country, cursor): self.country = country self.cursor = cursor
[ "def init_data_for_countries(db_data):\n countries = db_data.get('country')\n if countries is not None:\n rows = countries.get('data')\n for row in rows:\n country = Country(name=row)\n db_add_and_commit(db, country)", "def test_init(self):\n with SqlConnectionMana...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist.
def find_notebook(fullname, path=None): name = fullname.rsplit(".", 1)[-1] if not path: path = [""] for d in path: nb_path = os.path.join(d, name + ".ipynb") if os.path.isfile(nb_path): return nb_path # let import Notebook_Name find "Notebook Name.ipynb" n...
[ "def find_notebook(fullname ,path=None):\n name = fullname.rsplit('.',1)[-1]\n if not path:\n path=['']\n \n for d in path:\n nb_path = os.path.join(d,name+\".ipynb\")\n if os.path.isfile(nb_path):\n return nb_path\n nb_path = nb_path.replace(\"_\",\" \")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that tells if the given locale is supported by the Anaconda or not. We consider locales supported by the langtable as supported by the Anaconda.
def is_supported_locale(locale): en_name = get_english_name(locale) return bool(en_name)
[ "def Locale_IsAvailable(*args, **kwargs):\n return _gdi_.Locale_IsAvailable(*args, **kwargs)", "def IsAvailable(*args, **kwargs):\n return _gdi_.Locale_IsAvailable(*args, **kwargs)", "def is_multilocale_arkouda():\n out = subprocess.check_output([get_arkouda_server(), '--about'], encoding='utf-8')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that tells if the given locale can be displayed by the Linux console. The Linux console can display Latin, Cyrillic and Greek characters reliably, but others such as Japanese, can't be correctly installed.
def locale_supported_in_console(locale): locale_scripts = get_locale_scripts(locale) return set(locale_scripts).issubset(SCRIPTS_SUPPORTED_BY_CONSOLE)
[ "def is_multilocale_arkouda():\n out = subprocess.check_output([get_arkouda_server(), '--about'], encoding='utf-8')\n return 'CHPL_COMM: none' not in out", "def Locale_IsAvailable(*args, **kwargs):\n return _gdi_.Locale_IsAvailable(*args, **kwargs)", "def is_supported_locale(locale):\n\n en_name = get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that tells if the given langcode matches the given locale. I.e. if all parts of appearing in the langcode (language, territory, script and encoding) are the same as the matching parts of the locale.
def langcode_matches_locale(langcode, locale): langcode_parts = parse_langcode(langcode) locale_parts = parse_langcode(locale) if not langcode_parts or not locale_parts: # to match, both need to be valid langcodes (need to have at least # language specified) return False # Che...
[ "def locale_equals_language(locale, lang):\n locale_parts = locale.lower().split('-')\n lang_parts = lang.lower().split('-')\n\n return locale_parts[0] == lang_parts[0]", "def is_valid_language_code(code):\n try:\n iso639.languages.get(part3=code)\n return True\n except KeyError:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the best match for the locale in a list of langcodes. This is useful when e.g. pt_BR is a locale and there are possibilities to choose an item (e.g. rnote) for a list containing both pt and pt_BR or even also pt_PT.
def find_best_locale_match(locale, langcodes): score_map = { "language" : 1000, "territory": 100, "script" : 10, "encoding" : 1 } def get_match_score(locale, langcode): score = 0 locale_parts = parse_langcode(locale) langco...
[ "def get_closest(self, *locale_codes):\n app = get_app()\n if self._translations is None:\n self.load_translations(app.config['LOCALE_PATH'])\n\n for code in locale_codes:\n if not code:\n continue\n code = code.replace(\"-\", \"_\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Procedure setting the system to use the given locale and store it in to the ksdata.lang object (if given). DOES NOT PERFORM ANY CHECKS OF THE GIVEN LOCALE. $LANG must be set by the caller in order to set the language used by gettext. Doing this in a threadsafe way is up to the caller. We also try to set a proper consol...
def setup_locale(locale, lang=None, text_mode=False): if lang: lang.lang = locale # not all locales might be displayable in text mode if text_mode: # check if the script corresponding to the locale/language # can be displayed by the Linux console # * all scripts for the giv...
[ "def _initializeLocale():\n \n if sys.platform == constants.WIN32:\n locale.setlocale(locale.LC_ALL, \"\")\n else:\n if constants.LC_ALL in os.environ:\n try:\n locale.setlocale(locale.LC_ALL, os.environ[constants.LC_ALL])\n return\n except ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returning english name for the given locale.
def get_english_name(locale): parts = parse_langcode(locale) if "language" not in parts: raise InvalidLocaleSpec("'%s' is not a valid locale" % locale) name = langtable.language_name(languageId=parts["language"], territoryId=parts.get("territory", ""), ...
[ "def get_native_name(locale):\n\n parts = parse_langcode(locale)\n if \"language\" not in parts:\n raise InvalidLocaleSpec(\"'%s' is not a valid locale\" % locale)\n\n name = langtable.language_name(languageId=parts[\"language\"],\n territoryId=parts.get(\"territory...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returning native name for the given locale.
def get_native_name(locale): parts = parse_langcode(locale) if "language" not in parts: raise InvalidLocaleSpec("'%s' is not a valid locale" % locale) name = langtable.language_name(languageId=parts["language"], territoryId=parts.get("territory", ""), ...
[ "def native_name(self):\n return self.language.native_name", "def get_localized_name(name):\n locale = \"{}_{}\".format(\n name[\"preferredLocale\"][\"language\"],\n name[\"preferredLocale\"][\"country\"]\n )\n return name['localized'].get(locale, '')", "def get_language_name(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method that generates (i.e. returns a generator) available translations for the installer in the given localedir.
def get_available_translations(localedir=None): localedir = localedir or gettext._default_localedir # usually there are no message files for en messagefiles = sorted(glob.glob(localedir + "/*/LC_MESSAGES/anaconda.mo") + ["blob/en/blob/blob"]) trans_gen = (path.split(os.path.s...
[ "def init_translations():\n if \"@lang\" in input.load_input():\n lang = input.get_lang()\n try:\n trad = gettext.GNUTranslations(open(\"../course/common_student/$i18n/\" + lang + \".mo\", \"rb\"))\n except FileNotFoundError:\n trad = gettext.NullTranslations()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returning list of locales for the given territory. The list is sorted from the most probable locale to the least probable one (based on langtable's ranking.
def get_territory_locales(territory): return langtable.list_locales(territoryId=territory)
[ "def get_locales(self) -> List[str]:\n\n return self.possible_locale_list", "def translated_locales(self):\r\n return sorted(set(self.locales) - set([self.source_locale]))", "def sorted_languages():\n # Python 3: Use functools.cmp_to_key\n def compare(a, b):\n if a.name == u\"English\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returning preferred keyboard layouts for the given locale.
def get_locale_keyboards(locale): parts = parse_langcode(locale) if "language" not in parts: raise InvalidLocaleSpec("'%s' is not a valid locale" % locale) return langtable.list_keyboards(languageId=parts["language"], territoryId=parts.get("territory", ""), ...
[ "def parse_layout(keymap_c: str):\n lines = get_keymap(keymap_c)\n lines = remove_excess_white_space(lines)\n layout_strs = get_layouts_strs(lines)\n return get_layout_keys(layout_strs)", "def ck_lib_layouts():\n import ck_lib\n\n return [\n ck_lib.library.LayoutType.ColumnMaj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returning preferred timezones for the given locale.
def get_locale_timezones(locale): parts = parse_langcode(locale) if "language" not in parts: raise InvalidLocaleSpec("'%s' is not a valid locale" % locale) return langtable.list_timezones(languageId=parts["language"], territoryId=parts.get("territory", ""), ...
[ "def get_timezone_list():\n return pytz.country_timezones('US')", "def Timezones(context):\n return SimpleVocabulary.fromValues(pytz.all_timezones)", "def GetTimeZones(self):\n yield 'local'\n for zone in pytz.all_timezones:\n yield zone", "def get_timezones() -> set[str]:\n return availab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returning locale's territory.
def get_locale_territory(locale): parts = parse_langcode(locale) if "language" not in parts: raise InvalidLocaleSpec("'%s' is not a valid locale" % locale) return parts.get("territory", None)
[ "def get_territory_name(self, locale: Locale | str | None = None) -> str | None:\n if locale is None:\n locale = self\n locale = Locale.parse(locale)\n return locale.territories.get(self.territory or '')", "def territory_country(territory_code):\n return TERRITORIES.get(territor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returning preferred console fonts for the given locale.
def get_locale_console_fonts(locale): parts = parse_langcode(locale) if "language" not in parts: raise InvalidLocaleSpec("'%s' is not a valid locale" % locale) return langtable.list_consolefonts(languageId=parts["language"], territoryId=parts.get("territory",...
[ "def getAvailableFonts():\n return list(AVAILABLE_FONTS)", "def get_system_fonts():\n fonts = set()\n for x in font_manager.findSystemFonts():\n dot = x.rfind('.')\n slash = x.rfind(sep)\n x = x[slash + 1:dot]\n fonts.add(x)\n return sorted(fonts)", "def available_text_fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returning preferred scripts (writing systems) for the given locale.
def get_locale_scripts(locale): parts = parse_langcode(locale) if "language" not in parts: raise InvalidLocaleSpec("'%s' is not a valid locale" % locale) return langtable.list_scripts(languageId=parts["language"], territoryId=parts.get("territory", ""), ...
[ "def system_lang():\n loclang, _ = locale.getdefaultlocale()\n for lang in languages():\n if loclang.startswith(lang):\n return lang\n return \"en\"", "def get_script_name(self, locale: Locale | str | None = None) -> str | None:\n if locale is None:\n locale = self\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write language configuration to the $root/etc/locale.conf file.
def write_language_configuration(lang, root): try: fpath = os.path.normpath(root + LOCALE_CONF_FILE_PATH) with open(fpath, "w") as fobj: fobj.write('LANG="%s"\n' % lang.lang) except IOError as ioerr: msg = "Cannot write language configuration file: %s" % ioerr.strerror ...
[ "def _saveLanguagesToConfig(self):\n logger.debug(u\"Saving languages %s to configuration file\" % self._languages)\n self.config.set(\"DEFAULT\", \"languages\", \",\".join(self._languages))\n self._writeConfigFile()", "def change_language(self):\n if 'ru' == self.config.get('total', '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Procedure that returns the firmware language information (if any).
def get_firmware_language(text_mode=False): try: n = "/sys/firmware/efi/efivars/PlatformLang-8be4df61-93ca-11d2-aa0d-00e098032b8c" d = open(n, 'r', 0).read() except IOError: return None # the contents of the file are: # 4-bytes of attribute data that we don't care about # N...
[ "def available_language_model():\n from malaya_speech.utils import describe_availability\n\n return describe_availability(_language_model_availability)", "def get_languages():\n\n\treturn BT_LANGUAGES", "def describeWikiLanguage(ver, app):\r\n\r\n return ((\"wikidpad_mini_1_0\", u\"WikidPad Mini 1.0\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Puts the year, month and day objects in the right order according to the currently set locale and provides format specification for each of the fields.
def resolve_date_format(year, month, day, fail_safe=True): FAIL_SAFE_DEFAULT = "%Y-%m-%d" def order_terms_formats(fmt_str): # see date (1), 'O' (not '0') is a mystery, 'E' is Buddhist calendar, '(.*)' # is an arbitrary suffix field_spec_re = re.compile(r'([-_0OE^#]*)([yYmbBde])(.*)') ...
[ "def update_date_fields(self):\n if self.day_num and not self.day_ordstr:\n self.day_ordstr = ORDINALS[self.day_num]\n if (self.month_num is not None) and (not self.month_str):\n self.month_str = CYPRIAN_MONTHS[self.month_num]\n if self.year_num and not self.year_ordstr:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to set console font to the given value.
def set_console_font(font): log.debug("setting console font to %s", font) rc = execWithRedirect("setfont", [font]) if rc == 0: log.debug("console font set successfully to %s", font) return True else: log.error("setting console font to %s failed", font) return False
[ "def set_font(font):\n global _font\n _font = font", "def set_font(self, font):\n pass", "def setFont(text: unicode, color: java.awt.Color, ptSize: int) -> unicode:\n ...", "def syncterm_setfont(font_name, font_page=0):\n # font_code is the index of font_name in SYNCTERM_FONTMAP, so tha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clean and configure the local environment variables. This function will attempt to determine the desired locale and configure the process environment (os.environ) in the least surprising way. If a locale argument is provided, it will be attempted first. After that, this function will attempt to use the language environ...
def setup_locale_environment(locale=None, text_mode=False, prefer_environment=False): # pylint: disable=environment-modify # Look for a locale in the environment. If the variable is setup but # empty it doesn't count, and some programs (KDE) actually do this. # If prefer_environment is set, the enviro...
[ "def _initializeLocale():\n \n if sys.platform == constants.WIN32:\n locale.setlocale(locale.LC_ALL, \"\")\n else:\n if constants.LC_ALL in os.environ:\n try:\n locale.setlocale(locale.LC_ALL, os.environ[constants.LC_ALL])\n return\n except ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests to see if both locations are the same ie rank and file is the same.
def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError("Cannot compare other types with Location") return int(self.rank) == int(other.rank) and \ int(self.file) == int(other.file)
[ "def check_files_equal(callee_file, file1_name, file2_name):\n file_path = os.path.dirname(callee_file)\n file1_path = os.path.join(file_path, file1_name)\n file2_path = os.path.join(file_path, file2_name)\n print(file1_path, file2_path)\n result = filecmp.cmp(file1_path, file2_path, shallow=False)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns if the move is on the board or not. If the rank and file are both in between 0 and 7, this method will return True.
def on_board(self): if -1 < self._rank < 8 and \ -1 < self._file < 8: return True return False
[ "def winning_move(board):\n for row in WINNING_POSITIONS:\n if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:\n return True\n\n return False", "def check_on_board(board, move):\r\n if 1 <= move[0] + 1 <= board.row_num and 1 <= move[1] + 1 <= board.col_num:\r\n return T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shifts in direction provided by ``Direction`` enum.
def shift(self, direction): try: if direction == Direction.UP: return self.shift_up() elif direction == Direction.DOWN: return self.shift_down() elif direction == Direction.RIGHT: return self.shift_right() elif direc...
[ "def shift(self, shift_distance=0):\n\n pass", "def shift(self, shift: int, direction: int = 1) -> None:\n if not isinstance(shift, int):\n raise TypeError(\"Shift value must be an integer\")\n if direction in (1, -1):\n oldLi = (\n self.elements[shift * d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds Location shifted up by 1
def shift_up(self, times=1): try: return Location(self._rank + times, self._file) except IndexError as e: raise IndexError(e)
[ "def _shift(self, offset):\n return FeatureLocation(start = self._start._shift(offset),\n end = self._end._shift(offset))", "def shift_down(self, times=1):\n try:\n return Location(self._rank - times, self._file)\n except IndexError as e:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds Location shifted down by 1
def shift_down(self, times=1): try: return Location(self._rank - times, self._file) except IndexError as e: raise IndexError(e)
[ "def _shift(self, offset):\n return FeatureLocation(start = self._start._shift(offset),\n end = self._end._shift(offset))", "def next_location(x, y, direction):\n new_x = x\n new_y = y\n\n if direction == \"W\":\n new_x = new_x - 1\n elif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds Location shifted right by 1
def shift_right(self, times=1): try: return Location(self._rank, self._file + times) except IndexError as e: raise IndexError(e)
[ "def shift_down_right(self, times=1):\n try:\n return Location(self._rank - times, self._file + times)\n except IndexError as e:\n raise IndexError(e)", "def _shift(self, offset):\n return FeatureLocation(start = self._start._shift(offset),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds Location shifted left by 1
def shift_left(self, times=1): try: return Location(self._rank, self._file - times) except IndexError as e: raise IndexError(e)
[ "def _shift(self, offset):\n return FeatureLocation(start = self._start._shift(offset),\n end = self._end._shift(offset))", "def shift_down_left(self, times=1):\n try:\n return Location(self._rank - times, self._file - times)\n except IndexError as e:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds Location shifted up right by 1
def shift_up_right(self, times=1): try: return Location(self._rank + times, self._file + times) except IndexError as e: raise IndexError(e)
[ "def _shift(self, offset):\n return FeatureLocation(start = self._start._shift(offset),\n end = self._end._shift(offset))", "def upright(self):\n return Coord([self.x + 1, self.y - 1])", "def shift_up(self, times=1):\n try:\n return Location(self._ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds Location shifted up left by 1
def shift_up_left(self, times=1): try: return Location(self._rank + times, self._file - times) except IndexError as e: raise IndexError(e)
[ "def _shift(self, offset):\n return FeatureLocation(start = self._start._shift(offset),\n end = self._end._shift(offset))", "def shift_down_left(self, times=1):\n try:\n return Location(self._rank - times, self._file - times)\n except IndexError as e:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds Location shifted down right by 1
def shift_down_right(self, times=1): try: return Location(self._rank - times, self._file + times) except IndexError as e: raise IndexError(e)
[ "def downright(self):\n return Coord([self.x + 1, self.y + 1])", "def shift_down(self, times=1):\n try:\n return Location(self._rank - times, self._file)\n except IndexError as e:\n raise IndexError(e)", "def upright(self):\n return Coord([self.x + 1, self.y - 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds Location shifted down left by 1
def shift_down_left(self, times=1): try: return Location(self._rank - times, self._file - times) except IndexError as e: raise IndexError(e)
[ "def downleft(self):\n return Coord([self.x - 1, self.y + 1])", "def upleft(self):\n return Coord([self.x - 1, self.y - 1])", "def _shift(self, offset):\n return FeatureLocation(start = self._start._shift(offset),\n end = self._end._shift(offset))", "def shif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return shopping cart detail
def cart_detail(request): cart = Cart(request) return render(request, 'cart/cart.html', {'cart': cart})
[ "def detail(request):\n # del request.session['cart_id']\n # del request.session['total_in_cart']\n data = {}\n if (cart_id := request.session.get('cart_id', None)):\n cart = Cart.objects.get(pk=cart_id)\n data['products_in_cart'] = cart.cartitems.all()\n data['total_price'] = cart....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the indexes listed in this dataset's image set file.
def _load_image_set_index(self): image_index = [] image_set_file = self.data_dir \ + "/ImageSets/{}.txt".format(self.mode) assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file, 'r') as f: f...
[ "def _load_image_set_index(self):\n with open(self.img_set) as f:\n image_index = [x.strip() for x in f.readlines()]\n\n return image_index", "def _load_image_set_index(self):\n image_set_file = os.path.join(self._data_path, 'ImageSets', 'Main',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls the `to_pipeline` method on itself.
def pipeline(self) -> Pipeline: if self._to_pipeline is None: raise AttributeError( "pipeline not available because `to_pipeline` was not set on __init__." ) return self._to_pipeline(self)
[ "def pipeline(self):\n # gotta avoid circular imports by deferring\n from .pipeline import Pipeline\n return Pipeline().from_source(self._collection)", "def _transform_pipeline(self, pipeline: \"DatasetPipeline\") -> \"DatasetPipeline\":\n\n fit_status = self.fit_status()\n if f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists all primitive nodes, starting with the Individual's main node.
def primitives(self) -> List[PrimitiveNode]: primitives = [self.main_node] current_node = self.main_node._data_node while isinstance(current_node, PrimitiveNode): # i.e. not DATA_TERMINAL primitives.append(current_node) current_node = current_node._data_node retu...
[ "def ListPrimitives(self):\n return [mod.attrib['Name'] for mod in self._tree.getroot().iter('Primitive')]", "def get_all_nodes(self):\n pass", "def list_nodes(self, type_):\n raise NotImplementedError()", "def displayNode(self):\n for x in self.__node:\n print(x)", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists all terminals connected to the Individual's primitive nodes.
def terminals(self) -> List[Terminal]: return [terminal for prim in self.primitives for terminal in prim._terminals]
[ "def terminals(self):\n terminals = []\n # The two following lines are not the same as\n # descendants = self.children\n # which would extend also to self.children!\n descendants = []\n descendants.extend(self.children)\n for child in descendants:\n if chi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace the terminal at `position` by `new_terminal` inplace.
def replace_terminal(self, position: int, new_terminal: Terminal) -> None: scan_position = 0 for primitive in self.primitives: if scan_position + len(primitive._terminals) > position: terminal_to_be_replaced = primitive._terminals[position - scan_position] if ...
[ "def change_position(board: Board, position: Position, character: str) -> Board:\n board = list(board)\n \n row = board[position[0]]\n new_row = row[:position[-1]] + character + row[position[-1] + 1:]\n board[position[0]] = new_row\n\n board = tuple(board) \n\n return board", "def reset_po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace the PrimitiveNode at `position` by `new_primitive`.
def replace_primitive(self, position: int, new_primitive: PrimitiveNode): last_primitive = None for i, primitive_node in enumerate(self.primitives): if i == position: if primitive_node._primitive.output != new_primitive._primitive.output: raise ValueError(...
[ "def replace_node(self, new_node):\n\n pass", "def replace_terminal(self, position: int, new_terminal: Terminal) -> None:\n scan_position = 0\n for primitive in self.primitives:\n if scan_position + len(primitive._terminals) > position:\n terminal_to_be_replaced = pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct an Individual from its `pipeline_str` representation.
def from_string( cls, string: str, primitive_set: dict, to_pipeline: Optional[Callable] = None, strict: bool = True, ) -> "Individual": expression = PrimitiveNode.from_string(string, primitive_set, strict) return cls(expression, to_pipeline=to_pipeline)
[ "def from_str(cls, string):", "def from_str(cls, elementstr):\n ival, params = cls.parse(elementstr)\n return cls(ival, params)", "def on_pipeline_from_string(code: str) -> PipelineInspectorBuilder:\n return PipelineInspectorBuilder(python_code=code)", "def fromstring(text, parser=None, b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates code for lhs_ast = new_ast, where new_ast is an array initializer of either Type[expr1][expr2]...[exprN] or { { { ... } } }. Currently on supports Type[expr1]
def new_array(lhs_ast, new_ast): assert(new_ast.tag == 'NEW_ARRAY') rank = new_ast.rank assert(rank > 0) type_name = new_ast.type_name array_var = checker.new_temp() env = {} template = '{\n' template += 'var %s%s %s;\n' % (type_name, '[]'*rank, array_var) if rank == 1: templ...
[ "def compile_ast(self, ast, var_dict, code):\n if code is None:\n code = []\n\n ntype = ast.get_value()\n children = ast.get_children()\n\n if ntype == 'const':\n code_str = str(children[0].get_value())\n\n elif ntype == 'get':\n # Reference to a v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a shared matrix or vector using the given in_size and out_size. Inputs
def create_shared(out_size, in_size=None, name=None): if in_size is None: return theano.shared(np.zeros((out_size, ),dtype=theano.config.floatX), name=name) else: return theano.shared(np.zeros((out_size, in_size),dtype=theano.config.floatX), name=name)
[ "def gen_symmetric_matrix(size):\n matrix = np.zeros(shape=(size, size), dtype=np.float128)\n for i in range(0, size):\n for j in range(0, i + 1):\n value = uniform(-size, size)\n matrix[i][j] = value\n matrix[j][i] = value\n vector_x = Ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute the query in database. con is a SQLite connection and query is a string. Returns a dict with the query, the rows and column's names in the description item.
def execute(con, query): c = con.cursor() data = {} data['query'] = query data['rows'] = None data["description"] = None data['error'] = None try: data['rows'] = c.execute(query).fetchall() or None data["description"] = c.description or None except Exception as e: data['error'] = str(e) return json.dumps...
[ "def query(self, query):\n cursor = self.db.execute(query)\n columns = map(lambda x: x[0], cursor.description)\n return (cursor.fetchall(), columns)", "def execute_query(query):\n c.execute(query)\n return c.fetchall()", "def query(self, sql):\n\n try:\n results = se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Will attempt to parse out the title of a movie given a file name that contains the movie title. Most useful for torrented movies that follow a particular naming scheme
def parse_movie_title(file_name): movie_name = os.path.basename(file_name) movie_name = parsers.remove_extension(file_name) movie_name = movie_name.lower() movie_name = parsers.fix_word_seperators(movie_name) movie_name = parsers.remove_tags(movie_name) movie_name = parsers.remove_resolution(movie_name) movie_na...
[ "def get_title(movie_path):\n movie_title = movie_path.split('/')[-2:-1][0].split('.')[0]\n return movie_title", "def parse_manga_title(filename):\n print_info('Attempting to parse manga title from {0}'.format(filename))\n for regex in MANGA_TITLE_REGEX:\n m = re.search(regex, filename)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve wall time from cloudinit metadata. CloudInit saves all passed metadata into a cloudinit.sources.DataSource object with attribute 'metadata' A DataSourceOpenStack object stores information on additional metadata in a subdictionary 'meta'.
def get_times(): try: with open("/var/lib/cloud/instance/obj.pkl", "r") as file_: data = pickle.load(file_) except IOError: return meta = data.metadata.get("meta") if meta is None: raise EnvironmentError("Wrong virtualization environment.") keys = [x for x in me...
[ "def wall_time(self):", "def walltime(self):\n return self.step.run[\"walltime\"]", "def get_creation_time(metadata):\n meta = metadata.replace(\"'\", '\"') # json demands double-quote\n meta = json.loads(meta)\n return meta['creationTime']", "def get_walltime(self):\n walltime = self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save walltime information to system variables WALLTIME & BOOTTIME. Values by default are stored in /etc/environment, discarding old wall/boottime entries, preserving the rest.
def save_env(wall_time_=None, start_time_=None, environment_file="/etc/environment"): if not os.access(environment_file, os.W_OK): raise EnvironmentError("Can't write to %s" % environment_file) with open(name=environment_file, mode="r") as file_: # keep results != WALLTIME/BOOTTIME cont...
[ "def set_walltime(self, walltime):\n self.set_attr('walltimeused', walltime)", "def set_walltime(self, walltime):\n self.assessor.attrs.set('%s/walltimeused' % self.atype, walltime)", "def set_walltime(self, walltime: str) -> None:\n # For compatibility with other launchers, as explained in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
recs is array of Preverb objects
def write_preverbs(recs,fileout): fout = codecs.open(fileout,'w') n = 0 nadj=0 for rec in recs: L = rec.L # headword record number hw = rec.hw # the headword pfx = rec.pfx # the preverb prefixes pfxhw = rec.pfxhw linenum = rec.linenum out = "%s:%s:%s:%s:%s" %(L,hw,pfx,pfxhw,linenum) fout.write(out + ...
[ "def add(self, rec):\n\n q = rec.split()\n\n self.inds.append(int(q[0]))\n self.time.append(float(q[2]))\n self.tau.append(float(q[4]))\n self.rt['code'].append(int(q[6]))\n self.rt['str'].append(q[7])\n for i in range(3):\n self.n[i]['val'].append(int(q[9...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yield sample analysis results fetched from the server.
def get_analysis_results(self, cache=True): if cache and self._get_result_cache: for ar in self._get_result_cache: yield ar return url = f'sample_ars?sample_id={self.uuid}' result = self.knex.get(url) for result_blob in result['results']: ...
[ "def load(self):\n for sample in self.data:\n yield sample", "def get_data(self):\n if self.random_seeds: \n self._validate_random_seeds()\n seed_iter = list(map(iter,self.random_seeds))\n nsamples = len(self.random_seeds[0])\n else:\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a manifest for this sample.
def get_manifest(self): url = f'samples/{self.uuid}/manifest' return self.knex.get(url)
[ "def manifest(self):\n return _Manifest.from_json(self.get(_MANIFEST_FILENAME))", "def manifest(self) -> \"AssemblyManifest\":\n return jsii.get(self, \"manifest\")", "def manifest(self) -> \"ArtifactManifest\":\n return jsii.get(self, \"manifest\")", "def create_manifest(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the canvas size in pixels.
def getCanvasSize(): return canvas.winfo_width(), canvas.winfo_height()
[ "def get_canvas_width(self):\n\n return self.winfo_width()", "def get_canvas_height(self):\n return self.winfo_height()", "def size(self):\n return self.surface.get_size()", "def getPixelSize(self):\n return _yarp.Image_getPixelSize(self)", "def numPixels(self):\n\t\treturn self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves a python object to path (in filesytem).
def save_object(path,object): with open(path,"wb") as f: pickle.dump(object,f,pickle.HIGHEST_PROTOCOL)
[ "def store(obj, path: str) -> None:\n dirname = os.path.dirname(os.path.abspath(path))\n if dirname != \"\":\n os.makedirs(dirname, exist_ok=True)\n Backend({}, {}).dump(obj, path)", "def save_pickle(obj, path):\n pickle_out = open(path, \"wb\")\n dill.dump(obj, pickle_out)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loads a python object from path (in filesytem).
def load_object(path): with open(path,"rb") as f: object = pickle.load(f) return object
[ "def load_object(path):\n\n try:\n dot = path.rindex('.')\n except ValueError:\n raise ValueError(\"Error loading object '%s': not a full path\" % path)\n\n module, name = path[:dot], path[dot + 1:]\n mod = import_module(module)\n\n try:\n obj = getattr(mod, name)\n except Att...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of values filled with random numbers. The number of elements changes each time the function is called
def get_value_list(): return [some_random_number() for _ in range(some_random_number())]
[ "def _CreateRandomValues(self, num_values=100):\r\n return [int(random.uniform(0, 1 << 20)) for i in xrange(num_values)]", "def generate_numbers():\n\n return random.sample(range(100), 10)", "def generate_list(seed):\n rng = galsim.UniformDeviate(seed)\n out = []\n for i in range(20):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a nonframed message using the default algorithm.
def test_encryption_cycle_default_algorithm_non_framed(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=0, ) ...
[ "def test_encryption_cycle_default_algorithm_non_framed_no_encryption_context(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"], key_provider=self.kms_master_key_provider, frame_length=0\n )\n plaintext, _ = aws_encryption_sdk.decrypt(source=ciph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a nonframed message using the default algorithm.
def test_encryption_cycle_default_algorithm_non_framed_no_encryption_context(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, frame_length=0 ) plaintext, _ = aws_encryption_sdk.decrypt(source=ciphertext, key...
[ "def test_encryption_cycle_default_algorithm_non_framed(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_length=0,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a single frame message using the default algorithm.
def test_encryption_cycle_default_algorithm_single_frame(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=1024, ) ...
[ "def test_encryption_cycle_default_algorithm_multiple_frames(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"] * 100,\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a framed message with multiple frames using the default algorithm.
def test_encryption_cycle_default_algorithm_multiple_frames(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"] * 100, key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=1024, ...
[ "def test_encryption_cycle_default_algorithm_single_frame(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_length=1024,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a single frame message using the aes_128_gcm_iv12_tag16 algorithm.
def test_encryption_cycle_aes_128_gcm_iv12_tag16_single_frame(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=1024, ...
[ "def test_encryption_cycle_aes_192_gcm_iv12_tag16_single_frame(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_length=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a nonframed message using the aes_128_gcm_iv12_tag16 algorithm.
def test_encryption_cycle_aes_128_gcm_iv12_tag16_non_framed(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=0, a...
[ "def test_encryption_cycle_aes_192_gcm_iv12_tag16_non_framed(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_length=0,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a single frame message using the aes_192_gcm_iv12_tag16 algorithm.
def test_encryption_cycle_aes_192_gcm_iv12_tag16_single_frame(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=1024, ...
[ "def test_encryption_cycle_aes_256_gcm_iv12_tag16_single_frame(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_length=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a nonframed message using the aes_192_gcm_iv12_tag16 algorithm.
def test_encryption_cycle_aes_192_gcm_iv12_tag16_non_framed(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=0, a...
[ "def test_encryption_cycle_aes_256_gcm_iv12_tag16_non_framed(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_length=0,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a single frame message using the aes_256_gcm_iv12_tag16 algorithm.
def test_encryption_cycle_aes_256_gcm_iv12_tag16_single_frame(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=1024, ...
[ "def test_encryption_cycle_aes_192_gcm_iv12_tag16_single_frame(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_length=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a nonframed message using the aes_256_gcm_iv12_tag16 algorithm.
def test_encryption_cycle_aes_256_gcm_iv12_tag16_non_framed(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=0, a...
[ "def test_encryption_cycle_aes_192_gcm_iv12_tag16_non_framed(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n frame_length=0,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a single frame message using the aes_192_gcm_iv12_tag16_hkdf_sha256 algorithm.
def test_encryption_cycle_aes_192_gcm_iv12_tag16_hkdf_sha256_single_frame(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=10...
[ "def test_encryption_cycle_aes_256_gcm_iv12_tag16_hkdf_sha256_single_frame(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the enrypt/decrypt cycle completes successfully for a nonframed message using the aes_192_gcm_iv12_tag16_hkdf_sha256 algorithm.
def test_encryption_cycle_aes_192_gcm_iv12_tag16_hkdf_sha256_non_framed(self): ciphertext, _ = aws_encryption_sdk.encrypt( source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, encryption_context=VALUES["encryption_context"], frame_length=0, ...
[ "def test_encryption_cycle_aes_256_gcm_iv12_tag16_hkdf_sha256_non_framed(self):\n ciphertext, _ = aws_encryption_sdk.encrypt(\n source=VALUES[\"plaintext_128\"],\n key_provider=self.kms_master_key_provider,\n encryption_context=VALUES[\"encryption_context\"],\n fra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }