query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Test case for modify_response_descriptor_subscriptions_subscription_subscription_resource_spaces
def test_modify_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self): pass
[ "def test_create_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_index_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resour...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns country by location name. May raise LocationNotFound and LocationReplacement
def country(name): return location_db().find(name=name)["country"]
[ "def get_country(self, country_name):\n return self.map.get(country_name)", "def test_get_country_by_geo_location(self):\n pass", "def findCountry(latitude, longitude):\n try:\n results = Geocoder.reverse_geocode(latitude, longitude)\n country_out = results.country\n except:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns continent by either location name or country. May raise LocationNotFound and LocationReplacement
def continent(name=None): ldb = location_db() try: return ldb.find_continent(country=name) except LocationNotFound: return ldb.find_continent(country=ldb.find(name=name)["country"])
[ "def get_continent(country: str) -> str:\r\n for continent, countries in country_lookup.items():\r\n for c in countries:\r\n if country.lower() in c.lower():\r\n return continent", "def country(name):\n return location_db().find(name=name)[\"country\"]", "def find_continen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if every "locations" entry has corresponding "names" entry
def check(self): missing = [] for name in self.data["locations"]: try: n = self.data["names"][name] except KeyError: missing.append(name) if missing: raise RuntimeError("\"names\" list lacks:\n " + "\n ".join(missing))
[ "def check_names(sections):\n return _check_nentries(sections, \"NAMES\", \"NAMES\")", "def test_locations(self):\n locations = [\n 'http://portland.craigslist.org/',\n 'http://chicago.craigslist.org/'\n ]\n\n loc_url_parts = ['location=%s' % urllib.quote_plus(l) for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Forwards data migration. Remove all the externalaccounts for GitHub, GTalk, Verbatim and Locamotion.
def forwards(apps, schema_editor): ExternalAccount = apps.get_model('users', 'ExternalAccount') ExternalAccount.objects.filter(type='GITHUB').delete() ExternalAccount.objects.filter(type='GTALK').delete() ExternalAccount.objects.filter(type='MOZILLALOCAMOTION').delete() ExternalAccount.objects.filte...
[ "def migrateDown(self):\n ss = self.avatars.open()\n def _():\n oldAccounts = ss.query(LoginAccount)\n oldMethods = ss.query(LoginMethod)\n for x in list(oldAccounts) + list(oldMethods):\n x.deleteFromStore()\n self.cloneInto(ss, ss)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy the static resources.
def copy_static_resources(self): if not hasattr(settings, 'STATIC_ROOT'): raise MissingStaticRoot() destination = os.path.join(STORAGE_PATH, 'static') if os.path.exists(destination): shutil.rmtree(destination) shutil.copytree(settings.STATIC_ROOT, destination)
[ "def copy_static(self):\n try:\n shutil.copytree('template/static', 'public/static')\n except:\n print(\"Error copying static files \")", "def copy_site_assets(self):\n if os.path.isdir(\"static\"):\n self.merge_dirs(\"static\", os.path.join(self.out_dir, \"st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for privacy policy view
def test_1_privacy(self): response = self.client.get(reverse('privacy-policy'), follow=True) self.assertEqual(response.status_code, 200)
[ "def privacy(request):\n return render(request, \"privacy_policy.html\")", "def privacy():\n return render_template('privacy.html')", "def privacy():\n return generic_path_render(\"outside/privacy/privacy.html\")", "def test_viewPrivacyPolicyPage(self):\r\n print('=============================...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for group required decorator
def test_5_group_required(self): user = User.objects.get(email=data_user['email']) self.factory = RequestFactory() @group_required('default') def test(request): return 200 request = self.factory.get('/foo') request.user = user response = test(request...
[ "def test_group(self):\n pass", "def group_required(*groups):\n\n def decorator(func):\n @wraps(func)\n def check_auth(*args, **kwargs):\n check_user_group(*groups)\n return func (*args, **kwargs)\n return check_auth\n return decorator", "def test_decorato...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
metaDataInputAvailable(inputType, inputKey) Return true if inputType with inputKey is available.
def metaDataInputAvailable(inputType, inputKey): # Check if it is on metadata: # FIXME How can I do that using objKeyStore?? flag = False from RecExConfig.InputFilePeeker import inputFileSummary metaItemList=inputFileSummary.get('metadata_itemsList') if ( '%s#%s' % (inputType, inputKey) ) in metaItemList: ...
[ "def has_input(self, input_ref):\n inputs = self.get_recipe_inputs()\n for (input_role_name, input_role) in inputs.items():\n for item in input_role.get(\"items\", []):\n if item.get(\"ref\", None) == input_ref:\n return True\n return False", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test creation and deletion of tables.
def test_create(self): cursor = connection.cursor() # It needs to take at least 2 args self.assertRaises(TypeError, db.create_table) self.assertRaises(TypeError, db.create_table, "test1") # Empty tables (i.e. no columns) are not fine, so make at least 1 db.create_table("t...
[ "def test_create(self):\n cursor = connection.cursor()\n # It needs to take at least 2 args\n self.assertRaises(TypeError, db.create_table)\n self.assertRaises(TypeError, db.create_table, \"test1\")\n # Empty tables (i.e. no columns) are not fine, so make at least 1\n db.cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Span/RBW ratio {1, 10000}
def span_rbw_ratio(self): res = self._visa.query(f"SENSE{self._screen()}:BANDWIDTH:RESOLUTION:RATIO?") return 1 / float(res)
[ "def adv_ratio(self): # XXX\r\n bw = StatsRouter.global_bw_mean\r\n if bw == 0.0: return 0\r\n else: return self.bw/bw", "def golden_ratio():\n return 1.61803398875", "def bronze_ratio():\n\n return ratio(3)", "def metric_weight(off):\n# return gcd(100.0 * (4.0 - off), 400.0)/100.0\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RBW/Video BW ratio {0.001, 100}
def rbw_vbw_ratio(self): res = self._visa.query(f"SENSE{self._screen()}:BANDWIDTH:VIDEO:RATIO?") return 1 / float(res)
[ "def span_rbw_ratio(self):\r\n res = self._visa.query(f\"SENSE{self._screen()}:BANDWIDTH:RESOLUTION:RATIO?\")\r\n return 1 / float(res)", "def strm_bw_ratio(self):\r\n bw = self.bwstats.mean\r\n if StatsRouter.global_strm_mean == 0.0: return 0\r\n else: return (1.0*bw)/StatsRouter.global_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if create_knxipframe of base class raises an exception.
async def test_create_knxipframe_err(self): xknx = XKNX() udp_client = UDPClient(xknx, ("192.168.1.1", 0), ("192.168.1.2", 1234)) request_response = RequestResponse(xknx, udp_client, DisconnectResponse) request_response.timeout_in_seconds = 0 with self.assertRaises(NotImplemente...
[ "def create_knxipframe(self) -> KNXIPFrame:\n raise NotImplementedError(\"create_knxipframe has to be implemented\")", "def test_base_class_expection():\n with pytest.raises(TypeError):\n cardinal.CardinalPoints()", "def unexpectedException(self):", "def test_not_h5py_group(self):\n wi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an event on the given group.
def create_event(self, event): body = event['body'] body = json.loads(body) # Check all required fields are here required_fields = ['group_id', 'event_timestamp', 'location'] for f in required_fields: if f not in body: return get_bad_request('POST bod...
[ "def create_event(self, e, group_by=None):\n\n logger.debug(\"Creating event %s\", e.to_dict())\n\n assert e.ready_after is not None\n assert e.handler\n assert e.data\n\n # copy the event object to avoid mutating the original\n event = models.Event(\n handler=e....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the email addresses collected between startdate and enddate.
def get_email_addresses(survey, startdatetime, enddatetime): token = settings.SURVEYGIZMO_API_TOKEN secret = settings.SURVEYGIZMO_API_TOKEN_SECRET emails = [] page = 1 more_pages = True survey_id = SURVEYS[survey]["email_collection_survey_id"] dtfmt = "%Y-%m-%d+%H:%M:%S" # Can't do anyt...
[ "def get_email_addresses(startdate, enddate, user, password):\n emails = []\n page = 1\n more_pages = True\n\n while more_pages:\n response = requests.get(\n 'https://restapi.surveygizmo.com/v2/survey/{survey}'\n '/surveyresponse?'\n 'filter[field][0]=datesubmitte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add email to the exit survey campaign.
def add_email_to_campaign(survey, email): token = settings.SURVEYGIZMO_API_TOKEN secret = settings.SURVEYGIZMO_API_TOKEN_SECRET if token is None or secret is None: return survey_id = SURVEYS[survey]["exit_survey_id"] campaign_id = SURVEYS[survey]["exit_survey_campaign_id"] try: ...
[ "def send_to(self, email):\n current_site = Site.objects.get_current()\n\n subject = render_to_string('betainvite/invitation_email_subject.txt',\n { 'site': current_site,\n 'invitation_key': self })\n # Email subject *must no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collect and aggregate the exit survey results for the date.
def get_exit_survey_results(survey, date): token = settings.SURVEYGIZMO_API_TOKEN secret = settings.SURVEYGIZMO_API_TOKEN_SECRET answers = [] page = 1 more_pages = True survey_id = SURVEYS[survey]["exit_survey_id"] # Aggregate results. summary = { "yes": 0, "no": 0, ...
[ "def exit(self) -> None:\n self.store.generate_daily_report()\n quit()", "def aggregate_results(self):\n\n raise NotImplementedError", "def get_dates():\n\n if len(request.args) < 1:\n if session.handle:\n handle = str(session.handle)\n else:\n redirec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1. Check each peer's genesis block 2. Generate new blocks on each peer 2.1. 2 blocks on peer 1 2.2. 4 blocks on peer 2 2.3. 2 blocks on peer 3 3. Connect peers 3.1. peer 1 with 2 (1>2) 3.2. peer 1 with 3 (1>(2 and 3)) 4. Generate new blocks 4.1. 3 blocks on peer 1 4.2. 5 blocks on peer 3 5. Stop all peers
def scenario(): LOCAL_HOST = "http://127.0.0.1" # import functions from . import genesis_block from . import create_block from . import connect_peer from . import stop_server from . import block_crosscheck total_cnt = 0 pass_cnt = 0 # 1. Check each peer's genesis block try...
[ "def run(self):\n\n peers = Client(NetworkConfig.get_peer()).api(\"peers\").all_peers(limit=100)\n\n if not peers[\"success\"]:\n print(BPLClientNetworkException({\n \"message\": \"cannot get peers from network\",\n \"error\": peers[\"error\"]\n }), ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It's common to forget to initialize your variables to the same values, or (less commonly) if you update them in some other way than adam, to get them out of sync. This function checks that variables on all MPI workers are the same, and raises an AssertionError otherwise
def check_synced(localval, comm=None): comm = comm or MPI.COMM_WORLD vals = comm.gather(localval) if comm.rank == 0: assert all(val==vals[0] for val in vals[1:]),\ 'MpiAdamOptimizer detected that different workers have different weights: {}'.format(vals)
[ "def init_consistent_qa_variables(self):\n return tuple()", "def test_run_repeatability(self):\n self.assertEqual(TestTrain.hash_100_steps_1, TestTrain.hash_100_steps_2)", "def test_global():\n global_assumptions.add(x > 0)\n assert (x > 0) in global_assumptions\n global_assumptions.remov...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is used for create the nested dict.
def nested_dict(): try: num_list = [1, 2, 3, 4] new_dict = current = {} for name in num_list: current[name] = {} current = current[name] print(new_dict) except ValueError as e: logger.error("Not find the dictnary"+str(e))
[ "def createNestedDict(self, myDict, value, *path):\n for level in path[:-1]:\n myDict = myDict.setdefault(level, {})\n #for level -ends\n dict[path[-1]]=value\n return myDict", "def make_dict(self, item, external_id=True, no_html=False, depth=1, optimize=False):\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses attributes for given hosts, then checks if hosts are up and then calls path_check function with working hosts.
def ip_check(): hosts = [] valid_hosts = [] for item in sys.argv: if '@' in item: hosts.append(item) for i in hosts: host = i.split('@')[1].split(':')[0] command = os.system('ping -c 1 '+host+' > /dev/null') if command == 0: valid_hosts.append(i) ...
[ "def __check_hosts_config_files__(self,hostList):\n\n #If no hosts are defined, return true\n if not hostList:\n return 1\n\n self.hostConfigs={}\n self.ioengineConfigs={}\n errors=[]\n\n for host in hos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds all files or directories on remote machine, according to given attributes.
def find_remote_files(remote_path, type, ssh): (ssh_in, ssh_out, ssh_err) = ssh.exec_command("find %s -name \"*\" -type %s" % (remote_path, type)) files = [] for file in ssh_out.readlines(): files.append(file.rstrip()) return files
[ "def get_remote_files(self):\n fileattrs = []\n try:\n #print \"starting getting file\"\n fileattrs = self.transport.get_remote_files(self.remote_dir)\n# pprint.pprint(fileattrs)\n except Exception, e:\n self.lg.error(\"Failed to get list of files in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds all files or directories on local machine, according to given attributes.
def find_local_files(local_path, type): local_out = commands.getoutput("find %s -name \"*\" -type %s" % (local_path, type)) files = [] for file in local_out.split("\n"): files.append(file) return files
[ "def search(self, pattern):\n\n # list of found elements\n found = []\n\n def search_element(path, element, pattern, is_dir):\n \"\"\"\n check a specific element\n :param path: parent directory\n :param element: the file or directory to check\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show list of movies.
def movie_list(): movies = Movie.query.order_by(Movie.title).all() return render_template("movie_list.html", movies=movies)
[ "def show_movies():\n \n movies = Movie.query.all()\n return render_template('movie_list.html', movies=movies)", "def movies_list():\n \n movies = Movie.query.order_by(Movie.title).all()\n return render_template(\"movie_list.html\", movies=movies)", "def show_all_movies():\n return render_tem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show profile for given user.
def show_user_profile(user_id): user = User.query.filter_by(user_id=user_id).first() return render_template("user_profile.html", user=user)
[ "def show_user_profile(username):\n\n name = USERS[username]\n return f\"<h1>Profile for {name}</h1>\"", "def show_user(user_id):\n user = crud.get_user_by_id(user_id)\n\n return render_template(\"user_details.html\", user=user)", "def user_view(cls, user, profile):\r\n pass", "def user_vie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show profile for given movie.
def show_movie_profile(movie_id): # movie object given a movie_id movie = Movie.query.filter_by(movie_id=movie_id).first() # list of all rating objects for a given movie_id ordered by user_id sorted_ratings = Rating.query.filter_by(movie_id=movie_id).order_by('user_id').all() return render_templa...
[ "def show_movie(movie_id):\n\n movie = crud.get_movie_by_id(movie_id)\n\n return render_template('movie_details.html', movie = movie)", "def show_movie(movie_id):\n\n movie = crud.get_movie_by_id(movie_id)\n\n return render_template('movie_details.html', movie=movie)", "def show_movie_details(movie_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add or update movie rating
def add_movie_rating(movie_id): rating = request.form.get("rating") # Rating object from logged in user for movie on page user_rating_query = Rating.query.filter(Rating.user_id == session["user_id"], Rating.movie_id == movie_id).first() # Check to see if rating exists from logged in user if user_r...
[ "def movie_rating():\n\n rating = request.form.get(\"rating\")\n movie_id = request.form.get(\"movie_id\")\n current_user = session[\"user_id\"]\n\n existing_rating = Rating.query.filter_by(user_id=current_user, movie_id=movie_id).first()\n\n if existing_rating is None:\n new_rating = Rating(u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
, jmx_path, var=None (目前使用时间戳)
def runJmeter(self, jmx_path, var=None): # 提示执行时间 print("=" * 10 + "执行时间:%s" % self.logger_time() + "=" * 10) # 提示执行脚本 print("脚本名称:%s" % (jmx_path)) # 提示执行参数 print("执行参数:%s" % (var)) p = subprocess.Popen(self.make_cmd(var, self.jmeter_path, jmx_path, self.jmeter_l...
[ "def which_obs_mjd(filename):\n if not is_galex_file(filename):\n return None\n h_ = pf.getheader(filename)\n return time.Time(h_[\"OBS-DATE\"]+\"T\"+h_[\"TIME-OBS\"]).mjd", "def test_JtJ(self):\n jtj = m2.GetJandJtJInLogParameters(log(params))", "def __remote_job_info_path(self, sge_job_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a binary tree print the elements in a zig zag order
def zig_zag_traversal(root): return
[ "def zigzak_using_bfs(root):\n current_level = [root]\n next_level = []\n while current_level:\n node = current_level.pop()\n print(node.data, end=\" \")\n if node.right:\n next_level.append(node.right)\n if node.left:\n next_level.append(node.left)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the plotting paramters like legend size, text font size, etc See the return object
def global_plotting_parameters(): dpi = 10 plotting_param_dict = {'dpi':dpi, 'axis_font':{'size': str(int(15*dpi))}, 'title_font':{'size': str(18*dpi)}, 'legend_size':{'size': str(12*dpi)}, 'tick_size': 12*dpi, 'marker_size':100*3.5*dpi} return plotting_param_dict
[ "def get_plot_params():\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n\n mpl.rcParams['font.family'] = 'Serif'\n mpl.rcParams['font.serif'] = 'Times New Roman'\n plt.rcParams['font.size'] = 18\n plt.rcParams['axes.linewidth'] = 2\n\n plt.rcParams['xtick.major.size'] = 10\n pl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
assuming centerline cells have two layers, this method returns the arrays of each layers and their global id corresponding to cell_cent
def separate_centrline_lyers_by_y_coordinates(cell_cent, centerline_cells): cc4 = centerline_cells y_uniq_coord = np.unique(cc4[:,1]) idx_lst = [] cent_Y_lyrs = [] for yy in y_uniq_coord: cent_Y_lyrs_temp = centerline_cells[np.where(cc4[:,1] == yy)] idx = np.where((cell_cent==cent_Y...
[ "def getChipCoreAndCxId(layer):\n core_ids = []\n cx_ids = []\n chip_ids = []\n for id in layer.nodeIds:\n _, chip_id, core_id, cx_id, _, _ = layer.net.resourceMap.compartment(id)\n chip_ids.append(chip_id)\n core_ids.append(core_id)\n cx_ids.append(cx_id)\n return np.arra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts conditions file to dictionary
def read_conditions(filepath: str): with open(filepath, 'r') as conditions_file: conditions = {} current_condition_name = line = conditions_file.readline().strip( ).lower() current_condition_description = [] while line: if line.startswith('"'): cur...
[ "def readin_conditions(initial_conditions_text_file):\n with open(initial_conditions_text_file, 'r') as condition_file:\n\n class condition:\n def __init__(self, pressure, temperature, moles, name, species):\n self.name = name\n self.pressure = pressure\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if game is over
def is_game_over(cls): cls.record_winner() cls.record_tie()
[ "def check_if_game_over():\n check_if_win()\n check_if_tie()", "def event_game_over(self):\n print('Game over!')\n self._cmd_exit()", "def _check_game_over(self):\n return self.game_board.check_game_over()", "def gameover(self):\n return \"GAME OVER\"", "def check_game_over...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flip player from X to O and back
def flip_player(cls): cls.current_player = 'X' if cls.current_player == 'O' else 'O' cls.display_board() cls.prompt_player()
[ "def flip_player():\n #global variables that we need\n global current_player\n #if the current player is X, then switch to player O\n if current_player == 'X':\n current_player = 'O'\n #if the current player is O, then switch to player X\n elif current_player == 'O':\n current_player...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store current column width to the class variable
def __store_column_width(self): self.header_width = [] for i in range(0, self.view.header().count()): self.header_width.append(self.view.columnWidth(i))
[ "def width(self, width):\n self.col += width", "def set_column_width(self, index, width):\n self.colwid[index] = width", "def set_default_column_width(self, width):\n\t\tself.default_width = width", "def columnWidth(self, p_int): # real signature unknown; restored from __doc__\n return 0"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The name of the world
def world_name(self) -> str: return os.path.basename(self.path)
[ "def world_name(self) -> str:\n return self.root_tag[\"Data\"][\"LevelName\"].value", "def world_name(self):\n return self.root_tag[\"LevelName\"].value", "def worldStats(self):\n return \"%s: No stats given\" % self.myName", "def Name(self) -> str:", "def get_name(self):\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the options for a specific plugin. This will be the list of options that is registered and loaded by the specified plugin.
def get_plugin_options(name): return get_plugin_loader(name).get_options()
[ "def list_plugin_options(request):\n options = {}\n options.update(plugin.get_plugin_options(request.matchdict['plugin']))\n options.update(plugin.get_plugin_vizoptions(request.matchdict['plugin']))\n return options", "def get_opts(self):\n return self.__options", "def get_all_options(self): ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a plugin from the options available for the loader. Given the options that were specified by the loader create an appropriate plugin. You can override this function in your loader. This used to be specified by providing the plugin_class property and this is still supported, however specifying a property didn't l...
def create_plugin(self, **kwargs): return self.plugin_class(**kwargs)
[ "def load_from_options(self, **kwargs):\n missing_required = [o for o in self.get_options()\n if o.required and kwargs.get(o.dest) is None]\n\n if missing_required:\n raise exceptions.MissingRequiredOptions(missing_required)\n\n return self.create_plugin(**...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a plugin from the arguments retrieved from get_options. A client can override this function to do argument validation or to handle differences between the registered options and what is required to create the plugin.
def load_from_options(self, **kwargs): missing_required = [o for o in self.get_options() if o.required and kwargs.get(o.dest) is None] if missing_required: raise exceptions.MissingRequiredOptions(missing_required) return self.create_plugin(**kwargs)
[ "def create_plugin(self, **kwargs):\n plugin_args = self.get_plugin_params()\n if kwargs:\n plugin_args.update(kwargs)\n return self._create_plugin(**plugin_args)", "def create_plugin(self, **kwargs):\n return self.plugin_class(**kwargs)", "def load_plugin_from_args(args):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test Morlet agains T&C table 2 Psi_t(0) = pi^(1/4) Psi_f(0) = 0
def test_Morlet(): morl = cw.MorletWave() assert(np.isclose(morl(0), np.pi**(-1/4), atol=1.e-12)) assert(np.isclose(morl.freq(0), 0, atol=1.e-12))
[ "def test_t0(self):\n sol = Mader(p_cj=3.0e11, d_cj=8.0e5, gamma=3.0, u_piston=0.0)\n # r must contain 2 elements, otherwise the density and pressure are nan\n r = np.array([0.7, 0.8])\n t = 0.0\n solrt = sol(r, t)\n for quant in ['velocity', 'pressure', 'sound_speed', 'den...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute and return the precession matrix for FK4 using Newcomb's method. Used inside some of the transformation functions.
def _precession_matrix(oldequinox, newequinox): return earth._precession_matrix_besselian(oldequinox.byear, newequinox.byear)
[ "def _precession_matrix(oldequinox, newequinox):\n return earth.precession_matrix_Capitaine(oldequinox, newequinox)", "def get_FK5PrecessMatrix(begEpoch, endEpoch):\n # Interval between basic epoch J2000.0 and beginning epoch (JC)\n t0 = (begEpoch - 2000.0) / 100.0 # origin J2000\n\n # Interv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove features with multicollinearity based on crosscorrelation coefficient.
def remove_multicollinearity_correlation(data: pd.DataFrame, threshold: Optional[float] = 0.8) -> pd.DataFrame: corr_data = pd.DataFrame(np.triu(np.abs(data.corr())), columns=data.columns) multicoll_columns = np.logical_and(corr_data >= threshold, corr_data < 1.0).any() return data.loc[:, ~multicoll_column...
[ "def remove_correlated_features(x, threshold=0.9):\n x_copy = np.copy(x)\n \n corr_matrix = np.corrcoef(x_copy, rowvar=False)\n # Set to False highly correlated columns\n nb_col = len(corr_matrix)\n columns = np.full((nb_col,), True, dtype=bool)\n for i in range(nb_col):\n for j in range...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for picking the highest rating agent and picking the right agent when two agents are finish at the same time
def test_2_agents_done_at_once(self): # Test highest rating agent agent, wait_time = Agent.get(TEST_CUSTOMERS[0]) self.assertEqual( (TEST_AGENTS[1], 0), (agent.agent, wait_time)) # Test 2 agents done at the same time Agent.get(TEST_CUSTOMERS[1]) agent, wait_ti...
[ "def step(self):\n highest_offer = None\n\n if self.manager is None:\n highest_rep = 0\n\n else:\n highest_rep = self.manager.reputation\n\n for offer in self.offers:\n if offer.manager.reputation > highest_rep:\n highest_offer = offer\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a dialect, returns the dialect type, which is defines the engine/system that is used to communicates with the database/database implementation. Currently checks for RedShift/BigQuery dialects
def _get_dialect_type_module(dialect): if dialect is None: logger.warning( "No sqlalchemy dialect found; relying in top-level sqlalchemy types." ) return sa try: # Redshift does not (yet) export types to top level; only recognize base SA types if isinstance(di...
[ "def dialect(self):\n return self.engine.dialect.name", "def dialect(self) -> str:\n return self._engine.dialect.name", "def dialect_of(connection_type: str) -> Dialect:\n return MAP_CONNECTION_TYPE_DIALECT.get(connection_type, Dialect.ANSI)", "def dialect(self):\n return self._dia...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a SqlAlchemyExecutionEngine, using a provided connection string/url/engine/credentials to access the desired database. Also initializes the dialect to be used and configures usage statistics.
def __init__( self, name=None, credentials=None, data_context=None, engine=None, connection_string=None, url=None, batch_data_dict=None, create_temp_table=True, **kwargs, # These will be passed as optional parameters to the SQLAlchemy engi...
[ "def _build_engine(self, credentials, **kwargs) -> \"sa.engine.Engine\":\n # Update credentials with anything passed during connection time\n drivername = credentials.pop(\"drivername\")\n schema_name = credentials.pop(\"schema_name\", None)\n if schema_name is not None:\n log...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using a set of given credentials, constructs an Execution Engine , connecting to a database using a URL or a private key path.
def _build_engine(self, credentials, **kwargs) -> "sa.engine.Engine": # Update credentials with anything passed during connection time drivername = credentials.pop("drivername") schema_name = credentials.pop("schema_name", None) if schema_name is not None: logger.warning( ...
[ "def get_engine(db_credentials):\n\n url = 'postgresql://{user}:{passwd}@{host}:{port}/{db}'.format(\n user=db_credentials['user'], passwd=db_credentials['pwd'], host=db_credentials['host'], \n port=db_credentials['port'], db=db_credentials['db'])\n engine = create_engine(url, pool_size = 50)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For every metric in a set of Metrics to resolve, obtains necessary metric keyword arguments and builds bundles of the metrics into one large query dictionary so that they are all executed simultaneously. Will fail if bundling the metrics together is not possible.
def resolve_metric_bundle( self, metric_fn_bundle: Iterable[Tuple[MetricConfiguration, Any, dict, dict]], ) -> dict: resolved_metrics = dict() # We need a different query for each domain (where clause). queries: Dict[Tuple, dict] = dict() for ( metric_to_...
[ "def resolve_metric_bundle(\n self,\n metric_fn_bundle: Iterable[MetricComputationConfiguration],\n ) -> Dict[Tuple[str, str, str], MetricValue]:\n resolved_metrics: Dict[Tuple[str, str, str], MetricValue] = {}\n\n res: List[pyspark.Row]\n\n aggregates: Dict[Tuple[str, str, str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the values in the named column to the given date_format, and split on that
def _split_on_converted_datetime( self, table_name: str, column_name: str, batch_identifiers: dict, date_format_string: str = "%Y-%m-%d", ): return ( sa.func.strftime( date_format_string, sa.column(column_name), ...
[ "def split_date(X, date_column):\r\n X.copy()\r\n X[date_column] = pd.to_datetime(X[date_column])\r\n X['Month'] = X[date_column].dt.month\r\n X['Day'] = X[date_column].dt.day\r\n X['Year'] = X[date_column].dt.year\r\n X = X.drop(columns=date_column)\r\n return X", "def split_on_converted_dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Divide the values in the named column by `divisor`, and split on that
def _split_on_divided_integer( self, table_name: str, column_name: str, divisor: int, batch_identifiers: dict ): return ( sa.cast(sa.column(column_name) / divisor, sa.Integer) == batch_identifiers[column_name] )
[ "def split_on_divided_integer(\n df, column_name: str, divisor: int, batch_identifiers: dict\n ):\n matching_divisor = batch_identifiers[column_name]\n res = (\n df.withColumn(\n \"div_temp\",\n (F.col(column_name) / divisor).cast(pyspark.types.Intege...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split on the hashed value of the named column
def _split_on_hashed_column( self, table_name: str, column_name: str, hash_digits: int, batch_identifiers: dict, ): return ( sa.func.right(sa.func.md5(sa.column(column_name)), hash_digits) == batch_identifiers[column_name] )
[ "def split_on_hashed_column(\n df,\n column_name: str,\n hash_digits: int,\n batch_identifiers: dict,\n hash_function_name: str = \"sha256\",\n ):\n try:\n getattr(hashlib, hash_function_name)\n except (TypeError, AttributeError):\n raise (\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take a random sample of rows, retaining proportion p
def _sample_using_random( self, p: float = 0.1, ): return sa.func.random() < p
[ "def sample(probs):\n\n probs = probs / probs.sum()\n return np.random.choice(np.arange(len(probs)), p=probs.flatten())", "def _sample_proportional(self): \n indices = []\n p_total = self.sum_tree.sum(0, len(self) - 1)\n segment = p_total / self.batch_size\n \n for i in r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the mod of named column, and only keep rows that match the given value
def _sample_using_mod( self, column_name, mod: int, value: int, ): return sa.column(column_name) % mod == value
[ "def filter_rows(col, value):\n\n def filterer(data):\n return data.loc[data[col] != value]\n\n return filterer", "def filter_column(df: pd.DataFrame, column_name: str) -> None:\n\n from ipywidgets import interact\n\n options = sorted(df[column_name].unique())\n interact(lambda value: df[df[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Match the values in the named column against value_list, and only keep the matches
def _sample_using_a_list( self, column_name: str, value_list: list, ): return sa.column(column_name).in_(value_list)
[ "def _filter_values(vals, vlist=None, must=False):\n\n if not vlist: # No value specified equals any value\n return vals\n\n if vals is None: # cannot iterate over None, return early\n return vals\n\n if isinstance(vlist, str):\n vlist = [vlist]\n\n res = []\n\n for val in vlis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
将指定的配置相关文件从 源目录 覆盖到 目标目录
def sync_configs(source_dir: str, target_dir: str): sync_config_list = [ # 配置文件 "config.toml", "config.toml.local", # 特定功能的开关 ".disable_pause_after_run", ".use_by_myself", "不查询活动.txt", ".no_message_box", # 缓存文件所在目录 ".db", # #...
[ "def _adapt_cfg(self, source_cfg, target_cfg, failures):\n if not os.path.exists(self.cfgroot):\n raise DistutilsModuleError('Missing mediadart configuration directory: %s' % self.cfgroot)\n tmpfilename = os.path.join(os.sep, 'tmp', uuid4().get_hex())\n tmpfile = open(tmpfilename, 'w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[0x58, 0x59, 0x01, 0x00, 0x00] => "0x58, 0x59, 0x01, 0x00, 0x00"
def bytes_arr_to_hex_str(bytes_arr: List[int]) -> str: return ", ".join("0x%02x" % b for b in bytes_arr)
[ "def upp_stringer(input_list): #input a characteristics list\r\n\toutput_list=[]\r\n\tfor item in input_list:\r\n\t\toutput_list.append(str(stellagama.pseudo_hex(item)))\r\n\treturn ''.join (output_list) #output a string\r", "def chrlist2hex(x):\n return ''.join(['%02X' % i for i in [ord(c) for c in x]])", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
"0x58, 0x59, 0x01, 0x00, 0x00" => [0x58, 0x59, 0x01, 0x00, 0x00]
def hex_str_to_bytes_arr(bytes_str: str) -> List[int]: return eval(f"[{bytes_str}]")
[ "def hex_to_byte_list(data: str) -> List[int]:\n return list(binascii.unhexlify(data))", "def hexstring_to_bytelist(hexstring):\n return [int(byte, 16) for byte in chunks(hexstring, 2)]", "def hex_list(self):\r\n return [''.join(['{:02X}'.format(b) for b in data]) for data in self.buffers()]", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load csv into data frame
def load_data(csv_path): df = pd.read_csv(csv_path) return df
[ "def load_data(csv):\n df = pd.read_csv(csv, sep=',', error_bad_lines=False)\n return df", "def _parse_csv(csv_file: str) -> pd.DataFrame:\n return pd.read_csv(csv_file, header=0)", "def _load_csv_into_df(csv_file: Any, csv_name: str) -> pd.DataFrame:\n try:\n df = pd.read_csv(csv_file, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
split survivals results out of df
def split_outcomes(df): outcomes = df['Survived'] df = df.drop('Survived', axis=1) return outcomes, df
[ "def split_trips(df):\n #df=df.sort_values(by=['tmstmp', 'pdist'])\n #df=df.set_index('tmstmp')\n #group_obj = df.groupby([df[\"des\"],df[\"pid\"],df[\"vid\"]])\n #list_trips=[] \n #diff_list=[]\n #final=[]\n #for group in group_obj:\n #list_trips.append(group[1])\n #for trip in list_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read schedule configuration from file and load the json.
def get_schedules(): path = config.get('schedule', 'paths', './schedule.json') with open(path) as schedule_file: return json.load(schedule_file)
[ "def load(self):\n if isfile(self.schedule_file):\n json_data = {}\n with open(self.schedule_file) as f:\n try:\n json_data = json.load(f)\n except Exception as e:\n LOG.error(e)\n current_time = time.time()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check all schedule configurations to start and stop instances
def schedule(): for profile in schedules['profiles']: instances = _get_instances(profile['instance_tags'], profile['region']) start_stop_instances(instances, profile['schedule']) reregister_elb_instances(profile)
[ "def start_stop_instances(instances, schedule):\n for reservation in instances:\n for instance in reservation.instances:\n region = instance.placement\n if instance.state == 'running' and _get_desired_state(schedule) == 'stop':\n print \"Should stop \" + instance.id + \".\"\n instance.st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get boto ec2 instance objects by provided tags
def _get_instances(instance_tags, region): return ec2_conn[region].get_all_instances(filters={"tag:Name": instance_tags})
[ "def get_instances_by_tags(self, tags):\n return self.get_only_instances(filters={'tag:{}'.format(key): val for key, val in tags.items()})", "def _aws_get_instance_by_tag(region, name, tag, raw):\n client = boto3.session.Session().client('ec2', region)\n matching_reservations = client.describe_instances(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start and stop the instances given a schedule
def start_stop_instances(instances, schedule): for reservation in instances: for instance in reservation.instances: region = instance.placement if instance.state == 'running' and _get_desired_state(schedule) == 'stop': print "Should stop " + instance.id + "." instance.stop() elif...
[ "def schedule():\n for profile in schedules['profiles']:\n instances = _get_instances(profile['instance_tags'], profile['region'])\n start_stop_instances(instances, profile['schedule'])\n reregister_elb_instances(profile)", "def stopSchedule(self):\n DPxStopDinSched()", "async def test_stop(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the desired state give a schedule
def _get_desired_state(schedule): current_hour = int(time.strftime("%H", time.gmtime())) current_week_day = time.strftime("%A", time.gmtime()).lower() start = schedule[current_week_day]['start'] stop = schedule[current_week_day]['stop'] state = 'stop' if current_hour >= start and current_hour < stop: s...
[ "def test_get_current_state(self):\n schedule = parser.parse_schedule(SCHEDULE)\n self.assertEqual(\"a\", schedule.get_current_state(dt(monday, '09:30')))\n self.assertEqual(\"c\", schedule.get_current_state(dt(monday, '08:30')))\n self.assertIsNone(schedule.get_current_state(dt(saturday...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ELB does not send health checks after stopping/starting the instance. This method reregister the instances in the profile ELB's to start sending health checks again.
def reregister_elb_instances(profile): if 'elb_names' in profile: conn = elb_conn[profile['region']] elbs = conn.get_all_load_balancers(profile['elb_names']) for elb in elbs: instance_ids = _get_instance_ids(elb.instances) print "Reregistering " + elb.name + " instances." try: co...
[ "def drain():\r\n ami = get_ami_metadata()\r\n instance_id = ami['instance-id']\r\n ec2_utils.RemoveELBInstance(env.region, instance_id, env.nodetype)\r\n fprint('Removed instance %s from %s load balancers' % (instance_id, env.nodetype))", "def schedule():\n for profile in schedules['profiles']:\n instanc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an array of boto.ec2.instances returns instance ids.
def _get_instance_ids(instances): instance_ids = [] for instance in instances: instance_ids.append(instance.id) return instance_ids
[ "def get_ids(self, instances):\n instance_ids = []\n for instance in instances:\n instance_ids.append(instance.id)\n return instance_ids", "def instance_ids_from_names(inst_names):\n ec2 = boto3.resource('ec2')\n instances = ec2.instances.filter(Filters=[{\n 'Name': 't...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ecrire une fonction qui renvoie True si le point (x, y) est dans le cercle de r et de centre (0, 0)
def dans_cercle(self, r, x, y): self.r_num(r) valid = (isinstance(x, int) or isinstance(x, float)) and \ (isinstance(y, int) or isinstance(y, float)) if valid: if sqrt(x**2+y**2)<self.r: return True else: return Fals...
[ "def in_circle(x0, y0, x, y, r):\n return ((x - x0) ** 2 + (y - y0) ** 2) <= (r ** 2)", "def check_inside_circle(x, y, x_c, y_c, r):\n return (x - x_c) * (x - x_c) + (y - y_c) * (y - y_c) < r * r", "def in_circles(x, y, r1, r2, x_center, y_center):\n x_dist = abs(x-x_center)\n y_dist = abs(y-y_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper to calculate the remaining calls to github.
async def remaining(github: GitHubAPI): try: result = await github.rate_limit() except GitHubAuthenticationException as exception: _LOGGER.error(f"GitHub authentication failed - {exception}") return None except BaseException as exception: # pylint: disable=broad-except _LOGG...
[ "def get_pullReq_commits(pullreq_url, user, passwd):\n \n #auth for 5000 request/h limitprint(\"\\nINPUT GITHUB AUTH TO GET BETTER REQUEST LIMIT\")\n if user=='' or passwd=='':\n user = input('username : ')\n passwd = input('passwd : ')\n\n #fetch 250 max commits\n pullReq_commits = g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display a coloured subtitle.
def subtitle(string): print("{}\n{}\n".format(bold(string), underline(string, "-")))
[ "def subtitle(self, txt):\n num = len(txt)\n ticks = \"-\" * num\n print(txt)\n print(ticks)", "def create_subtitle(self):\n label_subtitle = Label(self.frame, text=\"Projet Python 2020\", font=(\"Arial\", 25), bg='light blue',\n fg='white')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
timestamp of last message
def last_timestamp(self): return self._last_timestamp
[ "def getLastNotificationTime():", "def last_message(self):\n return self.messages[-1]", "def last_message(self):\n return self.messages[-1] if self.messages else None", "def get_last_timestamp(self):\n return self._frame_timestamp", "def recent_message(self):\n ordered_messages =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
dictionary of all information multiple messages (key is a string, value is a list of lists that contains the messages)
def msg_info_multiple_dict(self): return self._msg_info_multiple_dict
[ "def messages(self):\n return {}", "def _add_message_info_multiple(self, msg_info):\n if msg_info.key in self._msg_info_multiple_dict:\n if msg_info.is_continued:\n self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value)\n else:\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
list of all changed parameters (tuple of (timestamp, name, value))
def changed_parameters(self): return self._changed_parameters
[ "def parameters_changed(self):\n pass", "def list_value_changes(self, field_name):\n\n t = self.data['timestamp']\n x = self.data[field_name]\n indices = t != 0 # filter out 0 values\n t = t[indices]\n x = x[indices]\n if len(t) == 0: return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
dict of MessageLoggingTagged objects
def logged_messages_tagged(self): return self._logged_messages_tagged
[ "def tags_dict(self):\n return ({'name': 'tag', 'attrs': {'k': k, 'v': v}} for k, v in self.tags.items())", "def tag_dict(self):\n tag_dict = dict()\n for document in self.documents:\n for tag in document.tags:\n tag_type = tag['tag']\n tag_dic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if a file corruption got detected
def file_corruption(self): return self._file_corrupt
[ "def _check_packet_corruption(self, header):\n data_corrupt = False\n if header.msg_type == 0 or header.msg_size == 0 or header.msg_size > 10000:\n if not self._file_corrupt and self._debug:\n print('File corruption detected')\n data_corrupt = True\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if compat flag DEFAULT_PARAMETERS is set
def has_default_parameters(self): return self._compat_flags[0] & (0x1 << 0)
[ "def test_defaults(self):\n fparam = FParameter(POSITIONAL_ONLY)\n assert fparam.kind == POSITIONAL_ONLY\n for k, v in FPARAM_DEFAULTS.items():\n assert getattr(fparam, k) == v", "def params_optional(self) -> bool:\n result = True\n if self.no_params:\n # W...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a list of (timestamp, value) tuples, whenever the value changes. The first data point with nonzero timestamp is always included, messages with timestamp = 0 are ignored
def list_value_changes(self, field_name): t = self.data['timestamp'] x = self.data[field_name] indices = t != 0 # filter out 0 values t = t[indices] x = x[indices] if len(t) == 0: return [] ret = [(t[0], x[0])] indices = np...
[ "def get_timestamped_metric_values_as_strings(self):\n ret_list = []\n i = 0\n while i < len(self.__metric_value_list):\n ret_list.append(self.__metric_value_list[i].timestamp.strftime(\"%Y-%m-%d %H:%M:%S\") + \" \" +\n str(self.__metric_value_list[i].value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a _MessageParameterDefault object
def _add_parameter_default(self, msg_param): default_types = msg_param.default_types while default_types: # iterate over each bit def_type = default_types & (~default_types+1) default_types ^= def_type def_type -= 1 if def_type not in self._default_paramet...
[ "def add_default_params(self):\r\n self.params = class_from_string(\r\n BaseFramework._configuration._default_param_type\r\n )()", "def Params_defaultParams(): # real signature unknown; restored from __doc__\n pass", "def add_default_params(self, params):\n params['key'] = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a message info multiple to self._msg_info_multiple_dict
def _add_message_info_multiple(self, msg_info): if msg_info.key in self._msg_info_multiple_dict: if msg_info.is_continued: self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value) else: self._msg_info_multiple_dict[msg_info.key].append([msg_in...
[ "def msg_info_multiple_dict(self):\n return self._msg_info_multiple_dict", "def _add_info(self, msg, **kwargs):\n\n args, extensions = self._filter_args(msg, **kwargs)\n for key, val in args.items():\n setattr(msg, key, val)\n\n if extensions:\n if msg.extension_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read the file from a given location until the end of sync_byte sequence is found or an end condition is met(reached EOF or searched all last_n_bytes).
def _find_sync(self, last_n_bytes=-1): sync_seq_found = False initial_file_position = self._file_handle.tell() current_file_position = initial_file_position search_chunk_size = 512 # number of bytes that are searched at once if last_n_bytes != -1: current_file_posit...
[ "def _read_until(self, c, chunk_size=96):\n s = io.BytesIO()\n fp = self._fp\n eof = False\n\n while True:\n chunk = fp.read(chunk_size)\n\n if not chunk:\n # The end of the file was reached. We'll bail out of the loop\n # and return ev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check for data corruption based on an unknown message type in the header set _file_corrupt flag to true if a corrupt packet is found
def _check_packet_corruption(self, header): data_corrupt = False if header.msg_type == 0 or header.msg_size == 0 or header.msg_size > 10000: if not self._file_corrupt and self._debug: print('File corruption detected') data_corrupt = True self._file_cor...
[ "def corrupted(pkt):\r\n chk_arr = pkt[1:3]\r\n data = pkt[3:]\r\n chk = int.from_bytes(chk_arr, 'little', signed=False)\r\n return not verify_checksum(data, chk)", "def test_process_optional_header_data_bad_header_length(self):\n with self.assertRaises(ValueError):\n decoder.process...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an array attribute containing array attributes of integers. If the operand is already an array attribute, forwards it. Otherwise treats the operand as a list of attributes or integers, potentially interpserced, to create a new arrayofarray attribute. Expects the threadlocal MLIR context to have been set by the ...
def _get_int_int_array_attr( values: Optional[Union[ArrayAttr, Sequence[Union[ArrayAttr, IntOrAttrList]]]] ) -> ArrayAttr: if values is None: return ArrayAttr.get([]) if isinstance(values, ArrayAttr): return values if isinstance(values, list): v...
[ "def enableAttributeArray(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads\n pass", "def setAttributeArray(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads\n pass", "def _egl_convert_to_int_array(egl_attributes):\n at...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hierarchically cluster the expression profiles.
def cluster(eps, linkage='average'): # TODO: your code here # Start by creating leaves for all the profiles and computing Euclidean distances between each pair. nodes = [ExpressionHierarchicalClusterLeaf(ep) for ep in eps] distances = {} for i in range(len(nodes)): f...
[ "def cluster_profiles(self):\n return self._cluster_profiles", "def cluster_hierarchically(active_sites):\n\n # Fill in your code here!\n\n return []", "def cluster_hierarchically(active_sites):\n\n\n cls, sc = agglomerative(active_sites)\n\n return cls", "def clusterize(self):\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Routes related to metrics are delegated to OtterMetrics.
def metrics(self, request): return OtterMetrics(self.store).app.resource()
[ "def test_route_with_metrics(self, mocker):\n client = wsgi.application.test_client(mocker)\n\n url = '/metrics'\n\n response = client.get(url)\n\n assert response.status_code == 200", "def supported_metrics_route():\n\n return flask.render_template(\"supported_metrics.html\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert that creating an amendment statement with secured party and debtor edits worksa as expected.
def test_create_amendment_edit(session, client, jwt, description, data, sp_amend_id, debtor_amend_id): json_data = copy.deepcopy(data) if sp_amend_id is not None: json_data['addSecuredParties'][0]['amendPartyId'] = sp_amend_id else: del json_data['addSecuredParties'][0]['amendPartyId'] i...
[ "def test_approve_agreement(self):\n pass", "def test_update_tam_security_advisory(self):\n pass", "def test_add_an_acl_item_and_verify_is_preserve_on_the_ad_dataset():", "def test_patch_tam_security_advisory(self):\n pass", "def test_verify_that_user_can_add_new_claim():", "def test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert that a get amendment registration statement works as expected.
def test_get_amendment(session, client, jwt, desc, roles, status, has_account, reg_num, base_reg_num): current_app.config.update(AUTH_SVC_URL=MOCK_URL_NO_KEY) headers = None # setup if status == HTTPStatus.UNAUTHORIZED and desc.startswith('Report'): headers = create_header_account_report(jwt, ro...
[ "def test_get_registration_statements(self):\n pass", "def test_verify_that_user_can_add_new_claim():", "def test_create_amendment_edit(session, client, jwt, description, data, sp_amend_id, debtor_amend_id):\n json_data = copy.deepcopy(data)\n if sp_amend_id is not None:\n json_data['addSecu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert that setting the amendment change type from the amendment data works as expected.
def test_change_types(session, client, jwt, change_type, is_general_collateral): current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL) json_data = copy.deepcopy(AMENDMENT_STATEMENT) json_data['changeType'] = change_type json_data['debtorName']['businessName'] = 'TEST BUS 2 DEBTOR' del json_data['c...
[ "def test_update_note_type(self):\n pass", "def test_update_contribution_type(self):\n pass", "def test_change_asset_type_assignment_rule(self):\n pass", "def test_update_catering_type(self):\n pass", "def test_update_event_type(self):\n pass", "def test_update_concern_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a financing statement for testing.
def create_financing_test(session, client, jwt): statement = copy.deepcopy(FINANCING_STATEMENT) statement['debtors'][0]['businessName'] = 'TEST BUS 2 DEBTOR' statement['type'] = 'SA' del statement['createDateTime'] del statement['baseRegistrationNumber'] del statement['payment'] del statemen...
[ "def doctest_DKBCCCsvStatementParser():", "def test_transaction_management_statements(self):\n for script_pattern in (\n \"BEGIN TRANSACTION; %s; COMMIT;\",\n \"BEGIN; %s; END TRANSACTION;\",\n \"/* comment */BEGIN TRANSACTION; %s; /* comment */COMMIT;\",\n \"/* ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the properties homepage.
def test_properties_index(self): result = self.client.get('/') self.assertEqual(result.status, '200 OK') self.assertIn(b'Welcome', result.data)
[ "def test_property_page(self):\n self.property_page.proceed_to_property_page()\n\n \"\"\"Step2 - Check rooms section\n Exp2 - Property page opened \"\"\"\n self.property_page.check_rooms_section()\n\n \"\"\"Step3 - Check other section\n Exp3 - Each item works well \"\"\"\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the new offer creation page.
def test_offers_new(self): result = self.client.get('/offers_new') self.assertEqual(result.status, '200 OK') self.assertIn(b'Make an Offer', result.data)
[ "def test_submit_offer(self, mock_insert):\n result = self.client.post('offers_show', data=sample_form_data)\n\n # After submitting, should redirect to the offers_show page.\n self.assertEqual(result.status, '302 FOUND')\n mock_insert.assert_called_with(sample_offer)", "def test_offer_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test showing the page of all offers.
def test_offers_show_every(self): result = self.client.get('/offers_show_every') self.assertEqual(result.status, '200 OK') self.assertIn(b'Offers', result.data)
[ "def test_get_offers(self):\n pass", "def test_08_special_offers(self):\n # Navigate to the Special Offers page\n try:\n if self.globs['cn_mode']:\n CP.NavMenu.ExploreAndPlan(self.dr).open().specialoffers().click()\n else:\n CP.NavMenu.Thing...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test submitting a new offer. Entry point for route is called offers_show_all.
def test_submit_offer(self, mock_insert): result = self.client.post('offers_show', data=sample_form_data) # After submitting, should redirect to the offers_show page. self.assertEqual(result.status, '302 FOUND') mock_insert.assert_called_with(sample_offer)
[ "def test_offers_new(self):\n result = self.client.get('/offers_new')\n self.assertEqual(result.status, '200 OK')\n self.assertIn(b'Make an Offer', result.data)", "def test_offer_post(self):\n\n data = {\n \"item\": self.item_1.id,\n \"status\": \"PURCHASE\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test showing a single offer.
def test_show_offer(self, mock_find): mock_find.return_value = sample_offer result = self.client.get(f'/offers/{sample_offer_id}') self.assertEqual(result.status, '200 OK') self.assertIn(b'Description', result.data)
[ "def test_offers_show_every(self):\n result = self.client.get('/offers_show_every')\n self.assertEqual(result.status, '200 OK')\n self.assertIn(b'Offers', result.data)", "def test_show_offer_with_coupon_id(self):\n business = COUPON_FACTORY.create_coupon().offer.business\n busin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test rendering of the edit offer form.
def test_offers_edit(self, mock_find): mock_find.return_value = sample_offer result = self.client.get(f'/offers/{sample_offer_id}/edit') self.assertEqual(result.status, '200 OK') self.assertIn(b'Edit This Offer', result.data)
[ "def test_edit_offer(self, mock_find):\n mock_find.return_value = sample_offer\n\n result = self.client.get(f'/offers/{sample_offer_id}')\n self.assertEqual(result.status, '200 OK')\n self.assertIn(b'Description', result.data)", "def test_edit(self):\n # Test using the Trovebox ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test submitted an edited offer.
def test_edit_offer(self, mock_find): mock_find.return_value = sample_offer result = self.client.get(f'/offers/{sample_offer_id}') self.assertEqual(result.status, '200 OK') self.assertIn(b'Description', result.data)
[ "def test_offers_edit(self, mock_find):\n mock_find.return_value = sample_offer\n\n result = self.client.get(f'/offers/{sample_offer_id}/edit')\n self.assertEqual(result.status, '200 OK')\n self.assertIn(b'Edit This Offer', result.data)", "def test_submit_offer(self, mock_insert):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test deletion of an offer.
def test_offers_delete(self, mock_delete): form_data = {'_method': 'DELETE'} result = self.client.post(f'/offers/{sample_offer_id}/delete', data=form_data) self.assertEqual(result.status, '302 FOUND') mock_delete.assert_called_with({'_id': sample_offer_i...
[ "def test_offer_delete(self):\n\n data = {\n \"item\": self.item_2.id,\n \"status\": \"SELL\",\n \"entry_quantity\": 700,\n \"price\": Decimal(\"3222.23\"),\n }\n response = self.post_offer(data)\n\n url = reverse(\"offer-detail\", None, {respo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A helper routine for selectionSort which finds the index of the biggest value in data at the mark index or greater.
def _findMaxIndex(data, mark): # assume the maximum value is at initial mark position maxIndex = mark # loop over the remaining positions greater than the mark for mark in range(mark+1, len(data)): # if a bigger value is found, record its index if data[mark][1][2] > data[maxIndex][1][2]:...
[ "def index_largest(seq):\n assert len(seq) > 0\n x, greatest, index = len(seq), seq[0], 0\n for elem in range(1, x):\n if seq[elem] > greatest:\n greatest = seq[elem]\n index = elem\n return index", "def max_index(lst):\n mx = lst[0][0]\n mi = 0\n for i in range(l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform an inplace selection sort of data.
def selectionSort(data): for mark in range(len(data)-1): maxIndex = _findMaxIndex(data, mark) # swap the element at marker with the min index data[mark], data[maxIndex] = data[maxIndex], data[mark] return data
[ "def selectionsort(arr):\n for i in range(len(arr)):\n minindex = i\n for j in range(i, len(arr)):\n if arr[j] < arr[minindex]:\n minindex = j\n temp = arr[minindex]\n arr[minindex] = arr[i]\n arr[i] = temp\n return arr", "def selection_sort(items...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform crossover from p1, p2 into c1, c2. Note that we do not actually perform crossover. We build a model from all the parents. Then we sample the model to produce the children. This function is called self.pop_size / 2 times.
def crossover (self, p1, p2, p_pop, c1, c2, c_pop) : assert self.crossover_count < self.pop_size assert self.get_iteration () == self.last_gen self.parents.append (p1) self.parents.append (p2) self.crossover_count += 2 if self.crossover_count == self.pop_size : ...
[ "def _cross_parents(self):\n while len(self.children_population) < self.children_count:\n parent_1, parent_2 = random.sample(self.population, k=2)\n self.children_population.extend(self.crossover.cross(parent_1, parent_2))", "def _crossover(self, best_population, crossover, n_parents=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An opengraph description meta should be present if the person bio placeholder is set.
def test_templates_person_detail_open_graph_description_bio(self): person = PersonFactory() page = person.extended_object # Add a bio to a person placeholder = person.extended_object.placeholders.get(slot="bio") add_plugin( language="en", placeholder=plac...
[ "def test_templates_person_detail_meta_description_bio(self):\n person = PersonFactory()\n page = person.extended_object\n\n # Add a bio to a person\n placeholder = person.extended_object.placeholders.get(slot=\"bio\")\n add_plugin(\n language=\"en\",\n place...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The "Organizations" section should not be displayed when empty.
def test_templates_person_detail_organizations_empty(self): person = PersonFactory(should_publish=True) # The "organizations" section should not be present on the public page url = person.public_extension.extended_object.get_absolute_url() response = self.client.get(url) self.as...
[ "def organizations(self):\n self.elements('organizations')", "def display_org_with_default(self):\r\n if self.display_organization:\r\n return self.display_organization\r\n\r\n return self.org", "def test_organizations_list(self):\n pass", "def prepare_organizations(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The "maincontent" placeholder block should not be displayed on the public page when empty but only on the draft version for staff.
def test_templates_person_detail_maincontent_empty(self): person = PersonFactory(should_publish=True) # The "organizations" section should not be present on the public page url = person.public_extension.extended_object.get_absolute_url() response = self.client.get(url) self.asse...
[ "def test_templates_program_detail_cms_no_course(self):\n program = ProgramFactory(\n page_title=\"Preums\",\n fill_cover=True,\n fill_excerpt=True,\n fill_body=True,\n )\n page = program.extended_object\n\n # Publish the program and ensure the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }