query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Check for satisfied degrees of freedom before running initialization.
def precheck(self, model: Block): dof = degrees_of_freedom(model) self._update_summary(model, "DoF", dof) if not dof == 0: self._update_summary(model, "status", InitializationStatus.DoF) raise InitializationError( f"Degrees of freedom for {model.name} were...
[ "def _check_initialized(self):\n check_is_fitted(self)", "def _check_initialized(self):\n check_is_fitted(self, 'estimators_')", "def _check_solver_is_ready(self) -> None:\n if not self.is_ready or self.H is None:\n msg = \"User must first run {type(self).__name__}.setup() before...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restore model state to that stored in self.initial_state.
def restore_model_state(self, model: Block): if model in self.initial_state: from_json(model, sd=self.initial_state[model], wts=StoreState) else: self._update_summary(model, "status", InitializationStatus.Error) raise ValueError("No initial state stored.")
[ "def reset_states(self):\n self.model.reset_states()", "def reset_model(self):\n pass", "def reset(self):\r\n self.model.load_state_dict(self.model_state)\r\n self.model.to(self.model_device)\r\n self.optimizer.load_state_dict(self.optimizer_state)", "def restore_state(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the model has been converged after initialization. If a results_obj is provided, this will be checked using check_optimal_termination, otherwise this will walk all constraints in the model and check that they are within tolerance (set via the Initializer constraint_tolerance config argument).
def postcheck( self, model: Block, results_obj: dict = None, exclude_unused_vars: bool = False ): if results_obj is not None: self._update_summary( model, "solver_status", check_optimal_termination(results_obj) ) if not self.summary[model]["solver...
[ "def check_termination(self):\r\n \r\n # First check if we are doing termination based on running time\r\n if (self.options.time_limit):\r\n self.time = time.clock - self.time_start\r\n if (self.time >= self.options.maxtime):\r\n self.term_reason = 'Exceeded...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize plugin model. This activates the Block and then calls self.initialize(plugin). Derived Initializers should overload this as required.
def plugin_initialize( self, plugin: Block, initial_guesses: dict = None, json_file: str = None ): plugin.activate() return self.initialize( plugin, initial_guesses=initial_guesses, json_file=json_file )
[ "def __init__(self, plugin):\n self.plugin = plugin", "def init_plugin(plugin_type, lang=\"en\", **plugin_data):\n placeholder = Placeholder.objects.create(slot=\"test\")\n return add_plugin(placeholder, plugin_type, lang, **plugin_data)", "def _make_block(self, model):\n # TODO Make base cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Final clean up of plugins after initialization. This method does nothing. Derived Initializers should overload this as required.
def plugin_finalize(self, plugin):
[ "def finalize(self):\n self.__doing('finalize')\n self.__do_if_not_done('load_plugins')\n\n if self.env.env_confdir is not None:\n if self.env.env_confdir == self.env.confdir:\n logger.info(\n \"IPA_CONFDIR env sets confdir to '%s'.\", self.env.confd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal method to iterate through items in initial_guesses and set value if Var and not fixed.
def _load_values_from_dict(self, model, initial_guesses, exception_on_fixed=True): for c, v in initial_guesses.items(): component = model.find_component(c) if component is None: raise ValueError(f"Could not find a component with name {c}.") elif not isinstanc...
[ "def setup_initial_guess(self):\n\n # Setting the parameters\n\n if 'initial_guess' in self.data:\n\n for name, values in self.data['initial_guess'].items():\n\n # Get Shape of Domain\n expected_shape = []\n for domain in getattr(self, name).Doma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define an Initializer for a give submodel or type of submodel.
def add_submodel_initializer(self, submodel: Block, initializer: InitializerBase): self.submodel_initializers[submodel] = initializer
[ "def get_submodel_initializer(self, submodel: Block):\n initializer = None\n\n if submodel in self.submodel_initializers:\n # First look for specific model instance\n initializer = self.submodel_initializers[submodel]\n elif type(submodel) in self.submodel_initializers:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lookup Initializer object to use for specified submodel.
def get_submodel_initializer(self, submodel: Block): initializer = None if submodel in self.submodel_initializers: # First look for specific model instance initializer = self.submodel_initializers[submodel] elif type(submodel) in self.submodel_initializers: #...
[ "def add_submodel_initializer(self, submodel: Block, initializer: InitializerBase):\n self.submodel_initializers[submodel] = initializer", "def initialize_submodels(\n self, model, plugin_initializer_args, sub_initializers, **kwargs\n ):\n results = None\n\n for sm in model.initiali...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare plugins for initialization. Iterates through model.initialization_order and collects Initializer objects for each plugin and calls plugin_prepare for each.
def prepare_plugins(self, model, plugin_initializer_args): sub_initializers = {} plugin_initializer_args = dict(plugin_initializer_args) for sm in model.initialization_order: if sm is not model: # Get initializers for plug-ins sub_initializers[sm] = se...
[ "def initialize_submodels(\n self, model, plugin_initializer_args, sub_initializers, **kwargs\n ):\n results = None\n\n for sm in model.initialization_order:\n if sm is model:\n results = self.initialize_main_model(model, **kwargs)\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize submodels in order defined by model.initialization_order. For the main model, self.initialize_main_model is called. For plugins, plugin_initialize is called from the associated Initializer.
def initialize_submodels( self, model, plugin_initializer_args, sub_initializers, **kwargs ): results = None for sm in model.initialization_order: if sm is model: results = self.initialize_main_model(model, **kwargs) else: sub_initiali...
[ "def prepare_plugins(self, model, plugin_initializer_args):\n sub_initializers = {}\n plugin_initializer_args = dict(plugin_initializer_args)\n for sm in model.initialization_order:\n if sm is not model:\n # Get initializers for plug-ins\n sub_initialize...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call solver on full model. If no plugins are present, just return results from previous solve step (main model).
def solve_full_model(self, model, results): # Check to see if there are any plug-ins if len(model.initialization_order) > 1: # Solve model with plugins solve_log = idaeslog.getSolveLogger( model.name, self.get_output_level(), tag="unit" ) w...
[ "def __solve(self)-> None:\n pyo.TransformationFactory(\"contrib.detect_fixed_vars\").apply_to(self.model) # type: ignore\n pyo.TransformationFactory(\"contrib.deactivate_trivial_constraints\").apply_to(self.model) # type: ignore\n\n # initialise the solver object\n self._logger.debug(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Postinitialization cleanup of plugins. Iterates through model.initialization_order in reverse and calls plugin_cleanup method from the associated Initializer for each plugin.
def cleanup(self, model, plugin_initializer_args, sub_initializers): for sm in reversed(model.initialization_order): if sm is not model: sub_initializers[sm].plugin_finalize(sm, **plugin_initializer_args[sm])
[ "def teardown(self):\n rc = self.rc\n try:\n for plugin in self.plugins:\n plugin.teardown(rc)\n except Exception as e:\n self.exit(e)", "def finalize(self):\n self.__doing('finalize')\n self.__do_if_not_done('load_plugins')\n\n if sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempt to login the user. If the login succeeds, self.user is set to an instance of Presenter or Student depending on the credentials of the user, and the onSuccess callback is called. If the login fails, self.user remains None and onFailure is called.
def Login(self, username, password, onSuccess, onFailure): pass
[ "def login(self):\n input_username = self.username_var.get()\n input_password = self.password_entry.get()\n\n db = self.pager_frame.master_root.db # gets database obj from main root of application\n user_type = ('Staff', 'Student')[int(self.is_student)]\n logging.debug(f'A {user_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the Layer Manager's model.
def SetUpLayerManager(self): pass
[ "def _init_layers(self):\n self._init_predictor()\n if self.use_edge_fusion:\n self._init_edge_module()", "def _init_layers(self) -> None:\n self._init_reg_convs()\n self._init_predictor()", "def initialize(self):\n for layer in self._layers:\n layer.init...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Not for public use; copies `data` to `NAME_STACK_DATA`
def absorb_name_stack_data(self, data: Deque): if data: return evolve(self, NAME_STACK_DATA=[*data]) return self
[ "def push(self, data):\n self.STACK.appendleft(data)\n self.SP = self.STACK[0]", "def push(self, data):\n\n # OVERVIEW\n # Since our stack is simply a Python list, we can take advantage of\n # Python built-in methods to add the given data to our Stack, making\n # this ope...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For a given RNA, get the p values for all proteins by negative binomial.
def pval_at_rna_by_nbinom( self, pos_dict_of_counts: Mapping[str, List], neg_vals_at_rna: np.array, gene_and_type, log_if_values_above=1E9, log_values=False, which='per_read', verbose=False): if len(neg_vals_at_rna) == 0: return None log_scale_high_value = (...
[ "def negativeBinomial(self, r, p):\r\n X = 0\r\n failures = 0\r\n while failures < r:\r\n U = next(self.RNG())\r\n if U <= p: # Success Case\r\n X += 1\r\n else: # Failure Case\r\n failures += ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to convert between doi, pmid (and PMC) either using prespecified mappings or using the PubMed API For reproducibility reasons, the script loads by default (load_pmid parameter) a saved doi > pmid mapping from a csv specified in load_loc, i.e. does not go through PubMed to do the conversions. If that is desired...
def convert_id(df, id_in, id_out, chunklength, timer, load_loc, save_loc=None, load_pmid=True, mail_ad='placeholder', tool='id_converter'): import time import requests import pandas as pd import numpy as np pubmedURL = 'https://www.ncbi.nlm.nih.gov/pmc/utils/idconv/v1.0/?tool=' + to...
[ "def test_id_convert():\n from vdm.pubmed import id_convert\n\n #Should return match\n meta = id_convert('10.1371/journal.pmed.0040305')\n assert(\n meta['pmid'] == '18001145'\n )\n\n #DOI identified but should not match\n meta = id_convert('10.2514/1.J051183baddoi')\n assert (\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for create_client
def test_create_client(self): pass
[ "def test_client_create(self):\n pass", "def create_client(self):", "def test_create_client(self):\n client = make_client()\n self.assertIsInstance(client, Dex_K8S_Client)", "def test_single_async_createClient(self):\n self.try_function(\n 'createClient',\n 'p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for delete_client
def test_delete_client(self): pass
[ "def test_single_async_deleteClient(self):\n self.try_function(\n 'deleteClient',\n 'delete',\n argumentNames=['clientId', ],\n )", "def test_delete_o_auth_client(self):\n pass", "def test_client_nationlity_delete(self):\n pass", "def test_05_delete...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_client
def test_get_client(self): pass
[ "def test_client_retrieve(self):\n pass", "def test_create_client(self):\n pass", "def test_get_api_v1_client(self):\n\n client = get_api_v1_client()\n self.assertEqual(type(client), Client)", "def test_get_client(self):\n client = meilisearch.Client(\"http://127.0.0.1:7700\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for list_clients
def test_list_clients(self): pass
[ "def test_client_list(self):\n pass", "def test_list_o_auth2_clients(self):\n pass", "def list_clients(self):\r\n\t\tmsg = {'type': 'list'}\r\n\t\tself.secure_send(msg)", "def test_single_async_listClients(self):\n self.try_function(\n 'listClients',\n 'get',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for update_client
def test_update_client(self): pass
[ "def test_client_update(self):\n pass", "def test_client_partial_update(self):\n pass", "def test_single_async_updateClient(self):\n self.try_function(\n 'updateClient',\n 'post',\n argumentNames=['clientId', 'payload', ],\n )", "def test_client_nat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is portfolio create new returning a Portfolio instance?
def test_01_portfolio_create_new(self): p = Portfolio.create_new(slug="test", description="Portfolio to be used in JPMorgan tests", user="automated unit tester",) self.assertTrue(isinstance(p, Portfolio), msg="Port...
[ "def test_create_portofolio(self):\n\n self.assertIsInstance(self.portfolio, Portfolio)", "def get_portfolio_object(self):\n return self.__get_portfolio_object(self.portfolio_name, self.portfolio_user)", "def portfolio(self):\n self.update_portfolio()\n return self._immutable_portfol...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is portfolio get all returning a list of Portfolio instances?
def test_02_portfolio_get_all(self): self.assertTrue(isinstance(Portfolio.get_all(), list), msg="Portfolio is NOT returning a list of all instances") print("Portfolio get_all method is returning the following list: {}".format( Portfolio.get_all(), ))
[ "def get(self):\n\n return {'Portfolios': list(map(lambda x: x.json(), PortfolioModel.query.all()))}", "def portfolio(self):\n self.update_portfolio()\n return self._immutable_portfolio", "def test_06_get_all_portfolio_transactions(self):\n p = Portfolio.get_portfolio_by_slug(\"test\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is portfolio get portfolio by slug returning an assertive instance?
def test_03_portfolio_get_specific_instance_by_slug(self): self.assertEqual(Portfolio.get_portfolio_by_slug("test"), Portfolio.get_all()[0], msg="Portfolio is NOT returning a valid instance for a specific slug") print("Portfolio get_portfolio_by_slug method is returning the foll...
[ "def get_portfolio(user_id, portfolio_id):", "def get_portfolio_object(self):\n return self.__get_portfolio_object(self.portfolio_name, self.portfolio_user)", "def test_01_portfolio_create_new(self):\n p = Portfolio.create_new(slug=\"test\",\n description=\"Portfoli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is TransactionCost insert cost returning a valid instance?
def test_04_insert_costs(self): c_stock = TransactionCost.insert_new_cost( TRANSACTION_TYPE_STOCK, TRANSACTION_COST_FIXED, 5 ) c_bond = TransactionCost.insert_new_cost( TRANSACTION_TYPE_BOND, TRANSACTION_COST_VARIABLE, 0.01/100 ) c_cash = TransactionCost.i...
[ "def test_create_transaction_money_in(self):\n line = StatementLine.objects.create(\n date=\"2016-01-01\", statement_import=self.statement_import, amount=100\n )\n line.refresh_from_db()\n\n transaction = line.create_transaction(self.sales)\n self.assertEqual(transactio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is transaction creating valid buy stock objects?
def test_05_transaction_create_buy_stock(self): portfolio = Portfolio.get_portfolio_by_slug("test") user = "automated unit tester" buy_stock_aapl = Transaction.buy_stock( portfolio=portfolio, asset="AAPL", t_currency=TRANSACTION_CURRENCY_USD, amou...
[ "def test_11_transaction_create_sell_stock(self):\n portfolio = Portfolio.get_portfolio_by_slug(\"test\")\n user = \"automated unit tester\"\n\n sell_stock_aapl = Transaction.sell_stock(\n portfolio=portfolio,\n asset=\"AAPL\",\n t_currency=TRANSACTION_CURRENCY_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is portfolio get transactions returning a list of Transaction instances?
def test_06_get_all_portfolio_transactions(self): p = Portfolio.get_portfolio_by_slug("test") t = Transaction.get_transactions(p) self.assertTrue(isinstance(t, list), msg="Transaction is NOT returning a list of all transaction instances") print("Transaction get tr...
[ "def getTransactions(self):\n return []", "def transactions(self):\n return self._call_account_method(\n 'transactions'\n )", "def test_08_transaction_assets_of_portfolio(self):\n p = Portfolio.get_portfolio_by_slug(\"test\")\n t = Transaction.get_transaction_assets...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is portfolio get transaction types returning an unique list of Transaction types?
def test_07_transaction_types_of_portfolio(self): p = Portfolio.get_portfolio_by_slug("test") t = Transaction.get_transaction_types(p) self.assertTrue(isinstance(t, list), msg="Transaction is NOT returning a list of unique transaction types") print("Transaction ge...
[ "def test_get_transaction_types(self):\n pass", "def test_06_get_all_portfolio_transactions(self):\n p = Portfolio.get_portfolio_by_slug(\"test\")\n t = Transaction.get_transactions(p)\n self.assertTrue(isinstance(t, list),\n msg=\"Transaction is NOT returning a ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is portfolio get transaction assets returning an unique list of Transaction assets?
def test_08_transaction_assets_of_portfolio(self): p = Portfolio.get_portfolio_by_slug("test") t = Transaction.get_transaction_assets(p) self.assertTrue(isinstance(t, list), msg="Transaction is NOT returning a list of unique transaction assets") print("Transaction...
[ "def test_09_transactions_by_asset(self):\n p = Portfolio.get_portfolio_by_slug(\"test\")\n user = \"automated unit tester\"\n\n buy_stock_ibm = Transaction.buy_stock(\n portfolio=p,\n asset=\"IBM\",\n t_currency=TRANSACTION_CURRENCY_USD,\n amount=32,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is portfolio get transactions by asset returning a list of Transactions?
def test_09_transactions_by_asset(self): p = Portfolio.get_portfolio_by_slug("test") user = "automated unit tester" buy_stock_ibm = Transaction.buy_stock( portfolio=p, asset="IBM", t_currency=TRANSACTION_CURRENCY_USD, amount=32, unit_p...
[ "def test_08_transaction_assets_of_portfolio(self):\n p = Portfolio.get_portfolio_by_slug(\"test\")\n t = Transaction.get_transaction_assets(p)\n self.assertTrue(isinstance(t, list),\n msg=\"Transaction is NOT returning a list of unique transaction assets\")\n prin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is transaction creating valid sell stock objects?
def test_11_transaction_create_sell_stock(self): portfolio = Portfolio.get_portfolio_by_slug("test") user = "automated unit tester" sell_stock_aapl = Transaction.sell_stock( portfolio=portfolio, asset="AAPL", t_currency=TRANSACTION_CURRENCY_USD, a...
[ "def test_05_transaction_create_buy_stock(self):\n portfolio = Portfolio.get_portfolio_by_slug(\"test\")\n user = \"automated unit tester\"\n\n buy_stock_aapl = Transaction.buy_stock(\n portfolio=portfolio,\n asset=\"AAPL\",\n t_currency=TRANSACTION_CURRENCY_USD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is Price insert asset price returning a valid instance?
def test_13_insert_bond_prices(self): p_alitalia = Price.insert_new_price("ALITALIA", 119000) p_samsung = Price.insert_new_price("SAMSUNG", 104000) self.assertTrue(isinstance(p_alitalia, Price), msg="Price is NOT returning a valid inserted ALITALIA instance") pri...
[ "def test_16_insert_cash_prices(self):\n p_eur = Price.update_price(\"EUR\", 1.17)\n p_usd = Price.insert_new_price(\"USD\", 0.8909)\n\n self.assertTrue(isinstance(p_eur, Price),\n msg=\"Price is NOT returning a valid inserted EUR instance\")\n print(\"Price insert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is transaction creating valid sell bond objects?
def test_14_transaction_create_sell_bonds(self): portfolio = Portfolio.get_portfolio_by_slug("test") user = "automated unit tester" sell_bond_alitalia = Transaction.sell_bond( portfolio=portfolio, asset="ALITALIA", t_currency=TRANSACTION_CURRENCY_USD, ...
[ "def is_affordable_transaction(self, terms: Terms) -> bool:", "def test_create_bid_and_check(exchange, mint_tokens) -> None:\n first_addr, second_addr = mint_tokens\n\n \"\"\"\n Trade Id\n Bidder NFT Address\n Asker NFT Address\n Bidder Address\n Asker Address\n Cre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is Price insert asset price returning a valid instance?
def test_16_insert_cash_prices(self): p_eur = Price.update_price("EUR", 1.17) p_usd = Price.insert_new_price("USD", 0.8909) self.assertTrue(isinstance(p_eur, Price), msg="Price is NOT returning a valid inserted EUR instance") print("Price insert EUR asset is retu...
[ "def test_13_insert_bond_prices(self):\n p_alitalia = Price.insert_new_price(\"ALITALIA\", 119000)\n p_samsung = Price.insert_new_price(\"SAMSUNG\", 104000)\n\n self.assertTrue(isinstance(p_alitalia, Price),\n msg=\"Price is NOT returning a valid inserted ALITALIA instanc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is Porfolio consolidation method returning a valid list of consolidated positions by asset?
def test_18_consolidate_portfolio(self): p = Portfolio.get_portfolio_by_slug("test") consolidations = Portfolio.consolidate_portfolio(p) self.assertTrue(isinstance(consolidations, list), msg="Portfolio is NOT returning a valid consolidated list") print("Portfolio ...
[ "def test_08_transaction_assets_of_portfolio(self):\n p = Portfolio.get_portfolio_by_slug(\"test\")\n t = Transaction.get_transaction_assets(p)\n self.assertTrue(isinstance(t, list),\n msg=\"Transaction is NOT returning a list of unique transaction assets\")\n prin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks for a given location and direction if the new location is a Passage.
def check_direction(self, board: np.array, location: tuple, direction: Direction) -> bool: new_location = np.array(location) + direction.array if not self.in_bounds(new_location): return False # Note that this is already a boolean (so no need for if statements) return board...
[ "def can_promote(self, location):\n piece = self.pieces[location]\n if isinstance(piece, King) or isinstance(piece, GoldGeneral) or piece.promoted:\n raise Exception(self.name, 'illegal move', 'Cannot promote {0}'.format(piece))", "def position_check(self, message):\n\n # Creating ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a location to which we can safely move.
def move_to_safe_location(self, obs, location: tuple): # Create a mapping of positions and danger level danger_map = self.create_danger_map(obs) # Check if our current position is safe, if so we can go/stay there. return self.find_reachable_safe_location(obs['board'], danger_map, locat...
[ "def move_toward(state, location):\n return move_relative(state, location, True)", "def _calculate_move_location(self, direction):\n current_row = self._current_loc.get_row()\n current_column = self._current_loc.get_column()\n\n # Calculate the new location for a left move\n if (dir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function to predict the values on the basis of theta and bias calculated while training. Use two methods of Gradient Descents i.e. SGD and BGD
def predict(self, X): SGD_predicted = [] for i in range(len(X)): hypothesis = 0 hypothesis = self.SGD_bias hypothesis += np.matmul(X[i], np.array(self.SGD_theta_list).T) de = 1.0 + np.exp(-hypothesis) sigmoidhypothesis = 1.0/de ...
[ "def gradient_descent(features, values, theta, alpha, num_iterations):\n\n # Write code here that performs num_iterations updates to the elements of theta.\n # times. Every time you compute the cost for a given list of thetas, append it\n # to cost_history.\n # See the Instructor notes for hints.\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get motif set from predefined motif database.
def get_default_motif_set(database="three_databases"): if database == "three_databases": motif_set = _parse_meme_database( f"{DEFAULT_MOTIF_DIR}/JASPAR2018HOCOMOCOv11Jolma2013.meme", f"{DEFAULT_MOTIF_DIR}/JASPAR2018HOCOMOCOv11Jolma2013.metadata.csv", ) # default thre...
[ "def get_set(self, set_id):\n pass", "def metonymic(self):\n return (\n Synset(\n self._wordnet_corpus_reader,\n synset[\"language\"],\n synset[\"pos\"],\n synset[\"offset\"],\n synset[\"gloss\"],\n )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fix duplicate field names by appending an integer to repeated names.
def fix_duplicate_field_names(self,names): used = [] new_names = [] for name in names: if name not in used: new_names.append(name) else: new_name = "%s_%d"%(name,used.count(name)) new_names.append(new_name) used....
[ "def uniqify_names(cls, fields):\n unique = {}\n for field in fields:\n i = 2\n new_id = field.ID\n while new_id in unique:\n new_id = field.ID + f\"_{i:d}\"\n i += 1\n if new_id != field.ID:\n vo_warn(W32, (field...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Postprune your DecisionTreeClassifier given some optional validation dataset. You can ignore x_val and y_val if you do not need a validation dataset for pruning.
def prune(self, x_val, y_val): # make sure that the classifier has been trained before predicting if not self.is_trained: raise Exception("DecisionTreeClassifier has not yet been trained.") ####################################################################### # ...
[ "def prune(self, x_val, y_val):\n\n # make sure that the classifier has been trained before predicting\n if not self.is_trained:\n raise Exception(\"DecisionTreeClassifier has not yet been trained.\")\n\n # get the maximum depth\n deepest_depth = get_max_depth(self.root)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the transform and modifies it such that we compare each line to its transformation. If they are different, that means the line is a special ipython command. We strip that from the output, but record the special command in a comment so we can restore it.
def tweak_transform(orig_transform): def new_push_builder(push_func): def new_push(line): result = push_func(line) if line != result: return "# EPY: ESCAPE {}".format(line) return result return new_push orig_t...
[ "def remove_code_annotations(line_to_transform):\n line_to_transform = str(line_to_transform)\n line_to_transform = line_to_transform.split(' #', 1)[0]\n line_to_transform = line_to_transform.replace(':', '')\n line_to_transform = line_to_transform.replace('\\t', '')\n line_to_transform = line_to_tra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fit_polynomial(self,x,t,m,lambda_reg) returns w_ml, design_matrix
def fit_polynomial(self,x,t,m,lambda_reg=0): phi = self.designMatrix(x,m) phi_trans = np.transpose(phi) a = phi_trans.dot(phi) + lambda_reg*np.identity(phi.shape[1]) b = np.linalg.inv(a) c = b.dot(phi_trans) w_ml = c.dot(t) return w_ml, phi
[ "def fit_polynomial(x, t, M):\n\t# Calculate phi\n\tphi = calculate_phi(x, M)\n\n\t# Calculate best fit (and do a type cast)\n\tWml = phi.T.dot(phi).I.dot(phi.T).dot(t)\n\treturn np.array(Wml)[0]", "def linear_regression(x, t, basis, reg_lambda=0, degree=0):\n\n # TO DO:: Complete the design_matrix function.\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes image passed in darker by halving red, green, blue values.
def darker(image): # Demonstrate looping over all the pixels of an image, # changing each pixel to be half its original intensity. for pixel in image: pixel.red = pixel.red // 2 pixel.green = pixel.green // 2 pixel.blue = pixel.blue // 2
[ "def darker(filename):\n # Demonstrate looping over all the pixels of an image,\n # using pixel.xxx in the loop to change each pixel,\n # int division, relative var updates.\n image = SimpleImage(filename)\n for pixel in image:\n pixel.red = pixel.red // 2\n pixel.green = pixel.green //...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the luminosity of a pixel using NTSC formula to weight red, green, and blue values appropriately.
def compute_luminosity(red, green, blue): return (0.299 * red) + (0.587 * green) + (0.114 * blue)
[ "def Luminosity(self):\n try:\n L = (self.E*self.Weight).sum()\n N = self.E.count()\n except:\n L = self.E.sum()\n N = self.E.count()\n return L, L/np.sqrt(N)", "def luminance(self, color):\n return 0.2426 * color[2] + 0.7152 * color[1] + 0.0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads image from file specified by filename. Change the image to be grayscale using the NTSC luminosity formula and return it.
def grayscale(filename): image = SimpleImage(filename) for pixel in image: luminosity = compute_luminosity(pixel.red, pixel.green, pixel.blue) pixel.red = luminosity pixel.green = luminosity pixel.blue = luminosity return image
[ "def read_image(filename, representation):\n image = imread(filename)\n new_image = image.astype(np.float64)\n new_image /= 255\n if representation == 1:\n new_image = rgb2gray(new_image)\n return new_image", "def read_image(filename, representation):\n img = imread(filename)\n img = i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements the notion of "redscreening". That is, the image in the main_filename has its "sufficiently red" pixels replaced with pixel from the corresponding x,y location in the image in the file back_filename. Returns the resulting "redscreened" image.
def find_flames(main_filename, back_filename): image = SimpleImage(main_filename) back = SimpleImage(main_filename) for pixel in image: average = (pixel.red + pixel.green + pixel.blue) // 3 # See if this pixel is "sufficiently" red if pixel.red >= average * INTENSITY_THRESHOLD:...
[ "def redscreen(main_filename, back_filename):\n image = SimpleImage(main_filename)\n back = SimpleImage(back_filename)\n for pixel in image:\n average = (pixel.red + pixel.green + pixel.blue) // 3\n # See if this pixel is \"sufficiently\" red\n if pixel.red >= average * INTENSITY_THRES...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the episode with the provided id
def get_episode(self, object_id): return self.get_object("episode", object_id)
[ "def episode(self, ep_id: int) -> Episode:\n cursor = self._conn.cursor()\n cursor.execute(self.SQL_EPISODES_BY_ID, (ep_id,))\n\n result = cursor.fetchone()\n if result is None:\n return None\n else:\n feed = self.feed(result[0])\n return Episode(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the playlist with the provided id
def get_playlist(self, object_id): return self.get_object("playlist", object_id)
[ "def get_playlist_by_id(cls, id):\n try:\n return cls._playlists_by_id[id]\n except KeyError:\n return None", "def get_playlist(self, playlist_id, playlist_dir, username):\n playlist_filename = BeetIdType.get_type(playlist_id)[1]\n location = os.path.join(playlist...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the podcast with the provided id
def get_podcast(self, object_id): return self.get_object("podcast", object_id)
[ "def get_podcast(_id):\r\n return [Podcast.podcast_json(Podcast.query.filter_by(id=_id).first())]\r\n # Podcast.podcast_json() coverts our output to the json format defined earlier\r\n # the filter_by method filters the query by the id\r\n # since our id is unique we will only get one re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the radio with the provided id.
def get_radio(self, object_id=None): return self.get_object("radio", object_id)
[ "def get_radio(name: str) -> Radio:\n for radio in RADIOS:\n if radio.name == name:\n return radio\n raise KeyError", "def get_radios(self):\n return self.get_object(\"radio\")", "def radio(self):\n\t\treturn self._radio", "def FindControlById(self, id):\n for ctrl in sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of radios.
def get_radios(self): return self.get_object("radio")
[ "def get_radios(self, **kwargs) -> list[Radio]:\n return self.get_relation(\"radios\", **kwargs)", "def radios(self, **kwargs):\n if self.name and ('name' not in kwargs or kwargs.get('name') == self.name):\n return self._element_call(lambda: self.frame.radios(**dict(kwargs, name=self.name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the top radios (5 radios).
def get_radios_top(self): return self.get_object("radio", relation="top")
[ "def get_radios(self):\n return self.get_object(\"radio\")", "def radioroot(self):\n # This is the only solution I found to retrieve the radiobutton var\n # in a clean way, using the current program arhitecture\n self.radio_root = tk.Tk()\n self.radio_var = tk.IntVar(self.radio_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parses a sabdb format status line. Support v1 and v2.
def parse_statusline(line): if line.startswith("="): line = line[1:] if not line.startswith("sabdb:"): raise OperationalError("wrong result received") code, prot_version, rest = line.split(":", 2) if prot_version not in ["1", "2"]: raise InterfaceError("unsupported sabdb protoc...
[ "def _parse_status_line(line):\n # Up to the first space is the protocol version.\n index0 = line.index(SPACE)\n http_version = line[: index0]\n # Make sure it's the protocol version we recognize.\n assert http_version == HTTP_VERSION\n # Starting from the first space, up to the next space is the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
raises an exception if the result is not empty
def isempty(result): if result != "": raise OperationalError(result) else: return True
[ "def _raise_if_empty_poll_result(result):\n if 'taskToken' not in result:\n raise EmptyTaskPollResult('empty result (no task token)')\n return result", "def db_query_is_empty(result):\n\n rows = []\n # start iterating through GqlQuery\n for r in result:\n rows.append(r)\n break...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the given database, if the MonetDB Database Server is running.
def start(self, database_name): return isempty(self._send_command(database_name, "start"))
[ "def cmd_database_service_start(self, arg):\n database.database_start(self.config)", "def start_db_instance(DBInstanceIdentifier=None):\n pass", "def start_relational_database(relationalDatabaseName=None):\n pass", "def set_working_database(self, database):\n self.db = self.client[database...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stops the given database, if the MonetDB Database Server is running.
def stop(self, database_name): return isempty(self._send_command(database_name, "stop"))
[ "def stop_db_instance(DBInstanceIdentifier=None, DBSnapshotIdentifier=None):\n pass", "def stop_relational_database(relationalDatabaseName=None, relationalDatabaseSnapshotName=None):\n pass", "def stop_db_cluster(DBClusterIdentifier=None):\n pass", "def docker_db_stop(ctx):\n ctx.run('sudo docker ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Kills the given database, if the MonetDB Database Server
def kill(self, database_name): return isempty(self._send_command(database_name, "kill"))
[ "def stop(self, database_name):\n return isempty(self._send_command(database_name, \"stop\"))", "def kill_connections(ctx, superuser='postgres', database='karelian_testdb'):\n ctx.run(\"\"\" psql -U {0} -d {1} -c \"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_act...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets property to value for the given database for a list of properties, use `pymonetdb get all`
def set(self, database_name, property_, value): return isempty(self._send_command(database_name, "%s=%s" % (property_, value)))
[ "def add_properties(jw_properties, db_result):\n\n # Only need to add the description and units entries from db_result\n jw_properties.extend(db_result[1:])\n\n return jw_properties", "def set_property(self,obj_property,value):\n existing_properties = self.get_property(obj_property)\n if ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add engine to the excel writer registry.io.excel. You must use this method to integrate with ``to_excel``.
def register_writer(klass: ExcelWriter_t) -> None: if not callable(klass): raise ValueError("Can only register callables as engines") engine_name = klass._engine _writers[engine_name] = klass
[ "def add_engine(self, engine):\n self.engines.append(engine)", "def _export_to_excel(self):\n\n wb = openpyxl.Workbook() # 声明工作薄实例\n ws = wb.active # 激活工作表\n ws.title = \"食谱数据\"\n\n ws['A1'] = \"菜名\"\n ws['B1'] = \"阅读数\"\n ws['C1'] = \"收藏数\"\n\n\n for i,ur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the default reader/writer for the given extension.
def get_default_engine(ext: str, mode: Literal["reader", "writer"] = "reader") -> str: _default_readers = { "xlsx": "openpyxl", "xlsm": "openpyxl", "xlsb": "pyxlsb", "xls": "xlrd", "ods": "odf", } _default_writers = { "xlsx": "openpyxl", "xlsm": "openp...
[ "def getReaderByExtension(self, ext, isRGB = 0):\n\t\tassert ext in self.extMapping, \"Extension not recognized: %s\" % ext\n\t\tmpr = self.extMapping[ext]\n\t\tprefix=\"vtk\"\n\t\t# If it's a tiff file, we use our own, extended TIFF reader\n\t\tif self.extMapping[ext] == \"TIFF\":\n\t\t\tmpr = \"ExtTIFF\"\n\t\t\tp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert Excel column name like 'AB' to 0based column index.
def _excel2num(x: str) -> int: index = 0 for c in x.upper().strip(): cp = ord(c) if cp < ord("A") or cp > ord("Z"): raise ValueError(f"Invalid column name: {x}") index = index * 26 + cp - ord("A") + 1 return index - 1
[ "def index_from_col(col_name):\n return ord(col_name.upper()) - 65", "def excel_col_letter_to_index(x):\n return reduce(lambda s,a:s*26+ord(a)-ord('A')+1, x, 0)", "def get_column_alphabetical_index_from_zero_indexed_num(col_idx: int) -> str:\n num_letters_alphabet = 26\n\n def get_letter_from_zero_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert `usecols` into a compatible format for parsing in `parsers.py`.
def maybe_convert_usecols( usecols: str | list[int] | list[str] | usecols_func | None, ) -> None | list[int] | list[str] | usecols_func: if usecols is None: return usecols if is_integer(usecols): raise ValueError( "Passing an integer for `usecols` is no longer supported. " ...
[ "def _modify_fields(usecols, dtype, badcols):\n for col in badcols:\n usecols = [badcols[col] if uc == col else uc for uc in usecols]\n try:\n dtype[badcols[col]] = dtype.pop(col)\n except KeyError:\n pass\n return usecols, dtype", "def parse_column_names(x_col_set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to combine two sources of kwargs for the backend engine. Use of kwargs is deprecated, this function is solely for use in 1.3 and should be removed in 1.4/2.0. Also _base.ExcelWriter.__new__ ensures either engine_kwargs or kwargs must be None or empty respectively.
def combine_kwargs(engine_kwargs: dict[str, Any] | None, kwargs: dict) -> dict: if engine_kwargs is None: result = {} else: result = engine_kwargs.copy() result.update(kwargs) return result
[ "def assign_kwargs(self, **kwargs):\n # Handy little loop here only adds kwargs that exist in DEFAULTS, or the default value.\n # It ignores any non-relevant kwargs\n for key, value in self.DEFAULTS.items():\n if key in kwargs:\n setattr(self, key, kwargs[key])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a serialized list of accounts that the authenticated user has access to
def get(self): held_accounts = User.get_held_accounts( get_jwt_identity(), initialize_models=True) schema = AccountsListSchema(many=True) response = schema.dumps(held_accounts) return jsonify_response(json.loads(response.data), 200)
[ "def accounts(self):\n return self._accounts.values()", "def get_accounts(self):\r\n return self._accounts", "def list_accounts(self):\n pass", "def getAccounts(self):\n query = (\"SELECT account from %s \" % (self.__tablename__), )\n results = self.sql_fetchall(query)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST endpoint used for creating new secondary Accounts linked to the currently authenticated user
def post(self): data = json.loads(request.data) user_id = get_jwt_identity() if 'title' not in data: return jsonify_response({"errors": "`title` field is required."}, 400) held_accounts = User.get_held_accounts(user_id) if held_accounts: user_accounts = ...
[ "def create_account(self):\n pass", "def account_post(request):\n fields = [\"fname\", \"lname\", \"email\", \"token\"]\n body = None\n\n try:\n body = request.get_json()\n except:\n return http400(\"Missing body\")\n\n body_validation = validate_body(body, fields)\n # check...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the devices connected over adb.
def get_devices(adb=DEFAULT_ADB): # Check that adb is running Device.__start_adb(adb) # Split by newline and remove first line ("List of devices attached") # TODO: surround with try/except? devices = subprocess.check_output( [adb, "devices", "-l"]).decode().split('\n'...
[ "def list_devices():\r\n return sd.query_devices()", "def get_android_devices():\n android_devices_list = []\n for device in Shell.invoke('adb devices').splitlines():\n if 'device' in device and 'devices' not in device:\n device = device.split('\\t')[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start adb if not started already
def __start_adb(adb): try: with open(os.devnull, "w") as dnl: subprocess.check_call(["pgrep", "adb"], stdout=dnl) except subprocess.CalledProcessError: # adb is not running try: # Try to start adb by calling "adb devices" ...
[ "def start(self):\n\n #print 'start tcp port 8080 forwarding'\n subprocess.call(r'%s forward tcp:%d tcp:8080'%(self.adbCmd,self.port),shell=True)\n\n\n # this is not mandatory as we already killed adb server, but this could \n # decrease the webview created in andriod server application....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy the SELinux policy from the device to the target path. If no policy is specified, the default location is assumed.
def pull_policy(self, target, policy=DEFAULT_POLICY_FILE): self.pull_file(policy, target)
[ "def set_device_policy(device_policy):\n if device_policy == 'silent':\n context.context().device_policy = context.DEVICE_PLACEMENT_SILENT\n elif device_policy == 'silent_for_int32':\n context.context().device_policy = context.DEVICE_PLACEMENT_SILENT_FOR_INT32\n elif device_policy == 'warn':\n context.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the appropriate "adb shell" command for the current device, taking into account the type of root available. Returns the command as a list.
def __get_adb_shell(self): shell = self.command + ["shell"] if self.root_adb == "root_adb": # Root adb-specific things pass elif self.root_adb == "root_shell": # Root shell-specific things shell.extend(["su", "-c"]) elif self.root_adb == "n...
[ "def get_android_devices():\n android_devices_list = []\n for device in Shell.invoke('adb devices').splitlines():\n if 'device' in device and 'devices' not in device:\n device = device.split('\\t')[0]\n android_devices_list.append(device)\n return androi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The device Android version.
def android_version(self): if not self._android_version: # Get the Android version from the connected device cmd = ["getprop", "ro.build.version.release"] # TODO: surround with try/except? tmp = subprocess.check_output(self.shell + cmd).decode() self._...
[ "def get_device_version():\n with os.popen('adb shell getprop ro.build.version.release') as device_version:\n version = device_version.read()\n logger.info(f'当前连接设备的版本号为: Android {version}')\n return version", "def device_version(self):\n return self._device_version", "def get_and...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The device SELinux mode (enforcing/permissive).
def selinux_mode(self): if not self._selinux_mode: # Get the SELinux mode from the connected device cmd = ["getenforce"] # TODO: surround with try/except? tmp = subprocess.check_output(self.shell + cmd).decode() self._selinux_mode = tmp.strip('\r\n').l...
[ "def is_selinux_system(self):\n if self.selinux == None:\n if shellutil.run(\"which getenforce\", chk_err=False) == 0:\n self.selinux = True\n else:\n self.selinux = False\n return self.selinux", "def se_linux(self) -> pulumi.Input['SELinuxStrategy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the processes running on the device. Returns a dictionary (PID, Process).
def get_processes(self): processes = {} # Get ps output cmd = ["ps", "-Z"] # Split by newlines and remove first line ("LABEL USER PID PPID NAME") # TODO: surround with try/except? psz = subprocess.check_output(self.shell + cmd).decode().split('\n')[1:] for line in...
[ "def get_process_list() -> Dict:\n return {proc.pid: proc.name() for proc in psutil.process_iter()}", "def get_running_processes(self, dev_handler):\n # Get the list of running processes on each device\n running_processes = NvmlHandler.exec_nvml_function(nvmlDeviceGetComputeRunningProcesses,dev_h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the files under the given path from a connected device. The path must be a directory. Returns a dictionary (filename, File).
def get_files(self, path="/"): files_dict = {} listing = [] path = os.path.normpath(path) cmd = ["ls", "-lRZ", "'" + path + "'"] # Get the File object for the top-level path # We could not get it otherwise files_dict.update(self.get_dir(path)) # If the de...
[ "def get_files_by_path(path):\n path = Path(path)\n if path.is_file():\n return [path]\n if path.is_dir():\n return get_morph_files(path)\n\n raise IOError('Invalid data path %s' % path)", "def get_file_disk_info_path(path, save_md5sum=False):\n # if relative path, is treated relative...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the file matching the given path from a connected device. The path must be a file. Returns a dictionary (filename, File).
def get_file(self, path): path = os.path.normpath(path) cmd = ["ls", "-lZ", "'" + path + "'"] listing = subprocess.check_output(self.shell + cmd).decode().split('\n') line = listing[0].strip("\r") # Parse ls -lZ output for a single file try: f = File(line, os....
[ "def get_file(self, job, path):\n\t\t\n\t\t# get file by path\n\t\tc = self.conn.cursor()\n\t\tc.execute(\"\"\"\n\t\t\tSELECT * FROM files WHERE job = ? AND path = ? LIMIT 1\n\t\t\"\"\", (job, path))\n\t\t\t\n\t\tresult = c.fetchone()\n\t\t\n\t\tif not result:\n\t\t\tc.close()\n\t\t\treturn None\n\t\t\n\t\tc.close(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a File. l the line in the Android ls l(R)Z output d the directory in which the file is a_v the Android version string ("5.1.1", "6.0", "N", ...)
def __init__(self, l, d, a_v): # TODO: change the parsing to matching groups in the regexes and # extract parameters that way. # If this is an old-style file line (Android<=6.0) if a_v == "6.0" or (a_v[0].isdigit() and (int(a_v)) < 6): if not File.correct_line_6_0.match(l): ...
[ "def __init__(self, version_file):\n self._ReadFile(version_file)\n\n self.filename_prefix = ''", "def get_file(self, path):\n path = os.path.normpath(path)\n cmd = [\"ls\", \"-lZ\", \"'\" + path + \"'\"]\n listing = subprocess.check_output(self.shell + cmd).decode().split('\\n')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the file is a symlink, False otherwise
def is_symlink(self): return self._security_class == "lnk_file"
[ "def is_symlink(self, path):\n return os.path.islink(path)", "def check_is_symlink():\n try:\n return not os.path.islink(im_dir)\n except OSError:\n return False", "def is_symlink(self):\n try:\n return S_ISLNK(self.lstat().st_mode)\n except OS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a Process. line the line in the Android ps Z output a_v the Android version string ("5.1.1", "6.0", "N", ...)
def __init__(self, line, a_v): # If this is an old-style process line (Android<=6.0) if a_v == "6.0" or (a_v[0].isdigit() and (int(a_v[0])) < 6): if not Process.correct_line_6_0.match(line): raise ValueError('Bad process "{}"'.format(line)) p = line.split(None, 4)...
[ "def do_version(self, line):\n print(version)", "def _prepare_process(self):\n\t\tself.argv = [self.executable]\n\t\tself.argv += self.default_argv\n\t\t# https://github.com/gustaebel/python-mpv/pull/2\n\t\tself.argv += [\"--input-ipc-server\", self._sock_filename]\n\t\tif self.window_id is not None:\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the process VSIZE
def vsize(self): if hasattr(self, "_vsize"): return self._vsize else: return None
[ "def vm_size(self) -> str:\n return pulumi.get(self, \"vm_size\")", "def vm_size(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"vm_size\")", "def vm_size(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"vm_size\")", "def virtual_size(self):\n return self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the process RSS
def rss(self): if hasattr(self, "_rss"): return self._rss else: return None
[ "def get_rss(self):\n out = subprocess.check_output(\n [\"ps\", \"-p\", \"%s\" % os.getpid(), \"-o\", \"rss\"])\n try:\n return int(out.splitlines()[-1].strip())\n except ValueError:\n return 0", "def scrape_rss(self):\n return self.scrape(self.RSS_ENTR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the process WCHAN
def wchan(self): if hasattr(self, "_wchan"): return self._wchan else: return None
[ "def getChannel(self):\r\n return self.channel", "def confchan (self):\n return self._confchan", "def wifi_channel(self):\n return self._wifi_channel", "def thread_get_io_channels(client):\n return client.call('thread_get_io_channels')", "def listAvailableCommunicationChannels():", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the process PC
def pc(self): if hasattr(self, "_pc"): return self._pc else: return None
[ "def get_pcname(): \n pc_name = '' \n try: \n pc_name = socket.gethostname() \n except Exception, e:\n initlog('failed to get PC name; %s' % str(e)) \n return pc_name", "def read_pc(self):\n pass", "def pc(self) -> int:\n return self.get_register_value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move a node from it's current position to end of queue (e.g. after a cache hit)
def move_to_end(self, node): # No need to move if node already at queue end if node is self.tail: return # If the node is at the head of the queue if node is self.head: self.head.next.prev = None self.tail.next = self.head self.head.prev ...
[ "def _move_to_head(self, node):\n self._remove_node(node)\n self._add_node(node)", "def move(self):\n active_item = self.stack.pop()\n self.backlog.put(active_item)", "def move_to_head(self, node):\n self.remove_node(node)\n self.add_node(node)", "def _move(self, node...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dequeue the node from head of queue, which is the LRU cache key
def dequeue(self): node = self.head self.head = self.head.next self.head.prev = None node.next = None return node.value
[ "def dequeue(self): \n if self.is_empty():\n raise self.EmptyError('Queue empty')\n elem = self._queue[self._head] # element to be returned\n self._queue[self._head] = None # garbage collection\n self._head = (self._head + 1) % len(self._queue) # advance head index\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert one queue into several equivalent Queues >>> q1, q2, q3 = multiplex(3, in_q)
def multiplex(n, q, **kwargs): out_queues = [Queue(**kwargs) for i in range(n)] def f(): while True: x = q.get() for out_q in out_queues: out_q.put(x) t = Thread(target=f) t.daemon = True t.start() return out_queues
[ "def reverse_queue2(queue):\r\n outqueue = QueueV3()\r\n stack = Stack()\r\n i = queue.length()\r\n for pos in range(i):\r\n item = queue.dequeue()\r\n stack.push(item)\r\n print('dequeued', item)\r\n queue.enqueue(item)\r\n while not stack.length() == 0:\r\n item =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge multiple queues together >>> out_q = merge(q1, q2, q3)
def merge(*in_qs, **kwargs): out_q = Queue(**kwargs) threads = [Thread(target=push, args=(q, out_q)) for q in in_qs] for t in threads: t.daemon = True t.start() return out_q
[ "def merge_qubits(self, q_id1, q_id2):\n l = self.shared_dict.get_queues_for_ids([q_id1, q_id2])\n if len(l) == 1:\n return # Already merged\n else:\n logging.debug(\"Merge Qubits %s and %s.\", q_id1, q_id2)\n q1 = l[0]\n q2 = l[1]\n merge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to assign the policy definition to the assignment_id
def __assign_policy_def(self): self.logger.info( f"Creating policy assignment of definition {self.policy_id} to assignment {self.assignment_id}" ) policy_assignment_res = self.interactor.put_policy_assignment( self.policy_id, self.assignment_id ) if poli...
[ "def policy_assignment_name(self, policy_assignment_name):\n self._policy_assignment_name = policy_assignment_name", "def set_assignment_policy(self, policy):\n self._config['assignment-policy'] = assert_type(policy, AssignmentPolicy)\n return self", "def organization_policy_assignment_id(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to trigger the evaluation of the policy with the given assignment_id
def __trigger_policy(self): self.logger.info(f"Triggering policy assignment {self.assignment_id}") eval_status_loc = self.interactor.trigger_policy().headers["location"] self.logger.debug( f"Policy evaluation for {self.assignment_id} at {eval_status_loc}" ) return e...
[ "def evaluation_policy_id(self, evaluation_policy_id):\n\n self._evaluation_policy_id = evaluation_policy_id", "def evaluate(rule_id):\n try:\n rule = Rule.objects.get(id=rule_id)\n except Rule.DoesNotExist:\n log.warning('Cannot evaluate rule %s, not found', rule_id)\n return\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Waits for the policy evaluation given at the url to be completed, blocks while evaluation ongoing (Status Code 202 Pending, 200 Completed)
def __poll_evalutation_result(self, eval_state_url, sleep_time): self.logger.debug( f"Starting poll cycle for {self.assignment_id}, eval_id {self.eval_id}. Polling {eval_state_url}" ) result = self.interactor.get_policy_eval_state(eval_state_url) while result.status_code =...
[ "def waitForAsyncJob(url, token):\n jobDetail = {}\n timeout = 5\n while jobDetail.get('isFinished', False) != True:\n jobDetail = getRequest(url, token)['body']\n time.sleep(timeout)\n return jobDetail", "async def _poll(self) -> None:\n if not self.finished():\n await...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to get the summary of the just finished evaluation
def __get_evaluation_summary(self): self.logger.debug( f"Getting summary for assignment {self.assignment_id}, eval_id {self.eval_id}" ) result = self.interactor.get_policy_eval_summary(self.assignment_id) if result.status_code != 200: self.logger.debug( ...
[ "def evaluation(self):\n return self._evaluation", "def _report_summary(self):\n self.report.add_heading(\"Summarized results for %s.\" % self.__class__.__name__, 3)\n entries = filter(lambda te: te.result is not None, self._tests)\n self.report.add_summary(entries)\n resultmsg ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes Policy assignment and definition for the current policy
def __cleanup(self): self.logger.debug("Deleting assignment and definition of policy") self.interactor.delete_policy_assignment(self.assignment_id) self.interactor.delete_policy_definition(self.policy_id)
[ "def delete_policy(policy_id):", "def delete_unused(self, mode):\n self.policies = self.list_policies()\n for policy in self.policies['Policies']:\n if policy['AttachmentCount'] < 1:\n self.policy_versions = self.con.list_policy_versions(\n PolicyArn=poli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a simulator with specified parameters
def create_simulator( simulation_parameters: Dict[str, Any], pulse_shape: str, num_realizations: int, distortion: bool ) -> QuantumMLSimulator: return QuantumMLSimulator( simulation_parameters["evolution_time"], simulation_parameters["num_time_steps"], simulat...
[ "def create_simulator(self):\n\n simulator = GAimsunSimulator()\n simulator.setModel(self.model)\n\n return simulator", "def _setup_simulator(args, port):\n from liveserial.simulator import ComSimulatorThread\n sensors = args[\"sensors\"][port]\n dtypes = []\n for s in sensors:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Quantum ML simulator from a known experiment name
def create_default_simulator( experiment_name: str, distortion: bool, num_realizations: int, pulse_shape: str, ) -> QuantumMLSimulator: if pulse_shape not in ["Gaussian", "Square", "Zero"]: raise ValueError( "Pulse Shape is not known. Expected one of {}, found {...
[ "def create_simulation_application(name=None, sources=None, simulationSoftwareSuite=None, robotSoftwareSuite=None, renderingEngine=None, tags=None):\n pass", "def create_experiment(self, name, artifact_location):", "def newExperiment(self):\n experiment = Experiment()\n newtitle = 'Untitled ' +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds forms for Bulk Add/Change and Bulk Delete to context
def change_view(self, request, object_id, form_url='', extra_context=None): section = models.Section.objects.filter(pk=object_id)\ .prefetch_related("facility__experiment", "participants")\ ...
[ "def admin():\n return render_template('bulkform.html')", "def forms(self):\n edit = EquipmentChownForm\n return {\n 'edit': edit,\n }", "def get_context_with_form(self):\n self.context['form'] = {\n 'profile': ProfileEditForm(),\n 'avatar': Avatar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test BIGIP refresh_ltm function.
def test_bigip_refresh_ltm(bigip_proxy): big_ip = bigip_proxy.mgmt_root() test_pools = [ IcrPool(**p) for p in big_ip.bigip_data['pools'] if p['partition'] == 'test' ] test_virtuals = [ VirtualServer(default_route_domain=0, **v) for v in big_ip.bigip_data['virtuals'] ...
[ "def test_refresh_vms(request, scenario):\n from_ts = int(time.time() * 1000)\n ssh_client = SSHClient()\n logger.debug('Scenario: {}'.format(scenario['name']))\n\n clean_appliance(ssh_client)\n\n monitor_thread = SmemMemoryMonitor(SSHClient(), 'workload-refresh-vm', scenario['name'],\n 'refre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test BIGIP refresh_net function.
def test_bigip_refresh_net(bigip_proxy): bigip = bigip_proxy.mgmt_root() test_arps = [ IcrArp(**a) for a in bigip.bigip_net_data['arps'] if a['partition'] == 'test' ] test_tunnels = [ IcrFDBTunnel(default_route_domain=0, **t) for t in bigip.bigip_net_data['fdbTunnels'] i...
[ "def test_bigip_refresh_ltm(bigip_proxy):\n big_ip = bigip_proxy.mgmt_root()\n\n test_pools = [\n IcrPool(**p) for p in big_ip.bigip_data['pools']\n if p['partition'] == 'test'\n ]\n test_virtuals = [\n VirtualServer(default_route_domain=0, **v)\n for v in big_ip.bigip_data['...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test BIGIP properties function.
def test_bigip_properties(bigip_proxy): big_ip = bigip_proxy test_pools = [ IcrPool(**p) for p in big_ip.mgmt_root().bigip_data['pools'] if p['partition'] == 'test' ] test_virtuals = [ VirtualServer(default_route_domain=0, **v) for v in big_ip.mgmt_root().bigip_data['vir...
[ "def test_serve_properties(self):\n pass", "def test_properties_get(self):\n pass", "def test_properties_distribution_get(self):\n pass", "def test_serve_property(self):\n pass", "def test_properties_stats_get(self):\n pass", "def test_properties_evolution_get(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a properly formatted XML backup file, and replies with the existence/condition of each Task.
def wmAnalyzeImportXML(self): inputtext = uiCommon.getAjaxArg("import_text") inputtext = uiCommon.unpackJSON(inputtext) on_conflict = uiCommon.getAjaxArg("on_conflict") # the trick here is to return enough information back to the client # to best interact with the user. ...
[ "def check_indicator_files(tasks):\n\n for task in tasks:\n if task[\"status\"]==\"unknown\":\n if os.path.exists(task[\"result\"]):\n task[\"status\"]=\"previously completed\"\n else:\n task[\"status\"]=\"to do\"\n return", "def _validate_taskfile(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will eventually have lots of flexibility based on the 'type' and 'in' parameters. For the moment we're starting with the ability to search Task function_xml for the pattern.
def wmSearch(self): _type = uiCommon.getAjaxArg("type") _in = uiCommon.getAjaxArg("in") _pattern = uiCommon.getAjaxArg("pattern") out = {} if _type == "task": # bare essentials - is the pattern in the function_xml column where_clause = "where (fu...
[ "def _filter_function_for_tasktype(self, functions):\n if len(functions) == 0:\n return None\n\n elif len(functions) == 1:\n return functions[0]\n\n category = self.context.task_type_category\n default = None\n\n for func in functions:\n filter_cat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }