query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
saves user dict in a json file for backup purposes.
def backup_users_dict(users_dict: dict) -> None: with open('users.json', 'w') as usrs: json.dump(users_dict, usrs)
[ "def save_user_db(file_path: str, user_db: dict) -> None:\n # In case directory is not yet existed.\n os.makedirs(os.path.dirname(file_path), exist_ok=True)\n\n with open(file_path, 'w') as f:\n print(f\"[I/O] Saving user data...{file_path}\")\n json.dump(user_db, f)", "def save(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Backups integer in a file
def backup_int_in_fname(num: int, file_name: str) -> None: with open(file_name, 'w') as fname: fname.write(str(num))
[ "def save_seq_count(file, seq_count):\n\n with open(file, \"w\") as f_out:\n f_out.write(f\"{seq_count}\")", "def save_id(statefile,id):\r\n last_id = get_last_id(statefile)\r\n\r\n if last_id < id:\r\n debug_print('Saving new ID %d to %s' % (id,statefile))\r\n f = open(statefile,'w'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Backups users_dict, start_idx and number of checked emails
def backup_all(users_dict: dict, start_idx: int, num_checked_emails: int)\ -> None: backup_users_dict(users_dict) backup_int_in_fname(start_idx, START_IDX_FNAME) backup_int_in_fname(num_checked_emails, CHECKED_EMAILS_FNAME)
[ "async def init_user_info_to_redis(self):\n step = 100\n times = 0\n while True:\n offset = step * times\n page_docs = await self.user_model.find_list().skip(offset).to_list(step)\n await self.add_user_info_to_redis(page_docs)\n await self.add_user_id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if program is connected to the internet
def connected_internet() -> bool: url = "http://www.google.com" timeout = 5 try: requests.get(url, timeout=timeout) return True except (requests.ConnectionError, requests.Timeout): print("\nError: No internet connection!\n") return False
[ "def check_internet_connection():\n logging.debug('Checking internet connection')\n try:\n urlopen(config.api_base_url,\n timeout=config.timeout_internet_connection)\n logging.debug('Connected to the internet')\n return True\n except URLError ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a state is not in the all_states_dict, it will retrive information of the state from api and add them to the dictionary.
def add_to_state_dict(all_states_dict: dict, state: str) -> None: if state not in all_states_dict: url = 'https://www.vaccinespotter.org/api/v0/states/' +\ f'{state}.json' all_states_dict[state] = get_json_dict(url)
[ "def __add_current_state_to_state_dict(self):\n board_fen = self.board_fen()\n if board_fen not in self.states:\n self.states[self.board_fen()] = GameState(self.board_array())", "def get_all(self) -> dict[str, Any]:\n return copy.copy(self._state)", "def load_state_dict(self, sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends unsubriction messages and updates users_dict accordingly
def remove_users(users_to_remove: list, users_dict: dict, end_of_service: str) -> None: for reciever in users_to_remove: if reciever in users_dict: send_message(reciever, 'Subscription expired\n', end_of_service, ...
[ "def update_users_data(self) -> None:\n users_utts = defaultdict(list)\n users_convos = defaultdict(list)\n\n for utt in self.iter_utterances():\n users_utts[utt.user].append(utt)\n\n for convo in self.iter_conversations():\n for utt in convo.iter_utterances():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the module checks. Validate `volumes` against defined rules.
def run(self, args, payload): if not payload.data or \ "RequestBody" not in payload.data or \ "HostConfig" not in payload.data["RequestBody"] or \ "Binds" not in payload.data["RequestBody"]["HostConfig"] or \ not payload.data["RequestBody"]["HostConfig"]["Bind...
[ "def validate_volumes(self, volumes):\n valid = True\n for volume in volumes:\n if not volume:\n # ignore when volume is ''\n continue\n src_path = volume.split(':', 1)[0]\n check = self.runner.validate_volume_source(src_path)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an ascii chart passing a list of tuples [('label', int)]
def chartify(title, data, auto=False): if auto == True: chart = '' graph = Pyasciigraph( line_length=8, min_graph_length=15, separator_length=2, titlebar='-', float_format='{0:.0f}' ) for line in graph.g...
[ "def draw_hkl(hkl):\n hkl_str= []\n for i in hkl:\n if i<0:\n label = str(int(-i))\n label = r\"$\\bar{\" + label + '}$'\n hkl_str.append(str(label))\n else:\n hkl_str.append(str(int(i)))\n\n return hkl_str", "def l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the first ICachableItem in the ICachableSource
def first(self): # we need to create a new object to insure we don't corrupt the generator count csvsource = CSVSource(self.source, self.factory, self.key()) try: item = csvsource.items().next() return item except StopIteration: return None
[ "def GetFirstVisibleItem(self):\r\n\r\n return self.GetNextVisible(self.GetRootItem())", "def _first_from_iterator(self):\n return next(iter(self))", "def GetFirstVisibleItem(self):\r\n\r\n id = self.GetRootItem()\r\n if not id:\r\n return id\r\n\r\n while id:\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the pose annotations as pickle files into the parent directory. A pickle file is created for each page in the flipbook with the name of the first image in the flipbook_page list as the base for the pickle file name.
def save_annotations(self): for fp in self.ris_widget.flipbook_pages: if len(fp) == 0: # skip empty flipbook pages continue annotations = getattr(fp, 'annotations', {}) pose = annotations.get('pose', (None, None)) if pose is not Non...
[ "def write_annotations(self):\n self.annotation_file.parent.mkdir(exist_ok=True, parents=True)\n self.annotation_file.write_bytes(pickle.dumps((self.annotations, self._timepoint_annotations)))", "def load_annotations(self):\n for fp in self.ris_widget.flipbook_pages:\n annotations ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads annotation metadata from a pickle file for each flipbook page.
def load_annotations(self): for fp in self.ris_widget.flipbook_pages: annotations = getattr(fp, 'annotations', {}) pose = annotations.get('pose') if pose in (None, (None, None)): annotation_path = pathlib.Path(fp[0].name).with_suffix('.pickle') ...
[ "def load_metadata_from_pickle(self):\n\n with open(self.data_folder_path + 'metadata.pickle', 'rb') as file_handle:\n self.metadata_dict = pickle.load(file_handle)", "def _load_annotations(self):\n if self._raw_annotations is not None:\n return self._raw_annotations\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sanitizes file list inputs This function checks that the input is a list of files and not a directory. If the input is a directory, then it returns a list of files in the directory which match the desired extension. This is to allow all functions which input filelists to be more flexible by accepting directories instea...
def enf_filelist(filelist, extension = None): new_filelist = None if isinstance(filelist, str): if os.path.isdir(filelist): new_filelist = list_files(False, filelist, False, False) elif os.path.isfile(filelist): new_filelist = [filelist] elif isinstance(filelist, ...
[ "def args_to_input_file_list(arg):\n # Check if the input file is a directory.\n if os.path.isdir(arg[0]):\n print \"Provided directory.\"\n file_list = [arg[0] + \"/\" + \n f for f in os.listdir(arg[0])]\n else:\n file_list = arg\n return file_list", "def clean_lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Outputs a for this set of choice fields. If an id was given to the field, it is applied to the (each item in the list will get an id of `$id_$i`).
def render(self): id_ = self.attrs.get('id') output = [] for i, choice in enumerate(self.choices): choice_value, choice_label = choice if isinstance(choice_label, (tuple, list)): attrs_plus = self.attrs.copy() if...
[ "def render(self):\n id_ = self.attrs.get('id')\n output = []\n for i, choice in enumerate(self.choices):\n w = self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, i)\n output.append(format_html(self.inner_html,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yields all "subwidgets" of this widget. Used only by RadioSelect to allow template access to individual buttons. Arguments are the same as for render().
def subwidgets(self, name, value, attrs=None, choices=()): yield SubWidget(self, name, value, attrs, choices)
[ "def __iter__(self):\n id_ = self.field.widget.attrs.get('id') or self.auto_id\n attrs = {'id': id_} if id_ else {}\n for subwidget in self.field.widget.subwidgets(self.html_name, self.value(), attrs):\n yield subwidget", "def subnotebook_get_widgets(self):\n logger.debug(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the Exception super class. A LicenseError may be thrown in any situation where the license utility is no longer able to function normally. Such a situation may be, for example, a cache miss or a connection timeout.
def __init__(self, message): self.message = LicenseError.ERROR + message super(LicenseError, self).__init__(self.message)
[ "def __init__(self, error_msg):\n super(ConnectionException, self).__init__(error_msg)", "def __init__(self, message, source=None):\n Exception.__init__(self, message)\n self.source = source", "def __init__(self, original_exception, request_args, request_kwargs):\n self.original_exce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if our categorical variable is outside the training range we should get an error
def test_check_X_categorical_prediction_exceeds_training(wage_X_y, wage_gam): X, y = wage_X_y # last feature is categorical gam = wage_gam # get edge knots for last feature eks = gam.edge_knots_[-1] # add 1 to all Xs, thus pushing some X past the max value X[:,-1] = eks[-1] + 1 with pyte...
[ "def _check_category(self):\n if self.category_num < 0:\n raise ValueError(\"category_num should be more than 0\")\n\n for var in self.cat_features:\n value_counts = len(np.unique(self.X[:, var]))\n if value_counts > self.category_num:\n self.more_value_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
y must be int or float, or we should get a value error
def test_check_y_not_int_not_float(wage_X_y, wage_gam): X, y = wage_X_y y_str = ['hi'] * len(y) with pytest.raises(ValueError): check_y(y_str, wage_gam.link, wage_gam.distribution)
[ "def test_check_y_TypeError_(self):\n self.assertRaisesRegex(\n ValueError,\n 'y must be >= 0',\n Rectangle,\n 4, 2, 0, -6, 12\n )", "def y(self, value):\n self.data_validator(\"y\", value)\n self.__y = value", "def _validate_y(self, y, sam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check_y will try to cast data to numerical types
def test_check_y_casts_to_numerical(wage_X_y, wage_gam): X, y = wage_X_y y = y.astype('object') y = check_y(y, wage_gam.link, wage_gam.distribution) assert y.dtype == 'float'
[ "def test_check_y_not_int_not_float(wage_X_y, wage_gam):\n X, y = wage_X_y\n y_str = ['hi'] * len(y)\n\n with pytest.raises(ValueError):\n check_y(y_str, wage_gam.link, wage_gam.distribution)", "def _validate_y(self, y, sample_weight=None):", "def test_correct_message_for_nonnumeric_y_data(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check_y expects a minimum number of samples
def test_check_y_not_min_samples(wage_X_y, wage_gam): X, y = wage_X_y with pytest.raises(ValueError): check_y(y, wage_gam.link, wage_gam.distribution, min_samples=len(y)+1, verbose=False)
[ "def _validate_y(self, y, sample_weight=None):", "def test_y_more_dim(self):\n qkclass = QuantumKernel(feature_map=self.feature_map, quantum_instance=self.qasm_simulator)\n\n with self.assertRaises(ValueError):\n _ = qkclass.evaluate(x_vec=self.sample_train, y_vec=self.sample_more_dim)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if you give labels outide of the links domain, check_y will raise an error
def test_check_y_not_in_domain_link(default_X_y, default_gam): X, y = default_X_y gam = default_gam with pytest.raises(ValueError): check_y(y + .1, default_gam.link, default_gam.distribution, verbose=False)
[ "def check_classification_targets(y):\n y_type = type_of_target(y, input_name=\"y\")\n if y_type not in [\n \"binary\",\n \"multiclass\",\n \"multiclass-multioutput\",\n \"multilabel-indicator\",\n \"multilabel-sequences\",\n ]:\n raise ValueError(\n f\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check_X accepts at most 2D inputs
def test_check_X_too_many_dims(): with pytest.raises(ValueError): check_X(np.ones((5,4,3)))
[ "def _check_input(self, X, Y):\n if not isinstance(X, np.ndarray):\n raise ValueError(\"Type of X must be numpy.ndarray. \" +\n \"Received type {}.\".format(type(X)))\n if not isinstance(Y, np.ndarray):\n raise ValueError(\"Type of Y must be numpy.ndarray. \" +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that an empty widget has height equal to 0.
def test_empty_widget_height(layout): l = layout() # Make sure this measurement does not depend on the width. assert l.get_content_height(Widget(), Size(80, 24), Size(80, 24), 24) == 0 assert l.get_content_height(Widget(), Size(80, 24), Size(80, 24), 20) == 0 assert l.get_content_height(Widget(), Si...
[ "def test_empty_widget_width(layout):\n l = layout()\n assert l.get_content_width(Widget(), Size(80, 24), Size(80, 24)) == 0", "def test_get_height_of_empty_tree(self):\n tree = BinarySearchTree()\n self.assertEqual(tree.get_height(), 0)", "def is_empty_layout(self) -> bool:\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that an empty widget has width equal to 0.
def test_empty_widget_width(layout): l = layout() assert l.get_content_width(Widget(), Size(80, 24), Size(80, 24)) == 0
[ "def test_empty_values_widget(self: TestCaseType):\n widget = self.model_field.formfield().widget\n for empty_value in self.model_field.empty_values:\n with self.subTest(value=empty_value):\n self.assertEqual(widget.format_value(empty_value), empty_value)", "def test_empty_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects to Covid Data API, fits Prophet model on top level of cases, and projects down to all 50 states.
def build_prophet_preds(data_url: str, changepoint_scale: float, holidays_scale: float, seasonality_scale: float, growth ='logistic') -> DataFrame: # read in the data df = pd.read_csv(data_url, parse_dates=['date'])...
[ "def get_new_modelling_data():\n # get latest epidemic data from OWID \n\n df = pd.read_json(requests.get(\"https://covid.ourworldindata.org/data/owid-covid-data.json\").content)\n data = pd.DataFrame(df[\"POL\"][\"data\"])\n\n # get latest government restriction data from Oxford tracker\n response =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DataSync Agent activation key during resource creation. Conflicts with `ip_address`. If an `ip_address` is provided instead, the provider will retrieve the `activation_key` as part of the resource creation.
def activation_key(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "activation_key")
[ "def _gen_activation_hash():\r\n # for now just cheat and generate an api key, that'll work for now\r\n return User.gen_api_key()", "def pre_instance_ip_create(self, resource_dict):\n pass", "def generate_activation_key(user):\n salt = hashlib.sha1(six.text_type(random.random())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The ARNs of the security groups used to protect your data transfer task subnets.
def security_group_arns(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: return pulumi.get(self, "security_group_arns")
[ "def security_group_arns(self) -> pulumi.Output[Optional[Sequence[str]]]:\n return pulumi.get(self, \"security_group_arns\")", "def subnet_arns(self) -> pulumi.Output[Optional[Sequence[str]]]:\n return pulumi.get(self, \"subnet_arns\")", "def subnet_arns(self) -> Optional[pulumi.Input[Sequence[pul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Amazon Resource Names (ARNs) of the subnets in which DataSync will create elastic network interfaces for each data transfer task.
def subnet_arns(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: return pulumi.get(self, "subnet_arns")
[ "def subnet_arns(self) -> pulumi.Output[Optional[Sequence[str]]]:\n return pulumi.get(self, \"subnet_arns\")", "def subnets(self) -> Sequence[str]:\n return pulumi.get(self, \"subnets\")", "def subnets(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:\n return pulumi.get(self, \"subnets\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The ID of the VPC (virtual private cloud) endpoint that the agent has access to.
def vpc_endpoint_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "vpc_endpoint_id")
[ "def vpc_endpoint_id(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"vpc_endpoint_id\")", "def endpoint_id(self) -> str:\n return pulumi.get(self, \"endpoint_id\")", "def vpc_id(self) -> str:\n return pulumi.get(self, \"vpc_id\")", "def client_vpn_endpoint_id(self) -> p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DataSync Agent activation key during resource creation. Conflicts with `ip_address`. If an `ip_address` is provided instead, the provider will retrieve the `activation_key` as part of the resource creation.
def activation_key(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "activation_key")
[ "def _gen_activation_hash():\r\n # for now just cheat and generate an api key, that'll work for now\r\n return User.gen_api_key()", "def pre_instance_ip_create(self, resource_dict):\n pass", "def generate_activation_key(user):\n salt = hashlib.sha1(six.text_type(random.random())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing Agent resource's state with the given name, id, and optional extra properties used to qualify the lookup.
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, activation_key: Optional[pulumi.Input[str]] = None, arn: Optional[pulumi.Input[str]] = None, ip_address: Optional[pulumi.Input[str]] = None, name: Opt...
[ "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n avatar_uri: Optional[pulumi.Input[str]] = None,\n default_language_code: Optional[pulumi.Input[str]] = None,\n description: Optional[pulumi.Input[str]] = No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The ARNs of the security groups used to protect your data transfer task subnets.
def security_group_arns(self) -> pulumi.Output[Optional[Sequence[str]]]: return pulumi.get(self, "security_group_arns")
[ "def security_group_arns(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:\n return pulumi.get(self, \"security_group_arns\")", "def subnet_arns(self) -> pulumi.Output[Optional[Sequence[str]]]:\n return pulumi.get(self, \"subnet_arns\")", "def subnet_arns(self) -> Optional[pulumi.Input...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Amazon Resource Names (ARNs) of the subnets in which DataSync will create elastic network interfaces for each data transfer task.
def subnet_arns(self) -> pulumi.Output[Optional[Sequence[str]]]: return pulumi.get(self, "subnet_arns")
[ "def subnet_arns(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:\n return pulumi.get(self, \"subnet_arns\")", "def subnets(self) -> Sequence[str]:\n return pulumi.get(self, \"subnets\")", "def subnets(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:\n return pulumi.get(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The ID of the VPC (virtual private cloud) endpoint that the agent has access to.
def vpc_endpoint_id(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "vpc_endpoint_id")
[ "def vpc_endpoint_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"vpc_endpoint_id\")", "def endpoint_id(self) -> str:\n return pulumi.get(self, \"endpoint_id\")", "def vpc_id(self) -> str:\n return pulumi.get(self, \"vpc_id\")", "def client_vpn_endpoint_id(self) -> pu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
saves a url to the name
def save_config(name, url): db = dbm.open(config_file, 'c') db[name] = url db.close()
[ "def save(self, url):\n self.database.insert({\n 'url': url,\n 'last_crawled': None,\n 'valid': True,\n 'sub_urls': [],\n })", "def saveUrl(url, short):\n\n with open(STORAGE_FILE, \"a+\") as file:\n file.write(urlTextFormat(url, short) + \"\\n\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes the name from configuration if name isnt there throughs a KeyError
def remove_config(name): db = dbm.open(config_file, 'c') del db[name] db.close()
[ "def remove_config(name):\n CONFIGS.pop(name, None)", "def test_config_remove(self):\n test_name = sys._getframe().f_code.co_name\n self.env.config.set('project', 'name', 'Test project')\n rv, output = self._execute('config remove project name')\n self.assertEqual(0, rv)\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receives observation and returns observations with shifted axis
def observation(self, obs): # import pdb;pdb.set_trace() return np.moveaxis(obs, 2, 0)
[ "def perfect_shift(y):\n return np.append([y[-1]],y[0:-1])", "def __shifted(self):\n ndarray = self.__tensor.detach().cpu().numpy()\n\n return torch.from_numpy(np.roll(ndarray, self.__distance, self.__axes)).to(self.__device)", "def shift(x, offset, dim, wrap, name=None):\n return ShiftOperati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add new observation to the bottom of the queue of observations
def observation(self, observation): # push backward all observations self.buffer[:-1] = self.buffer[1:] # add last observation to the end (similar to adding an item to a queue) self.buffer[-1] = observation return self.buffer
[ "def queue_append(self, object):\n self.queue.append(object)", "def enqueue(self, val):\n self.list.insert_last(val)", "def test_adding_item_to_queue():\n\n q = MyQueue()\n\n for i in range(5):\n q.add(i)\n\n assert q.new_top.peek().value == 4", "def add_last(self, data):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test urlpatterns is not empty.
def test_urls(): assert len(urlpatterns) > 0
[ "def test_number_urls(self):\n actual = len(urls.urlpatterns)\n expected = self.no_of_urls\n message = \\\n \"The no. of urlpatterns doesn't match the no. of test url_paths\"\n self.assertEqual(actual, expected, message)", "def validate_urlpattern_with_options(cls):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loads local user's Google Chrome URL istory
def load_chrome_urls(): #path to user's history database (Chrome) data_path = os.path.expanduser('~')+"/Library/Application Support/Google/Chrome/Default" files = os.listdir(data_path) history_db = os.path.join(data_path, 'history') #querying the db c = sqlite3.connect(history_db) cursor = c.cursor() select_sta...
[ "def open_chrome(url,chrome_path):\r\n webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path))\r\n webbrowser.get('chrome').open(url)", "def _set_url(self, full_url):\r\n self._chrome_driver.get(full_url)", "def getURL(self, url):\n \n if self.driver.current_url ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
process bpr state ready
def process_state_ready(self): try: notifier.DEBUG("{0} Processing State Ready".format(self.msg_type)) if FSwiftMLUtils.get_acm_version() >= 2016.4: ops_doc = FSwiftWriterUtils.CreateOperationsDocument(OperationsDocumentStatus.PENDING_GENERATION, ...
[ "def wait(self, state):\n pass", "def handle_ready(self):\r\n self._is_ready.set()", "def ready(self):\n self.update({self.STATE: self.STATE_READY})", "def check_ready(self):\n\n\t\tif len(self.ready) > 0 and len(self.running) == 0:\n\t\t\tself.running.append(self.ready[0])\n\t\t\tself.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
process bpr state swiftmsggenerated
def process_state_swiftmsggenerated(self): try: notifier.DEBUG("{0} Processing State SwiftMsgGenerated".format(self.msg_type)) self.acm_obj = FSwiftMLUtils.get_acm_object_from_bpr(self.business_process) carbon_copy_swift_path = getattr(self.fsec_lending_borrowing_out_msg_con...
[ "def process_state_ready(self):\n try:\n notifier.DEBUG(\"{0} Processing State Ready\".format(self.msg_type))\n if FSwiftMLUtils.get_acm_version() >= 2016.4:\n ops_doc = FSwiftWriterUtils.CreateOperationsDocument(OperationsDocumentStatus.PENDING_GENERATION,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a flattened dictionary of all default property assignments visible in the current scope that apply to the current component type.
def get_default_properties(self, comp_type): # type: (Type[comp.Component]) -> DefaultNSScope # Flatten out all the default assignments that apply to the current scope # This does not include any default assignments made within the current # scope, so exclude those. props = {} ...
[ "def get_default_properties(self, comp_type):\n # Flatten out all the default assignments that apply to the current scope\n # This does not include any default assignments made within the current\n # scope, so exclude those.\n props = {}\n for scope in self.default_property_ns_sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export all messages listed in the Locations view to an editor.
def export_locations_to_editor(): categories = {} # Get all messages msgs = GPS.Message.list() # Filter them and organize them by category and file for m in msgs: if m.get_flags() & 2: file = m.get_file() category = m.get_category() if category in cat...
[ "def show_messages(self):\n for msg in self.messages:\n print msg['text']", "def mailman_export_list(request):\n try:\n # Ignoring complexity of timezones because we just want a fuzzy range\n # that is limited to a recent window\n start_of_yesterday = datetime.today() - t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export the current contents of the Call Trees view to an editor.
def export_call_trees_to_editor(): def dump_tree_model(model, indent): values = [] if model: for row in model: first = row[0] if first == 'computing...': return [] if not row[1] or \ first.endswith(' ...
[ "def editor():\n pass", "def printEditor(self, editor):\n if editor:\n editor.printFile()\n else:\n return", "def newEditorView(self, fn, caller, filetype=\"\", indexes=None):\n editor, assembly = self.cloneEditor(caller, filetype, fn)\n \n self._addVi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns all foreign key related "Education" objects
def get_education(self): return self.education_set.all()
[ "def get_education(self):\n\t\treturn self.education_set.all()", "def _get_related_objects(self, assessment):\n url = \"/api/assessments/{}/related_objects\".format(assessment.id)\n return self.client.get(url).json", "def relations(self, edu_pairs):\n if not self.deptree:\n return [None ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns all foreign key related "Experience" objects
def get_experience(self): return self.experience_set.all()
[ "def get_experiences():\n return Experience.query.all()", "def get_experience(self):\n\t\treturn self.experience_set.all()", "def experiences(self):\n return self.client.call('GET',\n self.name + 'experiences')", "def getExperienceByRessource(self, ressourcePk):", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform effect when owner is given a stat mod
def onStatMod(self, owner, degree, messages): return degree
[ "async def mod_only(self, ctx, name: str):\r\n is_mod = False\r\n bypass = ctx.author.guild_permissions.manage_guild or ctx.author.id == 106429844627169280\r\n if ctx.guild.id == 113103747126747136:\r\n mod_role = 175657731426877440\r\n roles = [x.id for x in ctx.author.ro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a unique cache key for the Target. We include the Task source code so that code changes in the Task automatically cause a cache miss
def key(self): key = self.name if self.task: key += getsource(self.task.__class__) return hashlib.md5(key.encode()).hexdigest()
[ "def key_for(self, target_id, sources):\r\n sha = hashlib.sha1()\r\n actual_srcs = self._sources_hash(sha, sources)\r\n return CacheKey(target_id, sha.hexdigest(), len(actual_srcs), actual_srcs)", "def cache_key(self):\n return self.__class__.create_cache_key(self.key, **self.get_kwargs())", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the user's API key from the user record and stores in the API instance. This is done using a session authenticated with username and password, to avoid the user having to specify all three.
def _get_api_key(self): self.api.apikey = self.api.action.user_show(id=self.username)['apikey']
[ "def api_authentication():\r\n apikey = request.args.get('api_key', None)\r\n from flask import _request_ctx_stack\r\n if 'Authorization' in request.headers:\r\n apikey = request.headers.get('Authorization')\r\n if apikey:\r\n user = db.session.query(model.user.User...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the domain of the server URL for use in filename cache keys. This is used so that a single cache directory can be shared by multiple cached CKAN instances. (`urlparse` behaves inconsistently.)
def server_domain(self): url = self.api.address domain_start = url.find('://') + 3 if url.find('://') >= 0 else 0 domain_end = url.find(':', domain_start) if url.find(':', domain_start) >= 0 else \ url.find('/', domain_start) if url.find('/', domain_start) >= 0 else \ url...
[ "def get_domain():\n domain=\"\"\n for item in re.split(\"\\.\", env.host)[1:]:\n domain = domain + \".\" + item\n return domain.lstrip(\".\")", "def server_hostname():\n\n return urllib.parse.urlparse(request.url_root).hostname", "def getdomain(self):\n\n arUrl = self.url.split(\"/\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches for a Dataset by title. Used if Dataset title but not ID specified.
def find_package(self, package_title): metadata = self.get_ckan_metadata() results = [] for id, resource in metadata.items(): if resource['dataset']['title'] == package_title: results.append(resource['dataset']) return results[0] if len(results) == 1 else resu...
[ "def fetch_dataset(self, name_or_id):\n results = [y for x, y in self._data.datasets.items() if x.lower().startswith(name_or_id.lower())\n or (y.name and y.name.lower() == name_or_id.lower())]\n assert len(results) <= 1\n return first(results)", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches for a Resource by Resource name and optionally also containing Dataset title. Used if resource_id not specified.
def find_resource(self, resource_name, package_title=None): metadata = self.get_ckan_metadata() results = [] for id, resource in metadata.items(): if resource['name'] == resource_name: if package_title is None or resource['dataset']['title'] == package_title: ...
[ "def _FindResourceByName(\n self,\n resources: Dict[str, ComputeResource],\n name: str,\n zone: Optional[str] = None,\n region: Optional[str] = None\n ) -> ComputeResource:\n if zone and region:\n raise ValueError(\n 'The resource must be either zonal or regional: '\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete any cached resources that haven't been accessed for `self.cache_resources_for minutes`, or their custom expiry deadline. This is run each time a resource is downloaded. Nb. Cache pruning is done according to the current `self.cache_resources_for minutes` setting, rather than the setting when the resource was pre...
def _prune_cache(self): default_expiry = datetime.datetime.utcnow() - datetime.timedelta(minutes=self.cache_resources_for) for resource_id, resource in self.local_resource_status.items(): if 'cache_until' in resource: if datetime.datetime.utcnow() > resource['cache_until']: ...
[ "def _clean_cache(self):\r\n query = _AppEngineUtilities_Cache.all()\r\n query.filter('timeout < ', datetime.datetime.now())\r\n results = query.fetch(self.max_hits_to_clean)\r\n db.delete(results)\r\n #for result in results:\r\n # result.delete()\r", "def cache_clean(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the path of a local copy of a resource, downloading into the cache if necessary.
def get_resource(self, resource_id, cache_for=None): metadata = self.get_resource_metadata(resource_id) last_updated = self.get_resource_last_updated(resource_id) if metadata and last_updated > self.local_resource_status.get(resource_id, {})\ ...
[ "def local(self):\n if self.kind == \"file\":\n return self._path\n if self._local_path:\n return self._local_path\n\n dot = self._path.rfind(\".\")\n suffix = \"\" if dot == -1 else self._path[dot:]\n temp_file = tempfile.NamedTemporaryFile(suffix=suffix, de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new CKAN Resource with the metadata specified, maintaining a local cache.
def create_resource(self, **kwargs): results = self.api.action.resource_create(**kwargs) # TODO: use `results` rather than re-download, using an isolation layer to standardize the re-structure self.get_ckan_metadata(True) if 'id' in results: self._import_resource_to_cache(kwa...
[ "def create_metadata(self, resource, metadata):\n resp = requests.post(\n \"{}/api/node/{}/{}/metadata\".format(\n self.base_url, resource.UUID, resource.name\n ),\n data=metadata,\n )\n if resp.status_code != 200:\n raise requests.HTTP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates an existing CKAN Resource.
def update_resource(self, **kwargs): logging.warning('Updating a resource removes all existing data. ' 'If you wish to keep the existing data, use `CachedCKAN.patch_resource`.') results = self.api.action.resource_update(**kwargs) self.get_ckan_metadata(True) if 'u...
[ "def _update_resource(context, resource):\n api_url = urlparse.urljoin(context['site_url'], 'api/action')\n resource['last_modified'] = datetime.now().isoformat()\n post_data = json.dumps(resource)\n res = requests.post(\n api_url + '/resource_update', post_data,\n headers = {'Authorizatio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Irreversibly deletes a CKAN Resource.
def delete_resource(self, resource_id): results = self.api.action.resource_delete(id=resource_id) self.get_ckan_metadata(True) self._delete_cache(resource_id=resource_id) return results
[ "def remove(self):\n with CachedCKAN(**self.ckan_kwargs) as ckan:\n ckan.delete_resource(resource_id=self.resource_id)", "def delete(self, resource_id=None):\n\n if resource_id:\n db.resources.delete_one({\"_id\":resource_id})\n else:\n db.resources.delete_man...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes a resource permanently from CKAN and the local cache.
def remove(self): with CachedCKAN(**self.ckan_kwargs) as ckan: ckan.delete_resource(resource_id=self.resource_id)
[ "def delete_resource(self, resource_id):\n results = self.api.action.resource_delete(id=resource_id)\n self.get_ckan_metadata(True)\n self._delete_cache(resource_id=resource_id)\n return results", "def _delete_resource(self,metadata,permanent_delete=False):\n if self.archive:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares input features from California housing data set.
def preprocess_features(california_housing_dataframe): selected_features = california_housing_dataframe[ ["latitude", "longitude", "housing_median_age", "total_rooms", "total_bedrooms", "population", "households", "median_income"]] processed...
[ "def preprocess_features(california_housing_dataframe):\n selected_features = california_housing_dataframe[\n [\"latitude\",\n \"longitude\"]]\n # \"housing_median_age\",\n # \"total_rooms\",\n # \"total_bedrooms\",\n # \"population\",\n # \"households\",\n # \"median_income\"]]\n p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct the TensorFlow Feature Columns.
def construct_feature_columns(input_features): return set([tf.feature_column.numeric_column(my_feature) for my_feature in input_features])
[ "def construct_feature_columns():\n # There are 784 pixels in each image\n return set([tf.feature_column.numeric_column('pixels', shape=784)])", "def build_model_columns():\n # Continuous columns\n Open = tf.feature_column.numeric_column('Open')\n daily_returns = tf.feature_column.numeric_column('Daily')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
데이터 가져오기 및 전처리 코드로 돌아가서 버그가 있는지 확인 문제점을 찾아서 수정했으면 위의 latitude / longitude 도식화 셀을 다시 실행하여 타당성 검사 결과가 좋아졌는지 확인합니다. 여기에서 중요한 교훈을 얻을 수 있습니다. ML의 디버깅은 코드 디버깅이 아닌 데이터 디버깅인 경우가 많습니다. 데이터가 잘못되었다면 가장 발전한 최신 ML 코드라도 문제를 일으킬 수밖에 없습니다.
def work3(): features = ['latitude', 'longitude'] print(validation_examples[features]) print(training_examples[features]) # 데이터를 읽을 때 무작위로 섞는 부분을 살펴봅니다. # 학습 세트와 검증 세트를 만들 때 데이터를 무작위로 적절히 섞지 않으면, 데이터가 일정한 규칙으로 정렬된 경우 문제가 생길 수 있습니다. # 바로 이 문제가 발생한 것으로 생각됩니다. # 위도 경도가 각 head, tail 에서 가져온 거라 서로...
[ "def get_location():\n if 'name' in request.args:\n desc = request.args['name']\n else:\n return \"Error: No value for argument name \"\n if 'lat' in request.args:\n lat = request.args['lat']\n else:\n return \"Error: No value for argument latitude \"\n if 'long' in reques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that calling `music_tuple_generator()` returns an iterator over all tuples of the form (group, track_list, track).
def test_music_tuple_generator(self): group_config = { "name": "Group 1", "track_lists": [ {"name": "Track List 1", "shuffle": False, "tracks": ["track_1.mp3"]}, {"name": "Track List 2", "shuffle": False, "tracks": ["track_2.mp3", "track_3.mp3"]}, ...
[ "def test_yield_value(self):\n msg = 'Must be an iterable which yield analogy test data in order.'\n examples = (\n [\n [\n 'Taiwan',\n 'Taipei',\n 'Japan',\n 'Tokyo',\n 'capital',\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test ensures that `get_audio_stream()` uses `pafy` to obtain the best audio stream.
def test_get_audio_stream_uses_pafy(self, monkeypatch): pafy_mock = MagicMock() youtube_video_mock = MagicMock() audio_stream_mock = MagicMock() audio_stream_mock.url = "some-url" pafy_mock.new.return_value = youtube_video_mock youtube_video_mock.getbestaudio.return_value...
[ "def test_get_audio_stream_does_not_raise(self):\n youtube_url = \"https://www.youtube.com/watch?v=jIxas0a-KgM\"\n _ = utils.get_audio_stream(youtube_url)\n assert True # No error", "def test_get_stream(self):\n pass", "def test_alsa(self):\n report(_(\"Testing ALSA sound out...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test ensures that `pafy` and `youtubedl` do not raise any exceptions when getting the url of the audio stream.
def test_get_audio_stream_does_not_raise(self): youtube_url = "https://www.youtube.com/watch?v=jIxas0a-KgM" _ = utils.get_audio_stream(youtube_url) assert True # No error
[ "def test_get_audio_stream_uses_pafy(self, monkeypatch):\n pafy_mock = MagicMock()\n youtube_video_mock = MagicMock()\n audio_stream_mock = MagicMock()\n audio_stream_mock.url = \"some-url\"\n pafy_mock.new.return_value = youtube_video_mock\n youtube_video_mock.getbestaudio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a directory is specified at the MusicGroup level and not the TrackList level, return the MusicGroup directory (even if there is a default directory specified).
def test_get_track_list_root_directory_returns_group_directory(self, example_group): example_group.directory = "group/dir" example_track_list = example_group.track_lists[0] example_track_list.directory = None directory = utils.get_track_list_root_directory( group=example_grou...
[ "def test_get_track_list_root_directory_returns_track_list_directory(self, example_group):\n example_group.directory = \"group/dir\"\n example_track_list = example_group.track_lists[0]\n example_track_list.directory = \"track/list/dir\"\n directory = utils.get_track_list_root_directory(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a directory is specified at the TrackList, return it (even if there is a default directory and a MusicGroup directory specified).
def test_get_track_list_root_directory_returns_track_list_directory(self, example_group): example_group.directory = "group/dir" example_track_list = example_group.track_lists[0] example_track_list.directory = "track/list/dir" directory = utils.get_track_list_root_directory( g...
[ "def test_get_track_list_root_directory_returns_group_directory(self, example_group):\n example_group.directory = \"group/dir\"\n example_track_list = example_group.track_lists[0]\n example_track_list.directory = None\n directory = utils.get_track_list_root_directory(\n group=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If no directory is specified at all (neither the default, MusicGroup or TrackList level), then raise a ValueError.
def test_get_track_list_root_directory_raises_value_error_if_no_directory_on_any_level(self, example_group): example_group.directory = None example_track_list = example_group.track_lists[0] example_track_list.directory = None with pytest.raises(ValueError): utils.get_track_li...
[ "def test_get_track_path_raises_value_error_if_root_directory_unknown(self, example_group):\n example_group.directory = None\n track_list = example_group.track_lists[0]\n track_list.directory = None\n track = track_list.tracks[0]\n track.file = \"file.mp3\"\n with pytest.ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the `file` attribute of a `Track` is the link to a YouTube video, return the url of its audio stream.
def test_get_track_path_returns_audio_url_if_track_is_youtube_link(self, example_group, monkeypatch): track_list = example_group.track_lists[0] track = track_list.tracks[0] track.file = "https://www.youtube.com/watch?v=jIxas0a-KgM" get_audio_stream_mock = MagicMock(return_value="some-url...
[ "def youtube_link(self):\n return self.source_file.youtube_link", "def audio_url(self):\n\n self._audio_url = pykka.ThreadingFuture()\n\n def job():\n try:\n info = youtube_dl.YoutubeDL(\n {\n \"format\": \"bestaudio/best\",\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the `file` attribute of a `Track` is not the link to a YouTube video, return the file path. The file path consists of the root directory combined with the filename. If there is no root directory, raise a `ValueError`.
def test_get_track_path_raises_value_error_if_root_directory_unknown(self, example_group): example_group.directory = None track_list = example_group.track_lists[0] track_list.directory = None track = track_list.tracks[0] track.file = "file.mp3" with pytest.raises(ValueErr...
[ "def abs_path(filename: str) -> str:\n # get a list of the videos in this directory\n videos = list_videos()\n # iterate over the videos\n for video in videos:\n if filename in video:\n return video\n raise OSError('{} is not a valid file in the videos package'.format(filename))", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively build a list of all possible interlocked words based on t and s
def recursive_build_list(w, t, s): if len(t) == 0 and len(s) == 0: return [w] elif len(t) > 0 and len(s) > 0: return recursive_build_list(w+s[0], t, s[1:]) + recursive_build_list(w+t[0], t[1:], s) elif len(t) == 0: return recursive_build_list(w+s[0], t, s[1:]) else: re...
[ "def gen_all_strings(word):\n working_word = str(word)\n \n if not word:\n return ['']\n else:\n rest = working_word[1:] \n combination_list = gen_all_strings(rest)\n \n return_list = [] \n for aword in combination_list:\n low = insert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a list of words interlocked based on w and z
def merge_words(w, z): list_w = list(w) list_z = list(z) return recursive_build_list("", list_w, list_z)
[ "def populate_grid_with_words(words: list[str], grid: list[list[str]]) -> list[list[str]]:\n\t# HACK: need to think of a better algo to generate the words\n\tmask = generate_mask_from_grid(grid)\n\tshuffle(words)\n\twidth, height = len(grid), len(grid[0])\n\tattempts = 1000\n\tadded_words = []\n\n\tfor word in word...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of labels from the tasks.
def get_unique_label_list(self) -> List[str]: return self.tasks.get_label_list()
[ "def task_labels(self):\n return set([t.label for t in self.tasks])", "def scheduled_task_labels(self):\n tasks = self._get_decision_artifact('task-graph.json').values()\n return {t['label'] for t in tasks}", "def get_labels(self) -> List[str]:\n pass", "def target_task_labels(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of project names from the tasks.
def get_unique_project_list(self) -> List[str]: return self.tasks.get_project_list()
[ "def projectNames(self):\n names = []\n for project in self.projects:\n name = project.split('--')[0]\n if not name in names:\n names.append(name)\n return names", "def get_task_names(self):\n task_names = []\n\n tasks = self.get_tasks()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of due_date strings from the tasks.
def __get_unique_due_date_list(self) -> List[str]: return self.tasks.get_due_date_list()
[ "def due_tasks(ctx):\n api = ctx.obj['api']\n current_time_in_epoch = int(time.time()) * 1000.0\n due_tasks = [task for task in api().get_all_tasks()\n if current_time_in_epoch > task['dueDate'] and task['status'] != 'CHECKED']\n if not due_tasks:\n return\n else:\n prin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test basic Treant init
def test_init(self, treant, tmpdir): assert treant.name == self.treantname assert treant.location == tmpdir.strpath assert treant.treanttype == self.treanttype assert treant.abspath == (os.path.join(tmpdir.strpath, self.treantname) + os.sep)...
[ "def test_TangentSpace_init():\n TangentSpace(metric='riemann')", "def test_init(self):\n pass", "def test_constructor(self):\n\n treasure = TreasureGenerator(apl=10)\n self.assertTrue(treasure is not None)", "def test_init(small_bst):\n assert small_bst.root.val == 20", "def run_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the variety of ways we can generate a new Treant 1. ``Treant('treant')``, where 'treant' is not an existing file or directory path 2. ``Treant('treant')``, where 'treant' is an existing directory without Treant state files inside 3. ``Treant('/somedir/treant')``, where 'treant' is not an existing file or directory...
def test_gen_methods(self, tmpdir, treantclass): with tmpdir.as_cwd(): # 1 t1 = treantclass('newone') assert os.path.exists(t1.filepath) # 2 os.mkdir('another') t2 = treantclass('another') assert os.path.exists(t2.filepath) ...
[ "def test_noregen(self, tmpdir, treantclass):\n with tmpdir.as_cwd():\n # 1\n t1 = treantclass('newone')\n t2 = treantclass('newone', new=True)\n assert t1.uuid != t2.uuid\n\n with pytest.raises(dtr.treants.MultipleTreantsError):\n t3 = tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test a variety of ways that generation of a new Treant should fail. 1. `Treant('somedir/treant')` should raise `MultipleTreantsError` if more than one state file is in the given directory
def test_noregen(self, tmpdir, treantclass): with tmpdir.as_cwd(): # 1 t1 = treantclass('newone') t2 = treantclass('newone', new=True) assert t1.uuid != t2.uuid with pytest.raises(dtr.treants.MultipleTreantsError): t3 = treantclass('ne...
[ "def test_create_file_errors(self):\n\n # Ensure a file can't be written outside the build context.\n files_to_fail = ['../file', '../../file', 'wild/../../file']\n for file in files_to_fail:\n file_arg = {file: []}\n config = self._quick_test_cfg()\n config['bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the comparison of Treants when sorting
def test_cmp(self, tmpdir, treantclass): with tmpdir.as_cwd(): c1 = treantclass('a') c2 = treantclass('b') c3 = treantclass('c') assert sorted([c3, c2, c1]) == [c1, c2, c3] assert c1 <= c2 < c3 assert c3 >= c2 > c1
[ "def hasSortCriterion():", "def test_sorting_ascending_by_area():", "def test_sort_cost(self):\n l1 = self.create_landmark(name='Cheap Landmark', cost=1)\n l2 = self.create_landmark(name='Expensive Landmark', cost=60)\n self.assertEqual(sorted([l2, l1]), [l1, l2])", "def test_sorting_asce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setting a category to ``None`` should not change the value.
def test_None_no_change(self, treant): treant.categories['bark'] = 'smooth' treant.categories['bark'] = None assert treant.categories['bark'] == 'smooth' treant.categories.add(bark=None) assert treant.categories['bark'] == 'smooth'
[ "def RemoveCategory(self, category):", "def force_device_category(self, category_name, value):\r\n\t\t# Erase the exisiting categories if any\r\n\t\tself.categories = [c for c in self.categories if c.__class__.__name__ != category_name]\r\n\t\t# Add the new one\r\n\t\tself.add_category(category_name, value)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that a readonly Treant can be accessed, but not written to.
def test_treant_read_only(self, treant): c = dtr.treants.Treant(treant.filepath) assert '72' in c.tags with pytest.raises(OSError): c.tags.add('yet another')
[ "def test_data_read_only():\n t = Tree(None)\n with pytest.raises(AttributeError):\n t.data = 0", "def test_read_only_attribute(self):\n self.assertFalse(self.datastore.read_only)", "def test_get_node_state_readonly(self):\n pass", "def test_update_node_state_readonly(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that Group can access members when the Group is readonly.
def test_group_member_access(self, group): assert len(group.members) == 2
[ "def test_group_invite_only_access_allowed(self):\n group = Group.objects.create(name='test-group', invite_only=True)\n group.users.add(self.user)\n\n self.assertTrue(group.invite_only)\n self.assertTrue(group.is_accessible_by(self.user))\n self.assertFalse(group.is_accessible_by(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads file and adds users from info found therein.
def add_users_from_file(args): with open(args.users_from_file) as file: for line in file: name, email_address = line.split(',') add_user(name, email_address.strip().lower())
[ "def read_all():\n with open(User.get_users_path(), encoding='utf8') as file:\n for line in file:\n username, pw_hash, email, name, level = line.strip().split(';')\n level = int(level)\n user = User.from_file(username)\n# userfile = User....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the family id
def get_family_id(self): return self._family_id
[ "def family_id(self):\n\n return self._family_id", "def find_next_family_gramps_id(self):\n self.fmap_index, gid = self.__find_next_gramps_id(self.family_prefix,\n self.fmap_index, self.fid_trans)\n return gid", "def get_family_by_id(family_id):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a single child id
def add_child(self, child_id): self._children.append(child_id)
[ "def prepend_child(self, child):\n self.children.insert(0, child)\n child.parent = self\n return child.id", "def insert_child(self, child, index):\n self.children.insert(index, child)\n child.parent = self\n return child.id", "def insert(self, parent, name):\n pi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and return a listening TLS socket on a given address.
def create_listening_ssl_socket(address, certfile, keyfile): # check if 2 files exist. If not, raise exceptions if os.path.isfile(certfile) and os.path.isfile(keyfile): ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.options |= ( ssl.OP_NO_TLSv1 | s...
[ "def ssl_listener(address, certificate, private_key):\r\n warnings.warn(\"\"\"eventlet.api.ssl_listener is deprecated. Please use eventlet.wrap_ssl(eventlet.listen()) instead.\"\"\",\r\n DeprecationWarning, stacklevel=2)\r\n from eventlet import util\r\n import socket\r\n\r\n socket = util.wrap_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the loss weights for the given mode. The weights are normalized to sum to one.
def get_loss_weights(n: int, mode: Optional[str]) -> np.ndarray: # Construct the weights if mode is None or not isinstance(mode, str): weights = np.ones(shape=(n, )) elif mode.lower() == 'linear': weights = np.linspace(start=1, stop=n, num=n, endpoint=True) elif mode.lower() == 'quadrati...
[ "def get_loss_and_weights(model_cfg, device=torch.device(\"cuda\")):\n # Get the global weighting policy\n w_policy = model_cfg.get(\"weighting_policy\", \"static\")\n if not w_policy in [\"static\", \"dynamic\"]:\n raise ValueError(\"[Error] Not supported weighting policy.\")\n \n loss_func =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL.
def rasterize(vertices: type_alias.TensorLike, triangles: type_alias.TensorLike, view_projection_matrices: type_alias.TensorLike, image_size: Tuple[int, int], enable_cull_face: bool, num_layers: int, name: str = "rasterization_backend_r...
[ "def rasterize(self):\n\n for primitive in self._scene:\n bbox = primitive[\"bounding_box\"]\n # Loop through all pixels\n # You MUST use bounding boxes in order to speed up this loop\n for w in range(bbox[0][0], bbox[1][0]):\n x = w + 0.5\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The username gets added to the requestContext when the authorizer runs.
def get_username(request: Request) -> str: return request.scope["aws.event"]["requestContext"]["authorizer"]["username"]
[ "def get_username(self, request):\r\n try:\r\n return request.user.username\r\n except AttributeError:\r\n return ''", "def auth_username(self, auth_username):\n\n self._auth_username = auth_username", "def setAuthUserName(name):", "def get_serializer_context(self):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator that validates incoming requests using the provided swagger spec
def swagger_validate(f): @wraps(f) def swagger_validated_function(*args, **kwargs): converted_uri = request.path # convert /pet/mypetsid to /pet/{petId} for key, value in request.view_args.items(): target = '{{{0}}}'.format(key) converted_uri = converted_uri.repla...
[ "def validate_with(schema):\n def decorator(f):\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n if not (request.json or request.data or request.form):\n flask_restful.abort(400, message='Validation error.',\n errors=['No data ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A version of the standard mock_open that only mocks when filepattern matches the given pattern.
def fp_mock_open(filepattern='.*', **kwargs): mo_obj = mock_open(**kwargs) filepattern = filepattern.rstrip("$") + '$' # capture open() in a closure now before any patching can happen real_open = open def new_call(filename, *args, **kwargs): if not re.match(filepattern, filename): ...
[ "def mock_open(filename, contents=None, complain=True):\n open_files = set()\n def mock_file(*args):\n if args[0] == filename:\n f = io.StringIO(contents)\n f.name = filename\n else:\n mocked_file.stop()\n f = open(*args)\n mocked_file.start...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Twolayer NPTN as described in the paper. out_channels and num_transforms refer to the first layer only.
def two_layer_nptn(x, num_classes=10, out_channels=48, num_transforms=1): with tf.variable_scope('nptn_1'): x = nptn_layer(x, 3, 3, out_channels, num_transforms) x = tf.layers.batch_normalization(x) x = parametric_relu(x) x = tf.layers.max_pooling2d(x, (2, 2), 2) with tf.variabl...
[ "def create_output_layer(n):\n output_layer = nest.Create(\"iaf_psc_alpha\", n, params=iaf_params)\n # Create Output spike detector\n spike_detectors = nest.Create(\"spike_detector\", n, params={\"withtime\": True})\n nest.Connect(output_layer, spike_detectors, \"one_to_one\")\n return output_layer, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The ShuffleBag constructor accepts an arbitrary number of parameters. Initialize the ShuffleBag by providing tuples of itemscount's. Each itemcount tuple represents an item we want to
def __init__(self, *args): self.bag = [] # Each item in 'args' is a tuple, we can assign each item in # the tuple directly to a variable name in our loop. Here we # assign the first item in each tuple to the variable named # 'item' and we assign the second item in each tuple to ...
[ "def baskets(items, count):\n _baskets = [[] for _ in range(count)]\n for i, item in enumerate(items):\n _baskets[i % count].append(item)\n return list(filter(None, _baskets))", "def __init__(self,\n capacity: int,\n prices: List[int],\n weights: Lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the next random item from our bag Automatically reshuffles once all previously randomized items have been selected from.
def next(self): # The contents of self.bag have already been randomized so the # next item is always the item at our current position. next_item = self.bag[self.pos] # Each time an item is selected we decrement our position # until we finally arrive back at the beginning of the ...
[ "def next(self):\r\n items = self.items\r\n if items:\r\n if self.random:\r\n n = len(items)\r\n if self.repeat:\r\n n = (n + 1) // 2\r\n i = randrange(n)\r\n else:\r\n i = 0\r\n item = item...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a route in csv file
def deleteroute(self, new_route): route_key = new_route.replace('-', ',') error, exists, message, code, lines = self.selectroute(route_key) if error or not exists: return False, message, code else: error, message, code = self.commandroute('Delete', lines, route_ke...
[ "def delete_record(self):\n self.display_all_records()\n temp = []\n row = input(\"Enter the student name you would like to delete: \")\n with open('student.csv', 'r', newline='') as file:\n reader = csv.reader(file)\n fileTitles = next(reader)\n for i in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A utility method for parsing token keyword arguments.
def token_kwargs(bits, parser, support_legacy=False): if not bits: return {} match = kwarg_re.match(bits[0]) kwarg_format = match and match.group(1) if not kwarg_format: if not support_legacy: return {} if len(bits) < 3 or bits[1] != 'as': return {} k...
[ "def token_kwargs(bits, parser):\r\n if not bits:\r\n return {}\r\n kwargs = SortedDict()\r\n while bits:\r\n match = kwarg_re.match(bits[0])\r\n if not match or not match.group(1):\r\n return kwargs\r\n key, value = match.groups()\r\n del bits[:1]\r\n k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses bits for template tag helpers (simple_tag, include_tag and assignment_tag), in particular by detecting syntax errors and by extracting positional and keyword arguments.
def parse_bits(parser, bits, params, varargs, varkw, defaults, takes_context, name): if takes_context: if params[0] == 'context': params = params[1:] else: raise TemplateSyntaxError( "'%s' is decorated with takes_context=True so it must " ...
[ "def parse_bits(parser, bits, params, varargs, varkw, defaults,\n kwonly, kwonly_defaults, takes_context, name):\n # 如果使用 simple_tag 装饰器注册 tag 的处理函数时,提供了 takes_context=True 参数\n # 则必须保证 处理函数的第一个入口参数名必须是 context\n if takes_context:\n if params[0] == 'context':\n params = para...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request package lists from the storage service. Package lists will contain details of the AIPs that we want to download.
def package_lists_request(self, apiUrl, timestamp, packages_directory): META = "meta" NEXT = "next" LIMIT = "limit" COUNT = "total_count" IN_PROGRESS = "IN PROGRESS" ( base_url, request_url_without_api_key, request_url, ) = format_api_url_with_limit_offset(apiUrl) ...
[ "def _cmd_list(client: ADBClient, package: Optional[str] = None, **kwargs):\n result = client.shell(\n \"cmd package list packages\",\n **extends_extra_arguments(f\"{package if package else ''}\", **kwargs),\n )\n if result.is_ok() and result.output():\n return _parse_packages(result.o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request METS XML file from the storage service and parse. Download a METS file from an AIP that is stored in the storage service and then parse the results into the AIPscan database. This function relies on being able to use metsreaderwriter which is the primary object we will be passing about.
def get_mets( package_uuid, relative_path_to_mets, api_url, timestamp_str, package_list_no, storage_service_id, storage_location_id, origin_pipeline_id, fetch_job_id, ): download_file = download_mets( api_url, package_uuid, relative_path_to_mets, timestamp_str, package_li...
[ "def download_mets(\n api_url, package_uuid, relative_path_to_mets, timestamp, package_list_no\n):\n\n # Request the METS file.\n mets_response = requests.get(\n get_mets_url(api_url, package_uuid, relative_path_to_mets)\n )\n\n # Create a directory to download the METS to.\n numbered_subdi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract a set of ngrams from a list of integers.
def create_ngram_set(input_list, ngram_value=2): return set(zip(*[input_list[i:] for i in range(ngram_value)]))
[ "def create_ngram_set(input_list, ngram_value=2):\n return set(zip(*[input_list[i:] for i in range(ngram_value)]))", "def find_ngrams(input_list, n, **kwargs):\n del kwargs\n result = []\n for ngram in zip(*[input_list[i:] for i in range(n)]):\n result.append(\" \".join(ngram))\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Augment the input list of list (sequences) by appending ngrams values.
def add_ngram(sequences, token_indice, ngram_range=2): new_sequences = [] for input_list in sequences: new_list = input_list[:] for ngram_value in range(2, ngram_range + 1): for i in range(len(new_list) - ngram_value + 1): ngram = tuple(new_list[i:i + ngram_value]) ...
[ "def add_ngram(sequences, token_indice, ngram_range=2):\n new_sequences = []\n for input_list in sequences:\n new_list = input_list[:]\n for ngram_value in range(2, ngram_range + 1):\n for i in range(len(new_list) - ngram_value + 1):\n ngram = tu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }