query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Goldman Sachs' indicative charge of the bond (dollars).
def gs_charge_dollars(self) -> RangeFilter: return self.__gs_charge_dollars
[ "def get_charge(symbol):\n atom = as_atom(symbol)\n return atom.GetFormalCharge()", "def charge_2(dists, charges):\n d6 = dists <= 6.0\n d8 = dists <= 8.0\n d6_8 = logical_and(logical_not(d6), d8)\n epsilons = (d6*4.0) + \\\n d6_8*(38.0*dists-224.0) + \\\n logical_not(d8)*80.0\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a screen using GsScreenApi if it doesn't exist. Update the report if it does.
def save(self): parameters = self.__to_target_parameters() target_screen = TargetScreen(name=self.name, parameters=parameters) if self.id: target_screen.id = self.id GsScreenApi.update_screen(target_screen) else: screen = GsScreenApi.create_screen(targ...
[ "def createScreen(self, screen_name):\n self.screenname_field = screen_name\n self.click_ok_button()", "def post(self, args, id, test):\n # check current user authorization\n fulltext = db.session.query(Fulltext).get(id)\n if not fulltext:\n return not_found_error('<F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mock Sense object for authenticatation.
def mock_sense(): with patch( "homeassistant.components.sense.config_flow.ASyncSenseable" ) as mock_sense: mock_sense.return_value.authenticate = AsyncMock(return_value=True) mock_sense.return_value.validate_mfa = AsyncMock(return_value=True) mock_sense.return_value.sense_access_...
[ "def test_access_token_set(self, client, mocker):\n session_get = mocker.spy(requests.Session, \"get\")\n client.access_token = \"token\"\n assert client.access_token, \"token\"\n client.get_object(\"user\", \"me\")\n session_get.assert_called_with(\n mocker.ANY,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare the dict of values to create the new refund from the invoice. This method may be overridden to implement custom refund generation (making sure to call super() to establish a clean extension chain).
def _prepare_refund(self, invoice, date=None, period_id=None, description=None, journal_id=None): values = {} for field in ['name', 'reference', 'comment', 'date_due', 'cost_center_id', 'partner_id', 'company_id', 'account_id', 'currency_id', 'payment_term', 'user_id', 'fiscal_position'...
[ "def _prepare_invoice_line(self, invoice_id=False, invoice_values=False):\n vals = super()._prepare_invoice_line(invoice_id=invoice_id, \n invoice_values=invoice_values)\n vals['agents'] = [\n (0, 0, {'agent': x.agent.id,\n 'com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the key returned from the SAT attack is correct. It does this by creating a miter circuit with a locked version and an oracle. If the diff signal returned from the miter circuit cannot be True, then the circuits are equivalent.
def _check_key(self, key): locked_ckt = circuit.Circuit.specify_inputs(key, self.nodes, self.output_names) miter = circuit.Circuit.miter(locked_ckt, self.oracle_ckt) s = z3.Solver() s.add(miter.outputs()["diff"] == True) return s.check() == z3.unsat
[ "def test_equal_on_equal(self):\n a = SymmetricKey(\n enums.CryptographicAlgorithm.AES, 128, self.bytes_128a)\n b = SymmetricKey(\n enums.CryptographicAlgorithm.AES, 128, self.bytes_128a)\n\n self.assertTrue(a == b)\n self.assertTrue(b == a)", "def test_problem11(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the topmost visible child that overlaps with time t.
def top_clip_at_time(in_stack, t): # ensure that it only runs on stacks if not isinstance(in_stack, schema.Stack): raise ValueError( "Argument in_stack must be of type otio.schema.Stack, " "not: '{}'".format( type(in_stack) ) ) # build a ...
[ "def snapshot_at_time(self, t: float) -> Snapshot:\n for i, _ in enumerate(self.snapshots[1:]):\n if t >= self.snapshots[i - 1].time and t < self.snapshots[i].time:\n return self.snapshots[i - 1]\n\n return self.snapshots[-1]", "def best_child(self, node):\n if node....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flatten a Stack, or a list of Tracks, into a single Track. Note that the 1st Track is the bottom one, and the last is the top.
def flatten_stack(in_stack): flat_track = schema.Track() flat_track.name = "Flattened" # map of track to track.range_of_all_children range_track_map = {} def _get_next_item( in_stack, track_index=None, trim_range=None ): if track_index is None: ...
[ "def getFirstTrack(self):\n\n selectedTracks = self.getSelectedTracks()\n if not selectedTracks:\n return None\n\n t = selectedTracks[0]\n p = self.getPreviousTrack(t)\n while p != None:\n t = p\n p = self.getPreviousTrack(p)\n\n return t", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1) Gets subscribers of feed 2) Checks subscribers entries to find passive feeds. 3) Returns active_feeds, passive_feeds
def subscribers_of(feed_id): subscribers = [] try: feed_info = ff_api.fetch_feed_info(feed_id) except urllib2.HTTPError: feed_info = None print "Could'nt read subscribers:", feed_id if feed_info: print "Feed info fetched:", feed_info['id'] # get subscribers ...
[ "def get_feeds(self):\n return self.feeds", "def subscribers_for(item_uid):", "def get(self):\n feeds = []\n with self.get_db_session() as session:\n user = session.query(User).get(self.require_auth(session))\n for feed in user.subscriptions:\n feeds.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if event is a private slack channel
def is_private(event): return event.get('channel').startswith('D')
[ "def is_private(channel):\n\treturn isinstance(channel, discord.abc.PrivateChannel)", "def is_private_check(message):\r\n if(message.channel != message.author.dm_channel):\r\n message.content = \"is_private\"\r\n return message.channel == message.author.dm_channel", "def is_open(channel):\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Says hi to the user by formatting their mention
def say_hi(user_mention): response_template = random.choice(['Sup, {mention}...', 'Yo! {mention}', 'Ni hao']) return response_template.format(mention=user_mention)
[ "async def say_hi(self, to):\n name = to\n if to == 'me':\n name = self._message.author.name\n return f'Hello {name}, how are you?'", "def greet_user(self):\n print(\"Greetings \" + self.f_name.title() + \" \" + self.l_name.title() + \" we hope you enjoy your stay with us!\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring.
def get_top_n_words(word_list, n): word_frequencies = {} for word in word_list: word_frequencies[word.lower()] = word_frequencies.get(word.lower(), 0) + 1 top_words = sorted(word_frequencies, key=word_frequencies.get, reverse=True)[:n] return [(word_frequencies[word], word) for word in top_words]
[ "def most_frequent_words(text, n, lowercase=False):\r\n # YOUR CODE HERE\r\n\r\n from collections import Counter\r\n\r\n if lowercase:\r\n words = [word.strip().lower() for word in text.split()]\r\n else:\r\n words = [word.strip() for word in text.split()]\r\n\r\n word_count = Counter(wor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
V.InterpolateLine(vtkRenderer, vtkContourRepresentation, int, int) > int
def InterpolateLine(self, vtkRenderer, vtkContourRepresentation, p_int, p_int_1): ...
[ "def nearest_point_on_line(point, line): \n return line.interpolate(line.project(point))", "def extrapolate_lines(image_shape, line):\n slope, intercept = line\n y1 = image_shape[0]\n y2 = int(y1 * (3 / 5))\n x1 = int((y1 - intercept) / slope)\n x2 = int((y2 - intercept) / slope)\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write output file. `d` is the dict returned by parse_input().
def write_output(args, d): fout = args.outfile if args.head: fout.write(args.head.read() + '\n') fout.write('# ------------------------------------------\n') fout.write('# valgrind suppressions generated from\n') fout.write('# %s\n' % args.infile.name) fout.write('# ---------------------...
[ "def _write_output_file(self, output):\n self._make_output_dirs_if_needed()\n\n with open(self.output_path, \"w\") as output_file:\n json.dump(output, output_file, indent=1)\n output_file.write(\"\\n\") # json.dump does not write trailing newline", "def write_to_output_file(ou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a plot normalizing 1 fiber data to the isosbestic
def plot_1fiber_norm_iso(file_name): # Open file # Check for FileNotFound and Permission Error exceptions try: f = open(file_name, 'r',) except FileNotFoundError: print('No ' + file_name + ' file found') sys.exit(1) except PermissionError: print('Unable to access fil...
[ "def plot(self):\n norm = self.normal_vector()\n plt.plot(self.x, self.y)\n plt.quiver(self.x, self.y, norm[:, 0], norm[:, 1])\n if self.has_shadows():\n def consecutive(data, stepsize=1):\n return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists all service accounts for the current project.
def list(self): sa = ( self.resource.projects() .serviceAccounts() .list(name="projects/" + self.project_id) .execute() ) msg = "\n".join([f"{_['email']}" for _ in sa["accounts"]]) return f"```{msg}```"
[ "def list_accounts(ctx):\n accounts = ctx.obj['app'].services.accounts\n if len(accounts) == 0:\n click.echo('no accounts found')\n else:\n fmt = '{i:>4} {address:<40} {id:<36} {locked:<1}'\n click.echo(' {address:<40} {id:<36} {locked}'.format(address='Address (if known)',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes a service account's display name.
def rename(self, email, new_display_name): resource_name = f"projects/-/serviceAccounts/{email}" account = ( self.resource.projects().serviceAccounts().get(name=resource_name).execute() ) old_display_name = account["displayName"] account["displayName"] = new_display_...
[ "def set_user_display_name(self, value: str) -> None:\n if value is None:\n raise ValueError('Administrator full name is invalid')\n self._settings[USER_DISPLAY_NAME_KEY].set_value(value)", "async def set_displayname(\n self,\n target_user: UserID,\n requester: Reques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disables a service account.
def disable(self, email): self.resource.projects().serviceAccounts().disable( name=f"projects/-/serviceAccounts/{email}" ).execute() return f"Service account `{email}` disabled."
[ "def disable(nitro, service):\n __service = NSService()\n __service.set_name(service.get_name())\n __service.set_delay(service.get_delay())\n __service.set_graceful(service.get_graceful())\n return __service.perform_operation(nitro, \"disable\")", "def disableAccount():\n\tif Us...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables a service account.
def enable(self, email): self.resource.projects().serviceAccounts().enable( name=f"projects/-/serviceAccounts/{email}" ).execute() return f"Service account `{email}` enabled."
[ "def enable(nitro, service):\n __service = NSService()\n __service.set_name(service.get_name())\n return __service.perform_operation(nitro, \"enable\")", "def enable_service(credentials, service_name):\n service_usage = discovery.build(\"serviceusage\", \"v1\", credentials=credentials)\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes a service account.
def delete(self, email): self.resource.projects().serviceAccounts().delete( name=f"projects/-/serviceAccounts/{email}" ).execute() return f"Service account `{email}` deleted."
[ "def deleteServiceAcct(name, namespace):\n txClient = TxKubernetesClient()\n\n d = txClient.call(txClient.coreV1.delete_namespaced_service_account,\n name=name,\n namespace=namespace,\n body=txClient.V1DeleteOptions(),\n )\n return d", "def delete_account(l):\n user = a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists all keys for a service account.
def list_keys(self, email): keys = ( self.resource.projects() .serviceAccounts() .keys() .list(name=f"projects/-/serviceAccounts/{email}") .execute() ) msg = "\n".join(f"{key['name']} ({key['keyType']})" for key in keys["keys"]) ...
[ "def list_keys(\n self, resource_group_name, account_name, custom_headers=None, raw=False, **operation_config):\n # Construct URL\n url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/listKeys'\n path_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a service account key.
def create_key(self, email): key = ( self.resource.projects() .serviceAccounts() .keys() .create(name=f"projects/-/serviceAccounts/{email}", body={}) .execute() ) bucket_name = os.environ["KEY_FILES_BUCKET"] bucket_gs = f"gs://{...
[ "def CreateServiceAccountKey(service_account_name):\n default_credential_path = os.path.join(\n config.Paths().global_config_dir,\n _Utf8ToBase64(service_account_name) + '.json')\n credential_file_path = encoding.GetEncodedValue(os.environ,\n 'LOCAL_CREDE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes a service account key.
def delete_key(self, full_key_name): self.resource.projects().serviceAccounts().keys().delete( name=full_key_name ).execute() return f"Deleted `{full_key_name}`."
[ "def delete_key(self, key_id):\n return self.sshkey.deleteObject(id=key_id)", "def remove_service_public_key(self, service_id, key_id):\n self._transport.delete(\n \"{}/keys\".format(self.__service_base_path[0:-1]),\n self._subject, service_id=str(service_id), key_id=key_id)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Group for Service Account commands.
def service_accounts(ctx, *args, **kwargs): admin_check(ctx.obj["user_id"]) ctx.obj["sa_actions"] = ServiceAccountActions(ctx.obj["project"]) return ctx.obj["sa_actions"].list()
[ "def service_account():\n # This name should be same as SERVICE_NAME as it determines scheduler DCOS_LABEL value.\n name = config.SERVICE_NAME\n sdk_security.create_service_account(\n service_account_name=name, service_account_secret=name)\n # TODO(mh): Fine grained permissions needs to be addres...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the key and optionally add ``VirtualField`` helpers to the schema if create_helpers=True.
def __setkey__(self, schema: Schema, key: str) -> None: super().__setkey__(schema, key) if self.create_helpers: for mode in self.modes: schema._add_field("is_%s_mode" % mode, self._create_helper(mode))
[ "def set_key_field(self, key_field):\n return self.set_param('key_field', key_field)", "def _initialize_key(model_class, name):\r\n model_class._key = Key(model_class._meta['key'] or name)", "def _create_hstore_virtual_fields(self, cls, hstore_field_name):\n if not self.schema_mode:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute returns for each ticker and date in close.
def calculate_returns(close): # TODO: Implement Function return (close - close.shift(1)) / close.shift(1)
[ "def compute_returns(self):\n import numpy as np\n\n print(\"Compute returns and log returns...\")\n self.data['log_price'] = np.log(self.data['close'])\n self.data['log_returns'] = self.data['log_price'].diff()\n\n\n self.data['lagged_returns'] = self.data['returns'].shift(-1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the set of the top industries for the date
def date_top_industries(prices, sector, date, top_n): # TODO: Implement Function return set(sector.loc[prices.loc[date].nlargest(top_n).index])
[ "def get_top_expenses_data(date, next_date):\n data = []\n\n if date is None:\n expenses = Expense.objects().order_by('-amount').limit(10)\n else:\n expenses = []\n num = 1\n for expense in Expense.objects().order_by('-amount'):\n if expense.date >= date and expense.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test run analyze_returns() with net strategy returns from a file.
def test_run(filename='net_returns.csv'): net_returns = pd.Series.from_csv(filename, header=0, sep=',') t, p = analyze_returns(net_returns) print("t-statistic: {:.3f}\np-value: {:.6f}".format(t, p))
[ "def read_simulation_results(output_filename):\n\n # open the results file\n sp = openmc.StatePoint(output_filename)\n\n # access the tally\n tbr_tally = sp.get_tally(name=\"TBR\")\n df = tbr_tally.get_pandas_dataframe()\n tbr_tally_result = df[\"mean\"].sum()\n\n # print result\n print(\"Th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get item by id. Called with `GET /collections/{collectionId}/items/{itemId}`.
async def get_item(self, item_id: str, collection_id: str, **kwargs) -> Item: # If collection does not exist, NotFoundError wil be raised await self.get_collection(collection_id, **kwargs) req = self.search_request_model( ids=[item_id], collections=[collection_id], limit=1 )...
[ "def get(self, id: int) -> Optional[Item]:\n return self.session.query(Item).get(id)", "def get(category_id, item_id):\n category = CategoryModel.find_by_id(category_id)\n if not category:\n raise NotFound()\n item = ItemModel.find_by_id_and_category(category_id, item_id)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the HTML code of an horizontal bar included in a potentially wider chart.
def GenerateHTMLHorizontalBar(relWidth,relErrorWidth,color): if not (0. <= relWidth <= 1.): raise ValueError("Invalid relwidth '%s', it must be between 0 and 1" % relWidth) if not (0. <= relErrorWidth <= 1.): raise ValueError("Invalid relwidth '%s', it must be between 0 and 1" % relErrorWidth) if relWidth...
[ "def GenerateHTMLHorizontalBarChart(dataSamples,numStdev,color):\n if numStdev<0:\n raise ValueError(\"numStdev is negative (%s) but it is expected be positive\" % numStdev)\n norm = max(ds.value+(numStdev*ds.stdev) for ds in dataSamples)\n bars = [ GenerateHTMLHorizontalBar(float(d.value)/norm,float(numStdev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a row with the given label and data.
def GenerateHTMLLabelledRow(label,title,htmlRowData): return """\ <tr title="%s"> <th style="padding-top:.5ex;padding-right:1ex;text-align:right;">%s</th> <td style="padding-top:.5ex;width:100%%;"> %s </td> </tr>""" % (title,label,"\n".join(" %s"%line for line in htmlRowData.splitlines()))
[ "def make_label_row(self, row, row_name, dictionary, **kwargs):\n rowLabel = QtGui.QLabel(row_name)\n rowLabel.setSizePolicy(8,0)\n # the numeric arguments below are: row, column,rowspan, colspan\n self.gridLayout.addWidget(rowLabel, row, 0, 1, 1,\n QtCore.Qt.AlignLeft|QtCor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the code of an HTML table showing one horizontal bar for each data sample. Error bars are also shown for each dataSample at 'value+/(numStdevstdev)'.
def GenerateHTMLHorizontalBarChart(dataSamples,numStdev,color): if numStdev<0: raise ValueError("numStdev is negative (%s) but it is expected be positive" % numStdev) norm = max(ds.value+(numStdev*ds.stdev) for ds in dataSamples) bars = [ GenerateHTMLHorizontalBar(float(d.value)/norm,float(numStdev*d.stdev)/n...
[ "def create_tex_table(dbs):\n obs, series, pts = get_ordered_series(dbs)\n\n head = r\"\"\"\\begin{center}\n\\begin{tabular}{l|c|c|c}\n\\hline\n\"\"\"\n head += r\"\"\"Year & Cases & median Attack Ratio $ $S_0$ \\\\\n\\hline\n\"\"\"\n bot = r\"\"\"\n\\hline\n\\end{tabular}\n\\end{center}\n \"\"\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder buffered internal state (for incremental generation).
def reorder_incremental_state(self, incremental_state, new_order): input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: for k in input_buffer.keys(): input_buffer[k] = input_buffer[k].index_select(0, new_order) self._set_input_buff...
[ "def reorder_decoder_incremental_state(\n self, incremental_state: Dict[int, dict], inds: torch.Tensor\n ) -> Dict[int, dict]:\n incremental_state = fix_incremental_state(\n self.generation_model, incremental_state\n )\n if not incremental_state:\n return increme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder buffered internal state (for incremental generation).
def reorder_incremental_state(self, incremental_state, new_order): input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: for k in input_buffer.keys(): input_buffer[k] = input_buffer[k].index_select(0, new_order) self._set_input_buff...
[ "def reorder_decoder_incremental_state(\n self, incremental_state: Dict[int, dict], inds: torch.Tensor\n ) -> Dict[int, dict]:\n incremental_state = fix_incremental_state(\n self.generation_model, incremental_state\n )\n if not incremental_state:\n return increme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets or sets the silent status for this Session. Returns Logical Silent status.
def silent(self): return self.__silent
[ "def silent(self):\n ret = self._get_attr(\"silent\")\n return ret", "def silent(self): # bool\n return self._silent", "def silent(self):\n \n self.options[\"silent\"] = True", "def mute(self, value=None):\n if value is None:\n self._logger.info(\"Retrievi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets or sets the print_cmd status of the SyncroSim Session. Returns Logical print_cmd status.
def print_cmd(self): return self.__print_cmd
[ "def printable_status(self):\n return self._printable_status", "def _printer_status(self,printer):\n\n\t\t(stdout,stderr,status) = self._shell_command(['/usr/bin/lpstat','-p',printer],{'LANG':'C'})\n\t\tif status == 0:\n\t\t\tif ' enabled ' in stdout:\n\t\t\t\treturn 'enabled'\n\t\t\tif ' disabled ' in std...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show kernel information Including 1. max threads per block, 2. active warps per MP, 3. thread block per MP, 4. usage of shared memory, 5. const memory , 6. local memory 7. registers 8. hardware occupancy 9. limitation of the hardware occupancy
def get_kernel_function_info(a, W1=0, W2=1, W3=1): import pycuda.tools as tl import pycuda.driver as dri dev = dri.Device(0) td = tl.DeviceData() if not W1: W1 = a.max_threads_per_block to = tl.OccupancyRecord(td, W1*W2*W3, a.shared_size_bytes, a.num_regs) print "******************...
[ "def definekernel():\n time_list, volt_list=importandseparate(10)\n time_sec=makenparray(time_list)\n volt_mV=makenparray(volt_list)\n volt_mV=removeDCoffset(volt_mV)\n kernel, kernel_size=createkernel(time_sec,volt_mV)\n return kernel, kernel_size", "def _request_kernel_info(self):\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace the pageable array to pagelocked array
def get_page_locked_array(a): import pycuda.driver as drv temp_page_lock_p = drv.pagelocked_zeros_like(a, mem_flags=drv.host_alloc_flags.DEVICEMAP) if len(a.shape) == 1: temp_page_lock_p[:] = a else: temp_page_lock_p[:, :] = a assert numpy.allclose(a, temp_page_lock...
[ "def _copy_on_write(self):\n if (self._lazycopy):\n self._lazycopy = False\n pages = IntervalTree()\n lookup = dict()\n for p in self._lookup.values():\n n = p.copy()\n lookup[(p.begin, p.end)] = n\n pages.addi(n.begin,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of dummy notes.
def _get_dummy_notes(self, count=1): return [self._get_dummy_note(i) for i in range(count)]
[ "def list_all_notes(self) -> List[str]:\n if self.current_notebook is None:\n return [\"No currently opened notebook\"]\n names = []\n for name in self.notebooks[self.current_notebook].notes:\n names.append(name)\n if names:\n return names\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a single dummy note.
def _get_dummy_note(self, uid=0): nid = uuid4().hex return { "id": nid, "created": "2014-10-31T10:05:00.000000", "updated": "2014-10-31T10:50:00.101010", "user": "dummy-user-id", "usage_id": "dummy-usage-id-" + str(uid), "course_id"...
[ "def get_short_note(self):\n try:\n note_id = self.note_id\n return __notes__.get_short_note(note_id)\n except AttributeError:\n return ''", "def get_random_note(self) -> str:\n i = random.randint(0, len(self._config[\"notes\"]) - 1)\n return self._conf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test search with usage ids.
def test_search_usage_ids(self, usage_ids): url = self._get_url('api/v1/search') + usage_ids response = requests.get(url, params={ 'user': 'dummy-user-id', 'course_id': 'dummy-course-id' }) assert response.ok response = response.json() parsed = six...
[ "def test_search_query(self):\n pass", "def test_ids_post_search(self):\n self._request_valid(\n \"search\",\n protocol=\"POST\",\n post_data={\n \"collections\": [self.tested_product_type],\n \"ids\": [\"foo\", \"bar\"],\n },...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify the pagination information.
def _verify_pagination_info( self, response, total_notes, num_pages, notes_per_page, current_page, previous_page, next_page, start ): def get_page_value(url): """ Return page v...
[ "def test_true_validate_pagination_args():\n\n PaginationViewUtils.validate_pagination_args(PaginationDataRepository.get_valid_pagination().GET['page_num'],\n PaginationDataRepository.get_valid_pagination().GET['page_size'])", "def test_true_get_paginatio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return page value extracted from url.
def get_page_value(url): if url is None: return None parsed = six.moves.urllib.parse.urlparse(url) query_params = six.moves.urllib.parse.parse_qs(parsed.query) page = query_params["page"][0] return page if page is None else int(page)
[ "def parse_page_number(url):\n if '?' not in url:\n return 1\n params = url.split('?')[1].split('=')\n params = {k: v for k, v in zip(params[0::2], params[1::2])}\n if 'page' not in params:\n return 1\n return int(params['page'])", "def page_url(self, page_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test paginated response of notes api
def test_notes_collection(self): # Without user response = requests.get(self._get_url("api/v1/annotations")) assert response.status_code == 400 # Without any pagination parameters response = requests.get(self._get_url("api/v1/annotations"), params={"user": "dummy-user-id"}) ...
[ "def test_notes_collection_next_previous_with_one_page(self):\n response = requests.get(self._get_url(\"api/v1/annotations\"), params={\n \"user\": \"dummy-user-id\",\n \"page_size\": 10\n })\n\n assert response.ok\n self._verify_pagination_info(\n respon...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test next and previous urls of paginated response of notes api when number of pages are 1
def test_notes_collection_next_previous_with_one_page(self): response = requests.get(self._get_url("api/v1/annotations"), params={ "user": "dummy-user-id", "page_size": 10 }) assert response.ok self._verify_pagination_info( response=response.json(), ...
[ "def test_next_prev(self, client, blog_posts):\n article = blog_posts[\"article\"]\n feature = blog_posts[\"project_feature\"]\n announcement = blog_posts[\"announcement\"]\n # feature is oldest post; should have no prev and only next\n response = client.get(feature.get_url())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test paginated response of notes api when there's no note present
def test_notes_collection_when_no_notes(self): # Delete all notes self.test_cleanup() # Get default page response = requests.get(self._get_url("api/v1/annotations"), params={"user": "dummy-user-id"}) assert response.ok self._verify_pagination_info( response=...
[ "def test_notes_collection(self):\n\n # Without user\n response = requests.get(self._get_url(\"api/v1/annotations\"))\n assert response.status_code == 400\n\n # Without any pagination parameters\n response = requests.get(self._get_url(\"api/v1/annotations\"), params={\"user\": \"d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of notes from the stub EdxNotes service.
def _get_notes(self): notes = self.server.get_all_notes() assert len(notes) > 0, 'Notes are empty.' return notes
[ "def get_notes(self) -> TodoistNotesResponse:\n api = self._get_api()\n return TodoistNotesResponse(api.state['notes'])", "def get_all_notes(self):\n q=\"select * from note order by time desc;\"\n try:\n NoteDB.cursor.execute(q)\n notes=[]\n results=Not...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writting .tchanges file. .changes file file with special format that maintained by RMDupdaterAddin.
def write_changes_file(changes_string, filename): filename += '.changes' with open(filename, 'wb') as changes_file: changes_file.write(changes_string.encode('UTF-8'))
[ "def write_tchanges_file(tchanges_string, filename):\n filename += '.tchanges'\n with open(filename, 'wb') as tchanges_file:\n tchanges_file.write(tchanges_string.encode('UTF-8'))", "def log_diffs_to_file(latest_file_path, latest_file_ms, track_index, message_index):\n with open(os.path.join(os.pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writting .tchanges file. .tchanges file file with special format that maintained by RMDupdaterAddin.
def write_tchanges_file(tchanges_string, filename): filename += '.tchanges' with open(filename, 'wb') as tchanges_file: tchanges_file.write(tchanges_string.encode('UTF-8'))
[ "def write_changes_file(changes_string, filename):\n filename += '.changes'\n with open(filename, 'wb') as changes_file:\n changes_file.write(changes_string.encode('UTF-8'))", "def log_diffs_to_file(latest_file_path, latest_file_ms, track_index, message_index):\n with open(os.path.join(os.path.dir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for a pending or processing instance that matches the requested dates.
def pending_instance_exists(self, start_date, end_date): if self.instance is not None: # This is an update and does not need to check for existence. return queryset = self.queryset.filter( status__in=(DataExportRequest.PENDING, DataExportRequest.PROCESSING), ...
[ "def _check_date(self, cr, uid, ids, context=None):\n for act in self.browse(cr, uid, ids, context):\n if act.start_date and act.expiration_date:\n if self.get_date(act.start_date) > self.get_date(act.expiration_date):\n raise osv.except_osv(_(''), _(\"Start Date ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function places the students in their corresponding buildings, floor and rooms. It uses the hash functions in order to determine where the students should be placed according to the value of the corresponding hash.
def placeStudents(list): buildings = createBuilding() for line in list: name, furniture = line.split() floors = buildings.get(name) rooms = floors.get(name) room = rooms.get(name) if room.AddtoRoom(name, furniture): print("student", name, "already pr...
[ "def map_the_home(hlst):\n\n hdct = {}\n for e in hlst:\n if e.room in hdct.keys():\n hdct[e.room].append(e)\n else:\n hdct[e.room] = [e]\n return hdct", "def student_clusters_in_classes(self, students, class_rooms):\n # Closure function to verify if the student...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The main function reads in a file, converts it to a list and then proceeds to place the students.
def main(): textfile = input("input filename: ") list = readStudents(textfile) placeStudents(list)
[ "def addStudentsFromFile(self, filename):\n filereader=open(filename)\n lines=filereader.readlines()\n for line in lines[5:]:\n line=line.strip('\\n')\n rollno,name,*hwk=line.split(':')\n #Convert homework into numbers\n marks=[eval(mark) for mark in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This fuction checks valid ASIN.
def check_ASIN_validity(self,X): if self.check_ASIN == True: col = X['ASIN'].copy() uniq_col = pd.Series(col.unique()) mask = (uniq_col.str.match(r'\b[B\d][\dA-Z]{9}\b')) & (uniq_col.str.len()==10) inval_ASIN = uniq_col[~mask] print(inval_ASIN) ...
[ "def check_ASIN_validity(self,X,y=None):\n \n \n if self.check_ASIN == True:\n col = X['ASIN'].copy()\n uniq_col = pd.Series(col.unique())\n mask = (uniq_col.str.match(r'\\b[B\\d][\\dA-Z]{9}\\b')) & (uniq_col.str.len()==10)\n inval_ASIN = uniq_col[~ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This fuction checks valid ASIN.
def check_ASIN_validity(self,X,y=None): if self.check_ASIN == True: col = X['ASIN'].copy() uniq_col = pd.Series(col.unique()) mask = (uniq_col.str.match(r'\b[B\d][\dA-Z]{9}\b')) & (uniq_col.str.len()==10) inval_ASIN = uniq_col[~mask] ...
[ "def check_ASIN_validity(self,X):\n \n if self.check_ASIN == True:\n col = X['ASIN'].copy()\n uniq_col = pd.Series(col.unique())\n mask = (uniq_col.str.match(r'\\b[B\\d][\\dA-Z]{9}\\b')) & (uniq_col.str.len()==10)\n inval_ASIN = uniq_col[~mask]\n pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a User object from a player file.
def get_player(self, name): return User(name)
[ "def load_user():\n assert has_saved_user()\n with open(_user_path(), 'r') as f:\n json_string = f.read()\n return User.from_json(json_string)", "def from_file(file_path: str) -> \"UserData\":\n file_name = path.basename(file_path)\n\n if not file_name.startswith(\"user_\"):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert targets by image to targets by feature level. [target_img0, target_img1] > [target_level0, target_level1, ...]
def images_to_levels(target, num_level_anchors): target = torch.stack(target, 0) level_targets = [] start = 0 for n in num_level_anchors: end = start + n level_targets.append(target[:, start:end]) start = end return level_targets
[ "def images_to_levels(target, num_levels):\n target = stack_boxes(target, 0)\n level_targets = []\n start = 0\n for n in num_levels:\n end = start + n\n # level_targets.append(target[:, start:end].squeeze(0))\n level_targets.append(target[:, start:end])\n start = end\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dynamically create a Mock sub class that implements the given Zope interface class.
def create_interface_mock(interface_class): # the init method, automatically specifying the interface methods def init(self, *args, **kwargs): MagicMock.__init__(self, spec=interface_class.names(), *args, **kwargs) # we derive the sub class name from the interface name na...
[ "def test_set_interface():\n from .test_interface_base import Concrete\n\n e = Experiment()\n inst = Concrete()\n e.interface = inst\n assert_equal(e.interface, inst)", "def wrap_interface(self):\n api = TestAPI()\n module = Bar()\n wrapped = api.wrap_interface(module.foo)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine default machine folder. Return str.
def get_machine_folder(): properties = subprocess.check_output(['VBoxManage', 'list', 'systemproperties']) prop_name = "Default machine folder:" skip = len(prop_name) machine_folder = '' for line in properties.decode().split('\n'): if prop_name in li...
[ "def default_machine_folder(self):\n ret = self._get_attr(\"defaultMachineFolder\")\n return ret", "def _get_default_path(self):\n #return os.path.join(cfg.DATA_DIR, 'SNUBH_BUS')\n return cfg.DATA_DIR", "def get_default_path(self, default_path=''):\n return default_path if def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for VM using VBoxManage. If exist return True. Else return False
def _checkreg(self): retval = True try: with open('/dev/null') as devnull: subprocess.check_call(['VBoxManage', 'showvminfo', self.name], stdout=devnull, stderr=devnull ...
[ "def is_in_virtualbox():\n if not isfile(__VIRT_WHAT) or not access(__VIRT_WHAT, X_OK):\n raise IOError(\"virt-what not available\")\n try:\n return subprocess.check_output([\"sudo\", \"-n\", __VIRT_WHAT]).split('\\n')[0:2] == __VIRT_WHAT_VIRTUALBOX_WITH_KVM\n except subprocess.CalledProcessError as e:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for VM files. Return True if exists. Else False.
def _checkfiles(self, build=None): mf = get_machine_folder() inroot = os.path.exists(os.path.join(mf, self.name)) if build == 'stable': group = paths.vm_group_stable else: group = paths.vm_group insu = os.path.exists(os.path.join(mf, group, self.name)) ...
[ "def checkvm(self):\n if self._checkreg() or self._checkfiles():\n err = \"{} already exist!\".format(self.name)\n raise VirtualMachineExistsError(err)\n return 0", "def check_files_in_directory(self, path):\n if os.path.exists(path):\n return os.path.isfile(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raise VirtualMachineError if such VM exists. Else return 0
def checkvm(self): if self._checkreg() or self._checkfiles(): err = "{} already exist!".format(self.name) raise VirtualMachineExistsError(err) return 0
[ "def does_vm_exist_on_provider(self):\n return self.provider_crud.get_mgmt_system().does_vm_exist(self.name)", "def does_vm_exist_in_cfme(self):\n try:\n self.find_quadicon()\n return True\n except VmNotFound:\n return False", "def test_get_one_inexistent_vi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import VM and group into paths.vm_group.
def importvm(self, ova): assert os.path.exists(ova), "{} not found" % ova subprocess.call(['VBoxManage', 'import', ova, '--options', 'keepallmacs']) time.sleep(10) grouped = self._groupvm() sfolders = self._sharedfolders() return grouped, sfolders
[ "def just_import(ova):\n name = os.path.split(ova)[1].split('.')[0]\n v_machine = VirtualMachine(name)\n # This must throw exception if such VM already exists.\n try:\n v_machine.checkvm()\n except VirtualMachineExistsError:\n print(\"WARNING: %s already exists. Skipping...\" % name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build virtual machine. Remove existing if needed.
def build_vm(vmname, build=None): if build == 'stable': v_machine = VirtualMachine(vmname) else: v_machine = VirtualMachine(vmname) try: v_machine.checkvm() except VirtualMachineExistsError: v_machine.removevm() if build == 'stable': return v_machine.buildvm('...
[ "def clean_build():\r\n env.clean_build = True", "def __create_virtual_machine(self):\n vm_name = 'arista-cvx'\n logger.info('Launching the {} VM'.format(vm_name))\n\n arista_image_path = self.framework.model.resources.fetch(\n 'arista-image')\n\n # Officially Arista CVX ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import VM and group it. Return str. Import VM from specified ova and return VM name. If VM with such name already exists raise VirtualMachineExistsError.
def just_import(ova): name = os.path.split(ova)[1].split('.')[0] v_machine = VirtualMachine(name) # This must throw exception if such VM already exists. try: v_machine.checkvm() except VirtualMachineExistsError: print("WARNING: %s already exists. Skipping..." % name) else: ...
[ "def force_import(ova):\n name = os.path.split(ova)[1].split('.')[0]\n v_machine = VirtualMachine(name)\n try:\n v_machine.checkvm()\n except VirtualMachineExistsError:\n v_machine.removevm()\n v_machine.importvm(ova)\n return name", "def importvm(self, ova):\n assert os.pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import and group VM. Remove existing if needed.
def force_import(ova): name = os.path.split(ova)[1].split('.')[0] v_machine = VirtualMachine(name) try: v_machine.checkvm() except VirtualMachineExistsError: v_machine.removevm() v_machine.importvm(ova) return name
[ "def importvm(self, ova):\n assert os.path.exists(ova), \"{} not found\" % ova\n subprocess.call(['VBoxManage', 'import', ova,\n '--options', 'keepallmacs'])\n time.sleep(10)\n grouped = self._groupvm()\n sfolders = self._sharedfolders()\n return grou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build VMs from self.vmlist.
def build(self, bld=None): vm_number = len(self.vmlist) if vm_number == 1: if bld == 'stable': ova = build_vm(self.vmlist[0], 'stable') self.results.append(ova) else: ova = build_vm(self.vmlist[0]) self.results.appen...
[ "def create_vms(self):\n\n\t\tfor vmx_path in self.vmx_files:\n\t\t\t#vm = self.create_vm(\"/Users/alex/Documents/Virtual Machines.localized/macOS 10.12.vmwarevm/macOS 10.12.vmx\")\n\t\t\tvm = self.create_vm(vmx_path)\n\t\t\tself.start_vm(vm)\n\t\t\tself.virtual_machines[str(vm.uuid)] = vm\n\n\t\ttime.sleep(5)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove img. Return img if removed. Else None.
def _remove_existing(img): if os.path.exists(img): os.unlink(img) return img
[ "def remove_image(self: E) -> E:\n try:\n del self._image\n except AttributeError:\n pass\n\n return self", "def delete_image_tag(self, img, tag):\r\n return img.delete_tag(tag)", "def remove_profile_image(self):\n self.wait_for_field('image')\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare MIME message. Return email.mime.MIMEText.
def _prepare_message(msg): msg_mime = MIMEText(msg, 'text', 'utf-8') msg_mime['From'] = Header(infomail.fromaddr, charset='utf-8') msg_mime['To'] = Header(', '.join(infomail.toaddrs), charset='utf-8') msg_mime['Subject'] = Header("VirtualBox images built",...
[ "def CreateMessage(sender, to, subject, message_text):\n #message = MIMEText(message_text)\n message = MIMEText(message_text,'html')\n message['to'] = to\n message['from'] = sender\n message['subject'] = subject\n return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}", "def get_email_message...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send info mail using data from imfomail.py Argument upload_dir required for making download URL for recipients. Prepare and send message through smtplib.SMTP
def mail(self, upload_dir): url = infomail.download_url.format(os.path.split(upload_dir)[1]) mymessage = infomail.text_message.format(url) mymessage = self._prepare_message(mymessage) errpref = "SMTP Problem:" smtpconn = smtplib.SMTP(infomail.smtphost, infomail.smtpport) ...
[ "def send_email(sender, to, cc, subject, body, body_format, file_path, file_list):\n\n msg = MIMEMultipart()\n msg['From'] = sender\n msg['To'] = to\n msg['Cc'] = cc\n msg['Subject'] = subject\n text = body\n\n part1 = MIMEText(text, body_format)\n msg.attach(part1)\n\n ## ATTACHMENT PART...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import virtual machines from self.vmlist.
def vmimport(self, func=just_import): ovas = len(self.vmlist) if ovas == 1: vmname = func(self.vmlist[0]) self.results.append(vmname) elif ovas <= self.threads: self._import_pool(ovas, self.vmlist, func) else: tmplist = self.vmlist ...
[ "def importvm(self, ova):\n assert os.path.exists(ova), \"{} not found\" % ova\n subprocess.call(['VBoxManage', 'import', ova,\n '--options', 'keepallmacs'])\n time.sleep(10)\n grouped = self._groupvm()\n sfolders = self._sharedfolders()\n return grou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Look into Packer templates dir and return template's list.
def _discover_templates(): vms = [] for file in os.listdir(paths.packer_templates): json = os.path.join(paths.packer_templates, file, file + '.json') if os.path.exists(json): vms.append(file) return vms
[ "def list_templates():\n module_path = get_module_path()\n\n templates_path = os.path.join(module_path, TEMPLATES)\n result = []\n\n for root, subdirs, files in os.walk(templates_path):\n for fn in files:\n if fn == '_template':\n prefix_path = os.path.relpath(root, temp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build and upload VMs through Builder class methods Build from given as arguments list of VMs. If no arguments given then call self._discover to determine the list of VMs from existing Packer templates.
def _build(self): if self.args.VM_NAME: bld = Builder(self.args.VM_NAME) else: bld = Builder(self._discover_templates()) if self.args.stable: bld.build('stable') result = bld.upload(build='stable') else: bld.build() ...
[ "def create_vms(self):\n\n\t\tfor vmx_path in self.vmx_files:\n\t\t\t#vm = self.create_vm(\"/Users/alex/Documents/Virtual Machines.localized/macOS 10.12.vmwarevm/macOS 10.12.vmx\")\n\t\t\tvm = self.create_vm(vmx_path)\n\t\t\tself.start_vm(vm)\n\t\t\tself.virtual_machines[str(vm.uuid)] = vm\n\n\t\ttime.sleep(5)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve list of .ova from dir. Return list.
def _ova_from_dir(directory): res = [] for file in os.listdir(directory): if file.endswith('.ova'): res.append(os.path.join(directory, file)) return res
[ "def _prepare_ovas(self):\n ovalist = []\n for name in self.args.NAME:\n if name.endswith('.ova'):\n ovalist.append(name)\n elif os.path.isdir(name):\n ovalist.extend(self._ova_from_dir(name))\n else:\n print(\"%s doesn't lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get list of .ova from self.args. Return list.
def _prepare_ovas(self): ovalist = [] for name in self.args.NAME: if name.endswith('.ova'): ovalist.append(name) elif os.path.isdir(name): ovalist.extend(self._ova_from_dir(name)) else: print("%s doesn't looks like direc...
[ "def all_args(self) -> List[Namespace]:\n return (\n ([self.peas_args['head']] if self.peas_args['head'] else [])\n + ([self.peas_args['tail']] if self.peas_args['tail'] else [])\n + self.peas_args['peas']\n )", "def argv(self):\n optlist = []\n for n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get maximum speed of vehicle (superclass)
def speed_max(self): return self._speed_max
[ "def max_speed(self):\n raise NotImplementedError", "def max_speed(self, value):\n\n pass", "def getMaxSpeed(self):\n return getHandle().maxSpeed", "def max_speed(self):\n out = self.__fcobj._execute_transceiver_cmd()\n if self.__swobj.is_connection_type_ssh():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get maximum acceleration of vehicle (superclass)
def accel_max(self): return self._accel_max
[ "def max_velocity(self):\n return 10 * self.velocity_scale", "def getAccelerationMax(self, index):\r\n accelMax = c_double()\r\n \r\n try:\r\n result = PhidgetLibrary.getDll().CPhidgetMotorControl_getAccelerationMax(self.handle, c_int(index), byref(accelMax))\r\n exce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Vehicle maximum path curvature
def curvature_max(self): return 1.0 / self.radius_min
[ "def max_curvature(P0, P1, P2, P3):\n t = np.linspace(0, 1, 300)\n curv = curvature_bezier(P0, P1, P2, P3)(t)\n max_curv = np.max(np.abs(curv.flatten()))\n return max_curv", "def func_curvature(self):\r\n return u.Curvature.CONCAVE", "def func_curvature(self):\r\n return u.Curvature.CO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates a new location which is in the middle of two points.
def get_middle_point(l1, l2): row = (l1.row + l2.row) / 2 column = (l1.column + l2.column) / 2 return Location(row, column)
[ "def getMiddlePoint(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n return (round(float((x1 + x2)/2), 2), round(float((y1 + y2)/2), 2))", "def mid(self, other):\n sx, sy = self.xy()\n ox, oy = other.xy()\n return Point((sx+ox)/2, (sy+oy)/2)", "def mid_point(loc1, loc2):\n geod = Geodesic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the offset between two points.
def calculate_offset(location_1, location_2): row_offset = abs(location_1.row - location_2.row) column_offset = abs(location_1.column - location_2.column) return Location(row_offset, column_offset)
[ "def y_distance(p1: sdl2.SDL_Point, p2: sdl2.SDL_Point) -> int:\n\n return p2.y - p1.y", "def calculate_offset_pos_two_side_one_point_locked(b_struct, v_key, pt_1, pt_2, v1, v2, d_o_1, d_o_2):\n\n pt_1_new = add_vectors(pt_1, scale_vector(v1, -1.*d_o_1))\n pt_2_new = add_vectors(pt_2, scale_vector(v2, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for the lists in the board. If they do not exists create them
def __get_and_create_lists(self, board, lists_names): lists = [] names = [x.lower() for x in lists_names] lists_names = list(lists_names) # make a copy # search for the lists for lst in board.list_lists(): name = lst.name.lower() if name in names: ...
[ "def _fetch_lists(self):\n # List of the board\n self.lists = self.board.all_lists()\n\n # Compute list orders\n i = 1\n for list_ in self.lists:\n list_.order = i\n i += 1\n\n # List dict of the board used to avoid fetc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a subscription given a subscription_id. This does not return a result
def find(subscription_id): try: response = Http().get("/subscriptions/" + subscription_id) return Subscription(response["subscription"]) except NotFoundError: raise NotFoundError("subscription with id " + subscription_id + " not found")
[ "def get_subscription(self, id: UUID) -> Optional[Subscription]:\n subscription = select([subscriptions]).where(subscriptions.c.id == id).execute().first()\n return subscription", "def get_one(self, subscription_id):\n\n subscription = subscription_api.subscription_get(subscription_id)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method calls the method in the CommentDAO responsible for retrieving all the comments from the database. The array of comments is then properly formatted and then converted into a json which is then returned.
def getAllComment(self): result = CommentDAO().getAllComment() mapped_result = self.buildMethod(result) return jsonify(Comment=mapped_result)
[ "def get_comment_list(self, response):\n comment_list = CommentList()\n contact_comments = response['contact_comments']\n for value in contact_comments:\n contact_comment = Comment() \n contact_comment.set_comment_id(value['comment_id'])\n contact_comment.set_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method calls the method in CommentDAO responsible for getting a comments by a parameter id. If no comments with a matching id is found the method returns a json containing an error message. If a comment with a matching id is found then its properly formatted and returned as a json.
def getCommentByID(self, id): result = CommentDAO().getCommentById(id) mapped_result = [] if result is None: return jsonify(Error="NOT FOUND"), 404 else: mapped_result.append(self.build_comment(result)) return jsonify(Comment=mapped_result)
[ "def get(self, comment_id):\n\n db = get_db()\n if db.get_all_accounts() == []:\n response = jsonify([])\n else:\n log_in()\n if comment_id is None:\n response = jsonify(db.get_all_rows('comment'))\n\n return response\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method calls the method in CommentDAO responsible for getting a comments by a parameter date. If no comments with a matching date is found the method returns a json containing an error message. If a comment with a matching id is found then its properly formatted and returned as a json.
def getCommentByDate(self, json): result = CommentDAO().getCommentByDate(json["comment_date"]) if result is None: return jsonify(Error="NOT FOUND"), 404 else: mapped_result = self.buildMethod(result) return jsonify(Comment=mapped_result)
[ "def getCommentByID(self, id):\n result = CommentDAO().getCommentById(id)\n mapped_result = []\n if result is None:\n return jsonify(Error=\"NOT FOUND\"), 404\n else:\n mapped_result.append(self.build_comment(result))\n return jsonify(Comment=mapped_result)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize a link with two nodes, a name, a protocol and a risk value
def __init__(self, node1, node2, name, protocol, risk = 5): self._n1 = node1 # private variable storing the first node which is of type Node self._n2 = node2 # private variable storing the second node which is of type Node self._name = name # private variable storing the name of the link ...
[ "def make_link(self, node0, node1):\r\n Link(node0, node1)", "def __init__(self, from_bath, to_bath, label):\n super(Link, self).__init__(label)\n\n # can only attach Link to Bath\n assert isinstance(from_bath, Bath)\n assert isinstance(to_bath, Bath)\n\n self.from_bath =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a tuple of the two nodes assigned to the link
def getNodes(self): return (self._n1, self._n2)
[ "def link2node(self):\n self.link2nodeid = np.zeros((self.linknum, 2), dtype = int)\n \n for i in range(self.linknum):\n self.link2nodeid[i, 0] = self.internet1net2.edgelist[i][\"start node\"]\n self.link2nodeid[i, 1] = self.internet1net2.edgelist[i][\"end node\"]", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the protocol of the link to newProtocol
def setProtocol(self, newProtocol): self._proto = newProtocol
[ "def setProtocol( self, protocol ):\n\t\tself.protocol = protocol", "def set_protocol(self, protocol):\n self.protocol = protocol", "def setProtocol(self, protocol):\n self[SipViaHeader.PARAM_PROTOCOL] = protocol", "def protocol(ctx: Context, protocol_public_id):\n upgrade_item(ctx, \"protoco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the risk value of the link
def getRisk(self): return self._risk
[ "def get_risk(self):\n return str(Decimal(str(self.gui.spn_risk.textFromValue(\n self.gui.spn_risk.value())))\n )", "def get_risk(self, inst):\r\n return self.risk.get_risk(inst)", "def risk(self, dataset, individual_record):\n number_of_visits = len(individual_record.visi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add the value to the additional dictionary with the key name
def addAdditional(self, name, value): self._additional[name] = value
[ "def add(self,key,value):\n\t\tself.form_dict[key] = value", "def dict_add_dict_to(d, dict_to_add): # How to add the values of one dictionary to another?\n for key, value in dict_to_add.items():\n if key not in d:\n d[key] = value\n else:\n d[key] += value", "def add_dict...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the value from additional at the key name
def getAdditional(self, name): return self._additional[name]
[ "def _GetValueFromGroup(self, structure, name, key_name):\n structure_value = self._GetValueFromStructure(structure, name)\n return structure_value.get(key_name)", "def __getitem__(self, key):\n query = select([self.store.c.value]).where(self.store.c.key == key)\n result = self.conn.execute(qu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove the value from additional at the key name
def removeAdditional(self, name): del self._additional[name]
[ "def remove(key: str, value: object, catname: str=''):", "def remove_item(self, key, value):\n ...", "def remove_property(self, key):", "def _remove_special(cls, data):\n for key in list(data.keys()):\n if key.startswith(\"_\") or key == \"name\":\n del data[key]", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get slope of each edge of the polygon
def get_slopes(points) -> list: # Get no. of points points_length = len(points) i = 0 # Define an empty list to store slopes of all edges slopes = [] while i < points_length: # Get indices of the two points of the edge if i != points_length - 1: j = i + 1 els...
[ "def _get_slope(self):\n return self._slope", "def calc_slope(self):\n sigma_x = np.std(self.x)\n sigma_y = np.std(self.y)\n if sigma_x == 0 or sigma_y == 0:\n self.slope = 0\n else:\n r = np.corrcoef(x=self.x, y=self.y)[1, 0]\n self.slope = r * ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the circle obstacle on the mapimage
def draw_circle(self) -> None: # Define parameters of circular obstacles circle = [25, (225, 50)] # Define center of the circle a = circle[1][0] b = circle[1][1] # Define radius of the circle r = circle[0] # Draw the circle for y in range(self.heig...
[ "def _draw_map(self):\n\n for obstacle in self._obstacles:\n obstacle.draw(self._axes)", "def draw(self, image, px, py, angle, color, map_resolution, alpha=1.0, draw_steering_details=True):", "def _draw_circle(self):\n pygame.draw.circle(self.screen, GREY,\n (B...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the convex polygon, rectangle and rhombus on the mapimage
def draw_polygons(self) -> None: # Coordinates of the convex polygon coord_polygon = np.array([(20, self.height - 120), (25, self.height - 185), (75, self.height - 185), (100, self.height - 150), ...
[ "def draw(self, image, px, py, angle, color, map_resolution, alpha=1.0, draw_steering_details=True):", "def fillConvexPoly(img, points, color, lineType=..., shift=...) -> img:\n ...", "def draw_poly(self, param): \n\n poly = json.loads( param['poly'] )\n zoom = param['zoom']\n\n wid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get eroded image to check for obstacles considering the robot radius and clearance
def erode_image(self) -> bool: # Get map with obstacles eroded_img = self.world_img.copy() eroded_img = cv2.cvtColor(eroded_img, cv2.COLOR_BGR2GRAY) # Erode map image for rigid robot if self.thresh: kernel_size = (self.thresh * 2) + 1 erode_kernel = np.one...
[ "def get_image(self):\n im = np.ones((10*self.p + 1, 10*self.q + 1, 3))\n for i in range(self.p):\n for j in range(self.q):\n if self.maze_map[i][j].walls['top']:\n im[10*i, 10*j:(10*(j + 1) + 1), :] = 0\n if self.maze_map[i][j].walls['left']...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove check image from file system
def remove_check_image(self) -> bool: os.remove(self.CHECK_IMG_LOC) if os.path.exists(self.CHECK_IMG_LOC): return False return True
[ "def _remove_existing(img):\n if os.path.exists(img):\n os.unlink(img)\n return img", "def clean(image_name):\n logging.info('Cleaning image \\'' + image_name + '\\' files')", "def removeImage(self, fileName, validate=None): # XXX remove unused 'validate'?\n if self._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the graph with all the champions, add edges to connect people of the same class.
def _add_edges(self): for class_ in self.champions_in_class.keys(): # For each class for champ in self.champions_in_class[class_]: # For each Champ of that class for champ_of_same_class in self.champions_in_class[class_]: # Loop to all the other champions of the same class. ...
[ "def connect_all(self):\n # All classrooms are disconnected nodes\n for classroom in self.nodes.classrooms:\n a, b = funcs.naive_knn(classroom, self.nodes.hallways, k=2)\n d = funcs.project(a, b, classroom)\n\n self.add_edge(a, d, weight=funcs.euclidean_dist_nodes(a, d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all champs for each champ class in vert.champ
def find_all_champs_same_class_as(self, vert): start = self.getVertex(vert) # Root checked_classes = set() array_of_champs = {} # { 'yordle': set('kennen', ...), ...} # print("All of {}'s classes: {}".format(vert, start.champ.classes)) print("\n{}'s classes are: {}\n".format(ve...
[ "def get_champions_from_site(role):\n result = []\n # OP.GG classifies champions by tiers.\n appropriate_tiers = []\n mode = input(\"\\nHow do you feel like playing?\\n\" +\n \"1) Tryhard\\n\" +\n \"2) Not too troll\\n\" +\n \"3) Feed my ass off\\n\" +\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an edge to the graph and corresponding vertices to the sets of sources/stocks
def add_edge(self, v_from, v_to): self.v_sources.add(v_from) self.v_stocks.add(v_to) if v_from in self.edges: self.edges[v_from].append(v_to) else: self.edges[v_from] = [v_to,]
[ "def add_edge(source, target, label):\n if target not in elements_set: return\n if simple:\n if source != target:\n result.add_edge([source, target])\n else:\n result.add_edge([source, target, label])", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a vertex to the set of source vertices (suppose that a distinct vertex is a source)
def add_vertex(self, v): self.v_sources.add(v)
[ "def append_vertex(self, vertex):", "def add_vertex(self, v):\n pass", "def add_vertex(self, vertex):\r\n self.vertices.append(vertex)", "def add_vertex(self, id, vertex):\n \n # Check if vertex with given id already exists.\n if id in self.vertices:\n return\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an index of the first letter that is different in two strings, 1 if not found
def first_uncommon_letter(str1, str2): i = 0 min_len = min(len(str1), len(str2)) while str1[i] == str2[i]: i += 1 if i == min_len: return -1 return i
[ "def differs_by_one_char_same_len(str1, str2):\n if len(str1) != len(str2):\n raise ValueError(\"Strings aren't the same length\")\n\n one_difference_found = False\n found_index = 0\n for i, (chr1, chr2) in enumerate(zip(str1, str2)):\n if chr1 != chr2:\n if one_difference_found...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }