query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Creates a default .pypirc file. | def generate_pypirc(username, password):
rc = get_pypirc_path()
f = open(rc, 'w')
try:
f.write(DEFAULT_PYPIRC % (username, password))
finally:
f.close()
try:
os.chmod(rc, 0600)
except OSError:
# should do something better here
pass | [
"def generate_pypirc(self, pypirc):\n\n out = \"\"\"[distutils]\nindex-servers =\n \"\"\"\n out += '\\n '.join(pypirc.keys())\n out += '\\n'\n\n for index_server, properties in pypirc.items():\n out += '\\n[%s]\\n' % (index_server)\n for k, v in properties.ite... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper function around the refactor() class which performs the conversions on a list of python files. Invoke 2to3 on a list of Python files. The files should all come from the build area, as the modification is done inplace. | def run_2to3(files, doctests_only=False, fixer_names=None, options=None,
explicit=None):
#if not files:
# return
# Make this class local, to delay import of 2to3
from lib2to3.refactor import get_fixers_from_package, RefactoringTool
... | [
"def _refactor_2to3(self, path):\n # self.logger.debug('Refactoring: %s' % path)\n source, encoding = self.refactoring_tool._read_python_source(path)\n\n source += '\\n' # Silence certain parse errors.\n tree = self.refactoring_tool.refactor_string(source, path)\n return str(tree)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Issues a call to util.run_2to3. | def run_2to3(self, files, doctests_only=False):
return run_2to3(files, doctests_only, self.fixer_names,
self.options, self.explicit) | [
"def run_2to3(files, doctests_only=False, fixer_names=None, options=None,\n explicit=None):\n\n #if not files:\n # return\n\n # Make this class local, to delay import of 2to3\n from lib2to3.refactor import get_fixers_from_package, Refacto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ищет неточные рифмы через фонетические пары self.similarEnds | def approximateRhymes(self, word1, word2):
for (end1, end2) in self.similarEnds:
if len(word1) != len(end1) and len(word2) != len(end2):
if word1.endswith(end1) and word2.endswith(end2) and word1[-len(end1) - 1] == word2[-len(end2) - 1]:
return True
i... | [
"def test_custom_sentence_ending_markers(self):\n instance = hasami.Hasami(sentence_ending_markers='.,')\n self.assertEqual([\n 'これが最初の文です.',\n 'これは二番目の文です,',\n 'これが最後の文です。'\n ], instance.segment_sentences('これが最初の文です.これは二番目の文です,これが最後の文です。'))",
"def _similar(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This verifies a vote input is in the allowable range | def voteCheck(number):
if number >= MIN_VOTES and number <= MAX_VOTES:
return True
else:
return False
number = input("\n\tEnter votes: ") | [
"def can_vote(age):\n return age >= 18",
"def isRangeValid(self) -> bool:\n ...",
"def isInRange(val, minv, maxv):\n\treturn val >= minv and val <= maxv",
"def _validate_val_range(self, proposal):\n val_range = proposal[\"value\"]\n if len(val_range) != 2:\n raise traitlets.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace the ``step()`` method of env with a tracing function that calls callbacks with an events time, priority, ID and its instance just before it is processed. | def trace(self): # noqa
# pylint: disable=protected-access,invalid-name
def get_wrapper(env_step):
"""Generate the wrapper for env.step()."""
@wraps(env_step)
def tracing_step(): # noqa
"""Call *__monitor* for the next event if one exist before
... | [
"def tracing_step(): # noqa\n if len(self.__env._queue) > 0:\n t, prio, eid, event = self.__env._queue[0]\n self.__monitor(t, prio, eid, event)\n return env_step()",
"def _timestep_before_hook(self, *args, **kwargs):\n pass",
"def add_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call __monitor for the next event if one exist before calling ``env.step()``. | def tracing_step(): # noqa
if len(self.__env._queue) > 0:
t, prio, eid, event = self.__env._queue[0]
self.__monitor(t, prio, eid, event)
return env_step() | [
"def trace(self): # noqa\n\n # pylint: disable=protected-access,invalid-name\n def get_wrapper(env_step):\n \"\"\"Generate the wrapper for env.step().\"\"\"\n @wraps(env_step)\n def tracing_step(): # noqa\n \"\"\"Call *__monitor* for the next event if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set MHCI Database directory path | def __setMHCI_DB_Path(self, mhcidb_dirname):
if not hasattr(self, "mhcIdb_path") or self.mhcIdb_path is None:
cwd = self.getCWD()
pre_dir, after = cwd.split(mhcidb_dirname)
self.mhcIdb_path = self.joinPath(pre_dir,mhcidb_dirname )
print(("# MHCIDB workding path: ... | [
"def set_db_file():\n\n return os.path.join(db_path, db_file)",
"def set_database_path(dbfolder):\n try:\n d = get_config()\n except IOError:\n d = configparser.ConfigParser()\n d['planet4_db'] = {}\n d['planet4_db']['path'] = dbfolder\n with configpath.open('w') as f:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set MHCIDB working directory path and there existing data | def setMHCIDBPath(self, mhcidb_dirname="MHCIDB", data_dir="existing_data"):
self.__setMHCI_DB_Path(mhcidb_dirname)
self.mhcIdb_existing_data_path = self.joinPath(self.mhcIdb_path, data_dir)
self.mhcIdb_hla_path = self.joinPath(self.mhcIdb_existing_data_path, "hla" )
self.mhcIdb_pdb_path ... | [
"def __setMHCI_DB_Path(self, mhcidb_dirname):\n if not hasattr(self, \"mhcIdb_path\") or self.mhcIdb_path is None:\n cwd = self.getCWD() \n pre_dir, after = cwd.split(mhcidb_dirname)\n self.mhcIdb_path = self.joinPath(pre_dir,mhcidb_dirname )\n print((\"# MHCIDB wo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the path of the file contains the alinged protein seqeuences of HLA gene A, B and C | def get_hla_aligned_seq_fp(self):
fn_aln = "ClassI_prot.txt"
return self.joinPath(self.mhcIdb_hla_path, fn_aln) | [
"def _get_path(self, protein_id: int):\n protein_name = self.files_refined[protein_id]\n path_protein = os.path.join(\n self.init_refined, protein_name, protein_name + \"_protein.pdb\"\n )\n path_ligand = os.path.join(\n self.init_refined, protein_name, protein_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets Driver's node list. | def set_nodes(self, nodes):
self._drv_nodes = nodes | [
"def set_node_list(self, node_ids: Tuple['NodeId', ...]) -> None:\n self._nodes = node_ids",
"def _set_node_lists(self, new):\n for edge in self.edges:\n edge._nodes = self.nodes",
"def nodes(self, nodes):\n self._nodes = nodes",
"def nodes(self, nodes):\n\n self._nodes ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Snapshot an image of the specified instance | def snapshot(self, context, instance, image_id, update_task_state):
raise NotImplementedError() | [
"def snapshot(self, context, instance, image_href):\r\n try:\r\n virt_dom = self._lookup_by_name(instance['name'])\r\n except exception.InstanceNotFound:\r\n raise exception.InstanceNotRunning()\r\n\r\n instance_disk = None\r\n if self._is_run_onebs(instance):\r\n instance_disk = os... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Power off the specified instance. | def power_off(self, instance, timeout=0, retry_interval=0):
azure_name = self._get_omni_name_from_instance(instance)
utils.stop_instance(self.compute_client, drv_conf.resource_group,
azure_name) | [
"def power_off(self, instance):\n Maas().node_stop(instance['uuid'])",
"def power_off(self, instance, node=None):\n if not node:\n node = _get_baremetal_node_by_instance_uuid(instance['uuid'])\n pm = get_power_manager(node=node, instance=instance)\n pm.deactivate_node()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Azure doesn't support pause and cannot save system state and hence we've implemented the closest functionality which is to poweroff the instance. | def pause(self, instance):
self.power_off(instance) | [
"def suspend(self, context, instance):\n LOG.info(\"Suspending instance %s\" % instance.uuid)\n self.power_off(instance)",
"def power_off():\n print(\"Powering down...\")",
"def pause(self):\r\n return self.vmrun('pause')",
"def test_poweroff_environment_from_suspended(skytap_suspe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Azure doesn't support suspend and cannot save system state and hence Azure doesn't support suspend and cannot save system state and hence we've implemented the closest functionality which is to poweroff the instance. | def suspend(self, context, instance):
LOG.info("Suspending instance %s" % instance.uuid)
self.power_off(instance) | [
"def power_off():\n print(\"Powering down...\")",
"def power_off(vm_object):\n raise NotARealImplementationError",
"def test_poweroff_environment_from_suspended(skytap_suspended):\n skytap_suspended.poweroff_environment()\n assert skytap_suspended.is_env_status(\"stopped\")",
"def pause(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Since Azure doesn't support resume and we cannot save system state, Since Azure doesn't support resume and we cannot save system state, we've implemented the closest functionality which is to power on the instance. | def resume(self, context, instance, network_info, block_device_info=None):
LOG.info("Resuming instance %s" % instance.uuid)
self.power_on(context, instance, network_info, block_device_info) | [
"def vm_power(self, name, action):\n if action not in [\"start\", \"stop\"]:\n raise OpenStackConnectorIntegrationTestSuiteException(f\"The requested action {action} is incorrect. Must be either start or stop\")\n \n logging.info(f\"Received the power change request ({action}) for th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return data about VM diagnostics. | def get_diagnostics(self, instance):
# Fake diagnostics
return {
'cpu0_time': 17300000000,
'memory': 524288,
'vda_errors': -1,
'vda_read': 262144,
'vda_read_req': 112,
'vda_write': 5778432,
'vda_write_req': 488,
... | [
"def diagnostics(self):\r\n # NB: should be not None for multiprocessing works\r\n return {}",
"def jvm_diagnostics(self):\n return self._jvm_diagnostics",
"def getDiagnostics(self):\n\n assert(self.enable_diagnostics)\n\n local_diag = self.fwd_app.getSolnDiagnostics()\n\n # commun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return usage info for volumes attached to vms on a given host. | def get_all_volume_usage(self, context, compute_host_bdms):
volusage = []
return volusage | [
"def get_volume_info(host, disk_object, dc_obj):\n host_resource = get_host_resource_by_name(host)\n\n vol_id = disk_object.get_image_id()\n sd_id = disk_object.get_storage_domains().get_storage_domain()[0].get_id()\n image_id = disk_object.get_id()\n sp_id = dc_obj.get_id()\n\n args = {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return Azure Host Status of name, ram, disk, network. | def get_host_stats(self, refresh=False):
stats = []
for nodename in self._drv_nodes:
host_status = self.host_status_base.copy()
host_status['hypervisor_hostname'] = nodename
host_status['host_hostname'] = nodename
host_status['host_name_label'] = nodename
... | [
"def get_host_stats(self, refresh=False):\n return self.host_status",
"def get_host_stats(self):\n status, data, errors, messages = self._make_get_request(CraftyAPIRoutes.HOST_STATS)\n \n if status == 200:\n return data\n elif status == 500:\n self._check_e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if inputs is video or not | def check_is_video(self, inputs):
if isinstance(inputs, list):
return True
if isinstance(inputs, np.ndarray) and len(inputs.shape) == 4:
return True
return False | [
"def __is_video_input(self):\n if self.__prediction_conf['input_type'].lower() == 'camera':\n return False\n elif self.__prediction_conf['input_type'].lower() == 'video':\n return True\n raise Exception(\"input_type should be set to Camera or Video in Configuration\")",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates the postfix expression 's'. | def eval_postfix(s):
stack = Stack()
s = s.split()
for i in s:
if operator(i) == False:
stack.push(int(i))
else:
b = stack.pop()
a = stack.pop()
result = evaluate(a, i, b)
stack.push(result)
return stack.pop() | [
"def eval_postfix(s):\n stack = Stack()\n for x in s.split(): # rozděl 's' dle mezer\n if x == '+':\n stack.push(stack.pop() + stack.pop())\n elif x == '-':\n stack.push(-stack.pop() + stack.pop())\n elif x == '*':\n stack.push(stack.pop() * stack.pop())\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funkcja otwiera bazę danych z podanej lokalizacji baza zapisana uprzednio za pomocą pickle | def otworz(plik,tryb):
with open(plik,tryb) as plik:
database = pickle.load(plik, encoding='utf-8')
print(f"znaleziono i otwarto bazę danych ({len(database)-1} transakcji)\n")
return database | [
"def test__pickle_unpickle(self):\n pass",
"def __restoreBackup(self):\n pass #FIXME!!!",
"def __makeBackup(self):\n pass #FIXME!!!",
"def test_backup_bin_list():\n\tlib.backup_and_restore(\n\t\tput_data,\n\t\tNone,\n\t\tlambda context: check_data(context, True, True, True, False, True, T... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide tests for request to retrieve all way`s Notification | def test_get_all(self):
expected_response = [
{
'id': 101,
'start_time': '2019-11-27',
'end_time': '2020-12-27',
'week_day': 1,
'time': datetime.time(1, 12, 38),
'way': 100
},
{
... | [
"def test_get_from_another_way(self):\n url = reverse('notification', kwargs={'way_id': 101, 'notification_id': self.notification.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 403)",
"def test_can_get_status_of_notification(self):\n res = self.client.g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide tests for request to retrieve non owner Notification instance. | def test_get_non_owner(self):
another_user = CustomUser(id=101, email='another_user@mail.com', is_active=True)
another_user.set_password('testpassword')
another_user.save()
self.client.login(email='another_user@mail.com', password='testpassword')
url = reverse('notification',
... | [
"def test_tenants_tenant_id_notifications_get(self):\n pass",
"def testSimulateNotificationRaces(self):\r\n notification = Notification(self._user.user_id, 100)\r\n notification.name = 'test'\r\n notification.timestamp = time.time()\r\n notification.sender_id = self._user.user_id\r\n notific... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide tests for request to retrieve Notification instance with another `way_id`. | def test_get_from_another_way(self):
url = reverse('notification', kwargs={'way_id': 101, 'notification_id': self.notification.id})
response = self.client.get(url)
self.assertEqual(response.status_code, 403) | [
"def test_post_wrong_way_id(self):\n data = {\n 'start_time': '2019-10-29',\n 'end_time': '2019-12-29',\n 'week_day': 6,\n 'time': '23:58:59'\n }\n url = reverse('notification', kwargs={'way_id': 908, 'notification_id': self.notification.id})\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that tests the success post request for creating notification. | def test_post_success(self):
data = {
'start_time': '2019-10-29',
'end_time': '2019-12-29',
'week_day': 6,
'time': '23:58:59'
}
expected_data = {
'way': 100,
'start_time': '2019-10-29',
'end_time': '2019-12-29'... | [
"def test_create_valid_submission(self):\n with self.client:\n # valid submission registration\n sub_response = register_ok_submission(self, self.token)\n response_data = json.loads(sub_response.data.decode())\n self.assertTrue(response_data['status']=='success')",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that tests unsuccessful post request for creating notification with invalid post data. | def test_post_invalid_data(self):
data = {
'week_day': 'd',
'time': 'd'
}
url = reverse('notification',
kwargs={'way_id': self.notification.way_id, 'notification_id': self.notification.id})
response = self.client.post(url, json.dumps(data, cl... | [
"def test_create_invalid_submission(self):\n with self.client:\n # invalid submission registration\n sub_response = register_illegal_submission(self, self.token)\n response_data = json.loads(sub_response.data.decode())\n self.assertTrue(response_data['errors']!=Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that tests unsuccessful post request with empty JSON data. | def test_post_empty_json(self):
data = {}
url = reverse('notification',
kwargs={'way_id': self.notification.way_id, 'notification_id': self.notification.id})
response = self.client.post(url, json.dumps(data, cls=DjangoJSONEncoder), content_type='application/json')
... | [
"def test_empty_post():\n response = app.test_client().post(\n \"/perform/simple\", content_type=\"application/json\",\n )\n assert response.status_code == 200\n assert response.json == {\"status\": \"OK\"}",
"def test_invalid_JSON_returns_error(self):\n\n response = self.client.post(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide tests post request for creating notification with another `way_id`. | def test_post_wrong_way_id(self):
data = {
'start_time': '2019-10-29',
'end_time': '2019-12-29',
'week_day': 6,
'time': '23:58:59'
}
url = reverse('notification', kwargs={'way_id': 908, 'notification_id': self.notification.id})
response = s... | [
"def test_post_success(self):\n\n data = {\n 'start_time': '2019-10-29',\n 'end_time': '2019-12-29',\n 'week_day': 6,\n 'time': '23:58:59'\n }\n\n expected_data = {\n 'way': 100,\n 'start_time': '2019-10-29',\n 'end_ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that test success put request for the updating Notification | def test_put_success(self):
data = {
'time': '23:58:53'
}
url = reverse('notification', kwargs={'way_id': self.notification.way_id, 'notification_id': self.notification.id})
response = self.client.put(url, json.dumps(data, cls=DjangoJSONEncoder), content_type='application/j... | [
"def test_put(self):\r\n response = requests.put(BASE + \"developer/1\", data={\"age\": 30})\r\n self.assertEqual(response.json(), {'id': 1, 'name': 'Henrique Nishi', \r\n 'gender': 'Male', 'age': 30, 'hobby': 'series', 'date_of_birth': '07/11/1992'})\r\n self.assertEqual(str(respo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that tests for request to update non owner Notification instance. | def test_put_non_owner(self):
another_user = CustomUser.objects.create(id=1067, email='another_user1@mail.com', is_active=True)
another_user.set_password('testpassword')
another_user.save()
self.client.login(email='another_user1@mail.com', password='testpassword')
data = {
... | [
"def testSimulateNotificationRaces(self):\r\n notification = Notification(self._user.user_id, 100)\r\n notification.name = 'test'\r\n notification.timestamp = time.time()\r\n notification.sender_id = self._user.user_id\r\n notification.sender_device_id = 1\r\n notification.badge = 0\r\n notific... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide tests post request for updating notification with another `way_id`. | def test_put_wrong_way_id(self):
data = {
'start_time': '2019-10-29',
'end_time': '2019-12-29',
'week_day': 6,
'time': '23:58:59'
}
url = reverse('notification', kwargs={'way_id': 543, 'notification_id': self.notification.id})
response = se... | [
"def test_post_wrong_way_id(self):\n data = {\n 'start_time': '2019-10-29',\n 'end_time': '2019-12-29',\n 'week_day': 6,\n 'time': '23:58:59'\n }\n url = reverse('notification', kwargs={'way_id': 908, 'notification_id': self.notification.id})\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide tests for request to delete Notification instance with another `way_id`. | def test_delete_another_way_id(self):
url = reverse('notification',
kwargs={'way_id': 101, 'notification_id': self.notification.id})
response = self.client.delete(url)
self.assertEqual(response.status_code, 403) | [
"def test_error_db_deleting(self):\n\n url = reverse('notification',\n kwargs={'way_id': self.notification.way_id, 'notification_id': self.notification.id})\n with mock.patch('notification.views.Notification.delete_by_id') as notification_delete:\n notification_delete.r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that tests for request to delete non owner Notification instance. | def test_delete_non_owner(self):
another_user = CustomUser.objects.create(id=134, email='another_user2@mail.com', is_active=True)
another_user.set_password('qwerty12345')
another_user.save()
self.client.login(email='another_user2@mail.com', password='qwerty12345')
url = reverse... | [
"def test_error_db_deleting(self):\n\n url = reverse('notification',\n kwargs={'way_id': self.notification.way_id, 'notification_id': self.notification.id})\n with mock.patch('notification.views.Notification.delete_by_id') as notification_delete:\n notification_delete.r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that tests unsuccessful delete request when db deleting is failed. | def test_error_db_deleting(self):
url = reverse('notification',
kwargs={'way_id': self.notification.way_id, 'notification_id': self.notification.id})
with mock.patch('notification.views.Notification.delete_by_id') as notification_delete:
notification_delete.return_valu... | [
"def test_validate_delete(client):\n response = client.delete('/user/1')\n assert response.status_code == 400\n assert response.json['message'] == INVALID_ACTION_MESSAGE",
"def test_handle_delete_lookup_error(self):\n self.db.query.return_value = []\n self.assertTupleEqual(self.testcommand.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get the coding of a text. text text to inspect (string) coding string | def get_coding(text):
for line in text.splitlines()[:2]:
result = CODING_RE.search(line)
if result:
return result.group(1)
return None | [
"def get_text_coding(self):\n return self.text_coding",
"def _get_code(self, *args, **kwargs):\r\n\r\n code_reg = re.search(r\"^\\[\\d+\\] \\S+?:\", self.text).group(0)\r\n code = re.sub(r\"^\\[\\d+\\]| |:\", \"\", code_reg)\r\n return code",
"def apply_coder(text, coder):\n\tans = [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to encode a text. text text to encode (string) orig_coding type of the original coding (string) encoded text and encoding | def encode(text, orig_coding):
if orig_coding == 'utf-8-bom':
return BOM_UTF8 + text.encode("utf-8"), 'utf-8-bom'
# Try declared coding spec
coding = get_coding(text)
if coding:
try:
return text.encode(coding), coding
except (UnicodeError, LookupError):
... | [
"def encode(self, text: str):\r\n\r\n encoding = ''\r\n\r\n #We concatenate the code of each letter of the text\r\n for a in text:\r\n encoding = encoding + self.binary_tree[0][a] \r\n return encoding",
"def apply_coder(text, coder):\n encoded_s = ''\n for s in text:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write 'text' to file ('filename') assuming 'encoding' Return (eventually new) encoding | def write(text, filename, encoding='utf-8', mode='wb'):
text, encoding = encode(text, encoding)
with open(filename, mode) as textfile:
textfile.write(text)
return encoding | [
"def write_to_txt(text, txt_file_path):\n text = text.encode(\"ascii\", \"ignore\").decode() # remove unicode characters\n with open(txt_file_path, \"wb\") as f:\n f.write(text)",
"def write_text(file, text):\n\n with open(file, \"w\") as fin:\n fin.write(text)",
"def _write_to_file(text... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write 'lines' to file ('filename') assuming 'encoding' Return (eventually new) encoding | def writelines(lines, filename, encoding='utf-8', mode='wb'):
return write(os.linesep.join(lines), filename, encoding, mode) | [
"def write_lines(lines,data_file):\n with codecs.open(data_file,'w',encoding='utf-8') as f:\n for line in lines:\n f.write(line)",
"def write_file(filename, content):\n codecs.open(filename, \"w\", encoding='utf-8').writelines(content)",
"def write_lines(self, lines, encoding='None', err... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read text from file ('filename') Return text and encoding | def read(filename, encoding='utf-8'):
text, encoding = decode( file(filename, 'rb').read() )
return text, encoding | [
"def _read(filename, encodings=['ascii', 'utf-8', 'utf-16', 'latin-1']):\n text = None\n\n for encoding in encodings:\n try:\n f = open(filename, encoding=encoding)\n text = f.read()\n f.close()\n except UnicodeDecodeError:\n f.close()\n except ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read lines from file ('filename') Return lines and encoding | def readlines(filename, encoding='utf-8'):
text, encoding = read(filename, encoding)
return text.split(os.linesep), encoding | [
"def i_get_unicode_lines(file_name, encoding='utf-8', **kwargs):\n buffering = kwargs.get('buffering', FILE_BUFFER_SIZE)\n read_file_kwargs = dict(buffering=buffering, encoding=encoding)\n if is_py3():\n stream = i_read_buffered_text_file(file_name, **read_file_kwargs)\n for line in stream:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validate the access keys for this tenant | def _ensure_tenant_and_validate(tenant_, access_key):
tenant_data = registry.TENANT_DATA_GATEWAY
tenant = tenant_data.tenant_by_name(tenant_)
if tenant is None:
raise TenantNotFoundError(
"Tenant not found error. tenant='{}', access_key='{}'".format(
tenant_, access_key))... | [
"def _validate_client_credentials(self):\r\n self._validate_access_credentials()",
"def _validate_access_credentials(self):\r\n if self.client_secret is None and \"HTTP_AUTHORIZATION\" in self.request.META:\r\n authorization = self.request.META[\"HTTP_AUTHORIZATION\"]\r\n auth_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validates access to the tenant REQUIRES that arg 0 of the calling function contains an object with the following fields (tenant (str), access_key(str)) | def access_key_and_tenant_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
tenant = _ensure_tenant_and_validate(args[0].tenant,
args[0].access_key)
kwargs['tenant'] = tenant
return f(*args, **kwargs)
return wrapper | [
"def _ensure_tenant_and_validate(tenant_, access_key):\n tenant_data = registry.TENANT_DATA_GATEWAY\n tenant = tenant_data.tenant_by_name(tenant_)\n if tenant is None:\n raise TenantNotFoundError(\n \"Tenant not found error. tenant='{}', access_key='{}'\".format(\n tenant_,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validates access to the bucket for the given fields. REQUIRES that arg 0 of the calling function contains an object with the following fields (tenant (str), access_key(str), bucket(str)) | def access_to_bucket_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
tenant = _ensure_tenant_and_validate(args[0].tenant,
args[0].access_key)
bucket = tenant.get_bucket(args[0].bucket)
kwargs['bucket'] = bucket
return f(*args, **k... | [
"def access_key_and_tenant_required(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n tenant = _ensure_tenant_and_validate(args[0].tenant,\n args[0].access_key)\n\n kwargs['tenant'] = tenant\n return f(*args, **kwargs)\n return wrapper",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> validate_n_digits()("") False >>> validate_n_digits()("a") False >>> validate_n_digits()("asdf") False >>> validate_n_digits()("asdfghj") False >>> validate_n_digits()("123") False >>> validate_n_digits()("1234") True >>> validate_n_digits()("1235678") False >>> validate_n_digits(n=9)("000000001") True >>> validate... | def validate_n_digits(n: int = 4) -> bool:
def func(s: str):
if len(s) != n:
return False
if not s.isdigit():
return False
return True
return func | [
"def validate_n_digits_range(min_val: int, max_val: int, n: int = 4) -> bool:\n def func(s: str):\n return validate_n_digits(n)(s) and min_val <= int(s) <= max_val\n return func",
"def test_isNoDigit_passDigit_returnValueTrue_ut(no_Digit: str):\n assert not no_Digit.isdigit()",
"def nhs_number_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> validate_n_digits_range(1920, 2002)("2002") True >>> validate_n_digits_range(1920, 2002)("2003") False | def validate_n_digits_range(min_val: int, max_val: int, n: int = 4) -> bool:
def func(s: str):
return validate_n_digits(n)(s) and min_val <= int(s) <= max_val
return func | [
"def validate_n_digits(n: int = 4) -> bool:\n def func(s: str):\n if len(s) != n:\n return False\n if not s.isdigit():\n return False\n return True\n return func",
"def is_valid_birth_number(birth_number: int):\n if birth_number in range(1, 1000):\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> validate_hgt("60in") True >>> validate_hgt("190cm") True >>> validate_hgt("190in") False >>> validate_hgt("190") False | def validate_hgt(hgt: str) -> bool:
if hgt[-2:] == 'cm':
return 150 <= int(hgt[:-2]) <= 193
if hgt[-2:] == 'in':
return 59 <= int(hgt[:-2]) <= 76
return False | [
"def valid_hgt(cls, hgt):\n check = re.search(r\"^(\\d+)(in|cm)$\", hgt)\n if not check:\n raise ValueError(f\"Invalid hgt {hgt}\")\n n, unit = check.groups()\n n = int(n)\n if unit == \"in\":\n if not (76 >= n >= 59):\n raise ValueError(\"Inva... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> validate_hcl("123abc") True >>> validate_hcl("123abz") False >>> validate_hcl("123abc") False >>> validate_hcl("000000") True >>> validate_hcl("999999") True >>> validate_hcl("aaaaaa") True >>> validate_hcl("ffffff") True | def validate_hcl(hcl: str) -> bool:
if len(hcl) != 7 or hcl[0] != '#':
return False
for x in hcl[1:]:
if x not in list(map(str, range(9 + 1))) + \
list(map(chr, range(ord('a'), ord('f') + 1))):
return False
return True | [
"def validate_hash(h):\n if len(h) not in (32, 40, 64, 128):\n return False\n\n return bool(re.match(\"[0-9a-fA-F]*$\", h))",
"def verify_input(input_hash):\n from re import match\n if len(input_hash) != 32:\n verification = False\n return verification\n else:\n if match... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> validate_ecl("brn") True >>> validate_ecl("wat") False | def validate_ecl(ecl: str) -> bool:
return ecl in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] | [
"def is_valid_ecl(eye_color):\n if eye_color in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']:\n return True\n else:\n return False",
"def _human_comp_str_is_valid(self, human_comp_str):\n return human_comp_str in ('h', 'c')",
"def es_cadena_valida(adn):\n for base in adn:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a list of vectors and returns their average | def compute_average(vec_list):
return np.sum(vec_list, axis = 0)/len(vec_list) | [
"def v_avg(vecs):\n xs = []\n ys = []\n\n for v in vecs:\n xs.append(v[0])\n ys.append(v[1])\n\n xresult = 0\n for x in xs:\n xresult += x\n\n yresult = 0\n for y in ys:\n yresult += y\n\n return xresult / len(xs), yresult / len(ys)",
"def vector_mean(vectors):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes a sentence2vece embedding for preprocessed user input. | def compute_user_input_embedding(txt, model):
embeddings = []
tokens = txt.split(" ")
for word in tokens:
embeddings.append(model.wv[word])
sentence_embedding = compute_average(embeddings)
return sentence_embedding | [
"def _add_pre_trained_embedding(self):\n\n if self.embedding_type['type'] == 'glove':\n self.logging.info('use pre-trained glove word2vec')\n # a. load pre trained glove\n GLOVE_DIR = '../data/glove_pretrained/glove.6B'\n glove_suffix_name = 'glove.6B.' + str(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the n most similar products for a given user input embedding. | def get_similar_products(user_input_emb, ref_catalog, n = 5):
sim_list = []
for i in range(len(ref_catalog)):
desc_id = ref_catalog.iloc[i]['id']
emb = ref_catalog.iloc[i]['desc_embedding']
cos_sim = compute_cosine_sim(emb,user_input_emb)
sim_list.append((desc_id, cos_sim))... | [
"def get_n_similarWord(self,words, n=5):\r\n\r\n w2v_model = Word2Vec.load(self.model_name)\r\n return w2v_model.wv.most_similar(words, topn=n)",
"def get_n_similarWord(self,words, n=5):\r\n\r\n ft_model = FastText.load(self.model_name)\r\n return ft_model.most_similar(words, topn=n)",
"def top_simi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes html tags from txt | def remove_html(txt):
TAG_RE = re.compile(r'<[^>]+>')
return TAG_RE.sub("", txt).strip() | [
"def remove_html_tags(text):\n print('VOU REMOVER AS TAGS DA STRING')\n clean = re.compile('<.*?>')\n print('',re.sub(clean, '', text))\n return re.sub(clean, '', text)",
"def remove_html_tags(text):\n\tclean = re.compile('<.*?>')\n\treturn re.sub(clean, '', text)",
"def remove_html_tags(self,text):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the goal weight question and save the user's answers | def return_goal_weight_text_save_weight(self, data_dict, id_user):
# get robot advice to user : defined this weight goal
actual_weight = data_dict.get("actual_weight")
if actual_weight is not False:
# if the user answered to the goal weight question
# the parser method r... | [
"def return_weekly_questions_save_weight(self, weekly_weight, id_user):\n # get data\n context = {}\n weighing_date = ResultsUser.objects.values_list(\"weighing_date\")\n last_weighing_date = weighing_date.filter(user=id_user).order_by(\"weighing_date\").last()[0]\n one_week_after... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save advices to user | def save_advices_to_user(self, user_answer_id, old_question_id, id_user):
# get data
id_advice = DiscussionSpace.objects.values_list("robot_advices"). \
filter(robot_question=old_question_id).get(user_answer=user_answer_id)[0]
# if the user's answer
# contains a robot advice... | [
"def add_advices_to_user(self, id_user):\n # get data\n advice_type_id = RobotAdviceType.objects.values_list(\"id\").get(type=\"default\")\n advices_id = RobotAdvices.objects.values_list(\"id\").filter(robot_advice_type=advice_type_id)\n\n # add new advices to user\n for advice_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return weekly question and save user's answer | def return_weekly_questions_save_weight(self, weekly_weight, id_user):
# get data
context = {}
weighing_date = ResultsUser.objects.values_list("weighing_date")
last_weighing_date = weighing_date.filter(user=id_user).order_by("weighing_date").last()[0]
one_week_after_weighing = la... | [
"def __Check_Weekly_Answer(self) -> None:\n while True:\n bar = INFO_MANAGE().Task_Bar\n if bar[5].Current_Score != bar[5].Day_Max_Score:\n if self.__answer_time[-1]:\n if time.time() - self.__answer_time[0] <= 10:\n continue\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add new robot advices to user | def add_advices_to_user(self, id_user):
# get data
advice_type_id = RobotAdviceType.objects.values_list("id").get(type="default")
advices_id = RobotAdvices.objects.values_list("id").filter(robot_advice_type=advice_type_id)
# add new advices to user
for advice_id in advices_id:
... | [
"def add_advice_to_user_created(cls, user, list_advice_id):\n for id_advice in list_advice_id:\n advice = RobotAdvices.objects.get(id=id_advice)\n AdvicesToUser.objects.create(user=user, advice=advice)",
"def save_advices_to_user(self, user_answer_id, old_question_id, id_user):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reads a slope text data file | def read_slope(fname):
# http://milford.nserl.purdue.edu/weppdocs/usersummary/HillSlopeData.html
meta = {}
OFEs = []
meta['fname'] = fname
meta['id'] = ''.join([L for L in fname if L in '0123456789'])
fid = open(fname, 'r')
lines = fid.readlines()
lines = [L for L in lines i... | [
"def read_xy(filename):\n data = []\n infile = open(filename)\n line = infile.readline()\n while line != '':\n try:\n cols = line.split()\n x = float(cols[0])\n y = float(cols[1])\n data.append([x, y])\n except ValueError:\n pass\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create index, extracting substrings of length 'ln' | def __init__(self, t, ln):
self.t = t
self.ln = ln
self.index = []
size = len(t)
for i in range(len(t) - ln + 1):
self.index.append((t[i:i + ln], i)) # add <substr, offset> pair
self.index.sort() # sort pairs | [
"def nindex(str_in, substr, nth):\n\n m_slice = str_in\n n = 0\n m_return = None\n while nth:\n try:\n n += m_slice.index(substr) + len(substr)\n m_slice = str_in[n:]\n nth -= 1\n except ValueError:\n break\n try:\n m_return = n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load classes for a given excel_data string, containing 3 columns on each line separated by tabs. Load the schedule to a global variable for later access. | def load_classes(excel_data, slot_count):
return True | [
"def load_class_list():\r\n try:\r\n firstLine = True #keeping track of the first line in the csv file (the header)\r\n index = 0\r\n if os.access(\"mySchedule.csv\", os.F_OK): #If the file exists\r\n f = open(\"mySchedule.csv\")\r\n for row in csv.reader(f):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the names of exams available to pick for a given slot_number Returns list of names of exams. | def get_potential_classes_for_slot(slot_number):
return ["econ", "biz", "wtf"] | [
"def get_slot_names(self, *args, **kwargs):\n return self._opt.get_slot_names(*args, **kwargs)",
"def select_part(parts, slot_num):\n available_parts = \\\n [key for key in sorted(parts.keys()) if parts[key].is_available]\n print(\"\\nAvailable parts:\")\n for i in range(len(available_parts)):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select a class_name for a certain slot_number. Class name is selected from one of get_potential_classes_for_slot(slot_number) Do the necessary manipulation | def select_class_for_slot(class_name, slot_number):
return True | [
"def get_potential_classes_for_slot(slot_number):\n return [\"econ\", \"biz\", \"wtf\"]",
"def visit_class_slot(self, cls: ClassDefinition, aliased_slot_name: str, slot: SlotDefinition) -> None:\n ...",
"def get_skill_class(cursor, _class):\n cursor.execute('SELECT id FROM classes WHERE temp_id = ?... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resets all made selection, returning to initial state | def reset_selections():
return True | [
"def Reset_Selection(self):\r\n #if previous selection\r\n if( self.selected != 0 ):\r\n self.canvas_one.delete( self.selected ) #remove bounding rectangle\r\n #return chosen node to branch_color\r\n self.canvas_one.itemconfig( self.selected_ls.line_handle , fill = self.br... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returs a list of all pandigital primes up to ``n``. | def pandigital_primes(n=10000000):
pri = [x for x in primes(n) if is_pandigital(x)]
return pri | [
"def generate_n_primes(n):\n primes = []",
"def primes(n):\n return [i for i in xrange(1, n + 1) if mr_prime(i)]",
"def make_primes(n):\n out_list = []\n for i in range(2, n):\n if is_prime(i):\n out_list.append(i)\n return out_list",
"def get_primes(n):\n primes = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the local code for a device using the EufyHome account's username and password. | def get_local_code(username: str, password: str, ip_address: str):
client_id = 'eufyhome-app'
client_secret = 'GQCpr9dSp3uQpsOMgJ4xQ'
login_payload = {'client_id': client_id, 'client_Secret': client_secret, 'email': username, 'password': password}
login_request = requests.post("https://home-api.eufylif... | [
"def GetUserCode(self, callback):\r\n def _OnGetDeviceCode(response):\r\n response_dict = www_util.ParseJSONResponse(response)\r\n self._device_code = response_dict.get('device_code')\r\n callback(response_dict.get('user_code'), response_dict.get('verification_url'))\r\n\r\n # Get a device code... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encrypt data using the Eufy AES key and IV. Handles padding to a 16 byte interval. | def _encrypt(data):
cipher = AES.new(bytes(_AES_KEY), AES.MODE_CBC, bytes(_AES_IV))
# Pad to 16 bytes for AES CBC
for i in range(16 - (len(data) % 16)):
data += b'\0'
return cipher.encrypt(data) | [
"def encrypt_aes_ecb(data, key):\r\n cipher = AES.new(key, AES.MODE_ECB)\r\n\r\n # Only pad the data if it isn't the size of the block\r\n if not len(data) % block_size == 0:\r\n ciphertext = cipher.encrypt(pad(data, AES.block_size))\r\n else:\r\n ciphertext = cipher.encrypt(data)\r\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compile the given mode and command into the bytes data sent to the RoboVac. | def _build_robovac_command(mode, command):
mcu_ota_header_0xa5 = 0xA5
cmd_data = (mode.value + command.value)
return bytes([mcu_ota_header_0xa5, mode.value, command.value, cmd_data, 0xFA]) | [
"def generateCommand(self, mode, cmdType, sessionTime, payload, pinCode):\n self.encodedSessionTime = self.getFourByteInt(0, self.encodeFourByteInt(sessionTime))\n commandPayloadLength = 16 + len(payload)\n commandPayload = bytearray()\n commandPayload.append(mode & 0xFF) # Start of pay... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a decrypted response into a Protobuf Local Server Message | def _parse_local_server_message_from_decrypted_response(decrypted_response):
# First 2 bytes indicate length of the actual data
length = struct.unpack("<H", decrypted_response[0:2])[0]
protobuf_data = decrypted_response[2:length + 2]
message = LocalServerInfo_pb2.LocalServerMessage()
... | [
"async def asymetric_decode():\n return {\"message\": decrypted}",
"def _parse_reply(self, msg_list): #{\n logger = self.logger\n\n if len(msg_list) < 4 or msg_list[0] != b'|':\n logger.error('bad reply: %r' % msg_list)\n return None\n\n msg_type = msg_list[2]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Connect to the RoboVac at the given IP and port | def connect(self) -> None:
self.s.connect((self.ip, self.port)) | [
"def _connect_to_server(self, host_ip, port):\n return 0",
"def connect(self):\n self._socket.connect((self._ip, self._port))",
"def connect(self, port):\n cmd = self.getSSHCommand() + \" \" + self.getUsername() + \"@\" + str(self.getIPAddress()) + \" -p \" + str(3000 + int(port)) \n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the status of the RoboVac device (battery level, mode, charging, etc). | def get_status(self) -> RobovacStatus:
message = self._build_get_device_status_user_data_message()
robovac_response = self._send_packet(message, True)
received_status_bytes = robovac_response.c.usr_data
received_status_ints = [x for x in received_status_bytes]
return RobovacStat... | [
"async def get_battery_status(self) -> models.KamereonVehicleBatteryStatusData:\n # await self.warn_on_method(\"get_battery_status\")\n response = await self.session.get_vehicle_data(\n account_id=self.account_id,\n vin=self.vin,\n endpoint=\"battery-status\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to start its autoclean programme. | def start_auto_clean(self):
command = _build_robovac_command(RobovacModes.WORK, RobovacCommands.AUTO_CLEAN)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def manual_start(self):\n self.manual_seqnum = 0\n return self.send(\"app_rc_start\")",
"def autonomous(self):\n \n self.__nt.putString('mode', 'auto')\n self.__nt.putBoolean('is_ds_attached', self.ds.isDSAttached())\n\n self._on_mode_enable_components()\n\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to start its spotclean programme. | def start_spot_clean(self):
command = _build_robovac_command(RobovacModes.WORK, RobovacCommands.SPOT_CLEAN)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def start_auto_clean(self):\n command = _build_robovac_command(RobovacModes.WORK, RobovacCommands.AUTO_CLEAN)\n message = self._build_command_user_data_message(command)\n\n self._send_packet(message, False)",
"def startRun(self):\r\n #Ask user for verification\r\n usrData = sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to start its edgeclean programme. | def start_edge_clean(self):
command = _build_robovac_command(RobovacModes.WORK, RobovacCommands.EDGE_CLEAN)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def start_auto_clean(self):\n command = _build_robovac_command(RobovacModes.WORK, RobovacCommands.AUTO_CLEAN)\n message = self._build_command_user_data_message(command)\n\n self._send_packet(message, False)",
"def estop(self):\n self.status_message = \"EMERGENCY STOP - Check Rexarm an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to clean a single room. | def start_single_room_clean(self):
command = _build_robovac_command(RobovacModes.WORK, RobovacCommands.SINGLE_ROOM_CLEAN)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def delete(self, room, bus):\n\t\treturn remove_bus(room, bus), 204",
"async def clear(self, ctx):\n member = self.guild.get_member(ctx.author.id)\n await self.update_schedule(member, \"CLEAR\")\n await ctx.send(f\"Hi {member.display_name}. Availability cleared.\")",
"async def clear(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to stop cleaning. The RoboVac will not return to its charging base. | def stop(self):
command = _build_robovac_command(RobovacModes.WORK, RobovacCommands.STOP_CLEAN)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def stopclean(self):\n raise Exception(\"Not implemented\")",
"def stop(self, force=False):\n pass",
"async def async_stop(self, **kwargs: Any) -> None:\n await self._vacuum_bot.execute_command(Clean(CleanAction.STOP))",
"def _gracefully_stop(self):\n pass",
"def stop(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start the 'find me' mode. The RoboVac will repeatedly play a chime. | def start_find_me(self):
command = _build_robovac_command(RobovacModes.FIND_ME, RobovacCommands.START_RING)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def main():\n global repeat\n regime = collect()\n start = int(raw_input(\"Which line of the exercise script would you like to begin with? \")) - 1\n regime = regime[start:]\n say(\"Ready?\")\n time.sleep(1)\n for exercise in regime:\n coach(exercise[:-1])\n while repeat:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop the 'find me' mode. | def stop_find_me(self):
command = _build_robovac_command(RobovacModes.FIND_ME, RobovacCommands.STOP_RING)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def stop_auto_search(self):\n if self._search_thread is not None:\n self._run_auto_search = False",
"def stop_searching(self):\n self.searching = False\n self.receive_msg(\"No one is online :(\", keyboard=True)",
"def ToggleFind(self):\n if self.search.IsShown():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to use the standard fan speed. | def use_normal_speed(self):
command = _build_robovac_command(RobovacModes.SET_SPEED, RobovacCommands.SLOW_SPEED)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def set_fan(self, fan):\n if fan == \"auto\":\n self.fan_speed = 0\n else:\n assert fan >= 0 and fan <= 3\n self.fan_speed = fan",
"async def set_fan_speed(self, fan_speed):\n await self._set_value(FUNCTION_FANSP, fan_speed)",
"def set_fan_mode(self, fan):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to use the maximum possible fan speed. | def use_max_speed(self):
command = _build_robovac_command(RobovacModes.SET_SPEED, RobovacCommands.FAST_SPEED)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def max_speed(self, value):\n self.__max_speed = value",
"def set_max_speed(self, value):\n if self.mot_type == 'ims':\n return self.put_par(\"max_speed\",value)\n elif self.mot_type == 'xps8p':\n print \"asked to set the max speed to %f but max speed is read only for %s motors\\n\" % (val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to move forward without vacuuming. | def go_forward(self):
command = _build_robovac_command(RobovacModes.GO_FORWARD, RobovacCommands.MOVE)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def move_forward():\n pass",
"def MoveFleet(self):\n if self.travel_time > 0:\n self.travel_time -= 1\n if self.travel_time == 0:\n self.arrived = True",
"def move_forward(self):\n self.at(at_pcmd, True, 0, -self.speed, 0, 0)",
"def go_backward(self):\n command = _build_robov... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to move backward without vacuuming. | def go_backward(self):
command = _build_robovac_command(RobovacModes.GO_BACKWARD, RobovacCommands.MOVE)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def move_back(self):\n\n # slowly drive backwards\n self.velocity = -1 * const.Driving.CAUTIOUS_VELOCITY\n self.angle = const.Driving.NEUTRAL_STEERING_ANGLE\n\n # drive as long there is enough space to the next vehicle or obstacle\n gap = self.formation.calc_gap()\n self.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the RoboVac to turn left without vacuuming. | def go_left(self):
command = _build_robovac_command(RobovacModes.GO_LEFT, RobovacCommands.MOVE)
message = self._build_command_user_data_message(command)
self._send_packet(message, False) | [
"def turn_left(self):\n pass",
"def left(self):\n self.counterUp(teamNumber = 1)",
"def turn_left(self):\n #Set servo\n PWM.set_duty_cycle(self.servo, SG90_LEFT)",
"def go_left(self):\r\n self.change_x = -6\r\n self.direction = \"L\"",
"def turn_left(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a packet to the RoboVac. This method handles all the required encryption. Will attempt to reconnect to the RoboVac if sending a packet fails. | def _send_packet(self,
packet: LocalServerInfo_pb2.LocalServerMessage,
receive: True) -> Union[None, LocalServerInfo_pb2.LocalServerMessage]:
raw_packet_data = packet.SerializeToString()
encrypted_packet_data = _encrypt(raw_packet_data)
try:
... | [
"def send(self, packet):\n pass",
"def send(self, packet):\n\n self.conn.send(packet)",
"def send(self, packet):\n\t\t# TODO change implementation...\n\t\tpass\n\t\t#send(packet, verbose=False)",
"def _send_packet(self, packet: bytes):\n self._transport.sendto(packet, self._caddr)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the edges of this tree. | def set_edges(self, edges):
assert len(edges) == self._num_edges
self._tree_grid = make_tree(edges) | [
"def set_edges(self, edges):\n self._tree.set_edges(edges)\n self._program = make_propagation_program(self._tree.tree_grid)",
"def edges(self, edges):\n\n self._edges = edges",
"def set_edges(self, edges):\n if (not isinstance(edges, None.__class__) and (edges.size != 0)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes an efficient schedule for message passing on a tree. | def make_propagation_schedule(grid, root=None):
if root is None:
root = find_center_of_tree(grid)
E = grid.shape[1]
V = 1 + E
neighbors = [set() for _ in range(V)]
edge_dict = {}
for e, v1, v2 in grid.T:
neighbors[v1].add(v2)
neighbors[v2].add(v1)
edge_dict[v1, v2... | [
"def algo_schedule():\n\talgo(node.id, node)\n\treactor.callLater(STEP_TIME, algo_schedule)",
"def _build_schedule_for_tree(self, current, parent, already_visited=None):\n # Keep track of already visited variables.\n if already_visited is None:\n already_visited = {current}\n else:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove edge at position e from tree and update data structures. | def remove_edge(self, e):
assert len(self.e2k) == self.VEK[1]
assert len(self.k2e) == self.VEK[1]
neighbors = self.neighbors
components = self.components
k = self.e2k.pop(e)
self.k2e.pop(k)
v1, v2 = self.grid[1:, k]
neighbors[v1].remove(v2)
neighbo... | [
"def remove_edge(self, e):\r\n for i in self.edges[e]:\r\n self.nodes[i] = tuple(d for d in self.nodes[i] if d != e)\r\n del self.edges[e]",
"def remove_edge(e, R):\n\tR.remove_edge(e[0], e[1])\n\tupdate_after_mod(e,R)",
"def remove_edge(self, edge: Edge) -> Edge:",
"def remove(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add edge k at location e and update data structures. | def add_edge(self, e, k):
assert len(self.e2k) == self.VEK[1] - 1
assert len(self.k2e) == self.VEK[1] - 1
v1, v2 = self.grid[1:, k]
assert self.components[v1] != self.components[v2]
self.k2e[k] = e
self.e2k[e] = k
self.neighbors[v1].add(v2)
self.neighbors[... | [
"def add_edge(self, e):\n a, b = e\n self[a][b] = e\n self[b][a] = e",
"def add_edge(self,e):\r\n\r\n self.edge_set.add(e)\r\n\r\n self.update_vertices()",
"def addEdge(self, e):\n v = e.either()\n w = e.other(v)\n self._validateVertex(v)\n self._validateVertex(w)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sample a random spanning tree of a dense weighted graph using MCMC. This uses Gibbs sampling on edges. Consider E undirected edges that can move around a graph of V=1+E vertices. The edges are constrained so that no two edges can span the same pair of vertices and so that the edges must form a spanning tree. To Gibbs s... | def sample_tree(grid, edge_logits, edges, steps=1):
logger.debug('sample_tree sampling a random spanning tree')
COUNTERS.sample_tree_calls += 1
if len(edges) <= 1:
return edges
tree = MutableTree(grid, edges)
V, E, K = tree.VEK
for step in range(steps):
for e in range(E):
... | [
"def gibbs_step():\n\n for ind in np.random.permutation(n_edges):\n sample_assignment(ind) # sample c\n sample_node_prob() # sample beta",
"def random_sample(G):\n E = collections.defaultdict(list) # to store the new sampled preference list\n for student in G.A:\n pref_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests GET method on google authenticator | def test_read_ga(self):
url = reverse('admin_google_authenticator')
data = {
}
self.client.force_authenticate(user=self.admin)
response = self.client.get(url, data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) | [
"def test_0040_registration_get(self):\n response = self.fetch(\n '/registration', method=\"GET\", follow_redirects=False\n )\n self.assertEqual(response.code, 200)",
"def test_GET(self):\n if not self.url:\n return\n response = self.client.get(self.url, {}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests PUT method on google authenticator | def test_update_ga(self):
url = reverse('admin_google_authenticator')
data = {
}
self.client.force_authenticate(user=self.admin)
response = self.client.put(url, data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) | [
"def test_PUT(self):\n if not self.url:\n return\n response = self.client.put(self.url, {}, format='json')\n self.assertIn(response.status_code, [status.HTTP_405_METHOD_NOT_ALLOWED,\n status.HTTP_401_UNAUTHORIZED])",
"def test_put_method(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests POST method on google authenticator | def test_create_ga(self):
url = reverse('admin_google_authenticator')
data = {
}
self.client.force_authenticate(user=self.admin)
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) | [
"def test_initiate_account_request_using_post(self):\n pass",
"def test_0050_registration_post_1(self):\n response = self.fetch(\n '/registration', method=\"POST\", follow_redirects=False,\n body=urlencode({'name':'anoop', 'email':'pqr@example.com',\n 'password':... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests DELETE method on ga without being an admin | def test_delete_ga_failure_no_admin(self):
url = reverse('admin_google_authenticator')
data = {
'google_authenticator_id': self.ga.id
}
self.client.force_authenticate(user=self.test_user_obj)
response = self.client.delete(url, data)
self.assertEqual(respon... | [
"def test_delete_ga_failure_no_ga_id(self):\n\n url = reverse('admin_google_authenticator')\n\n data = {\n }\n\n self.client.force_authenticate(user=self.admin)\n response = self.client.delete(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests DELETE method on ga without a ga id | def test_delete_ga_failure_no_ga_id(self):
url = reverse('admin_google_authenticator')
data = {
}
self.client.force_authenticate(user=self.admin)
response = self.client.delete(url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) | [
"def test_delete_ga_failure_ga_id_not_exist(self):\n\n url = reverse('admin_google_authenticator')\n\n data = {\n 'google_authenticator_id': '499d3c84-e8ae-4a6b-a4c2-43c79beb069a'\n }\n\n self.client.force_authenticate(user=self.admin)\n response = self.client.delete(ur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests DELETE method on ga with a ga id that does not exist | def test_delete_ga_failure_ga_id_not_exist(self):
url = reverse('admin_google_authenticator')
data = {
'google_authenticator_id': '499d3c84-e8ae-4a6b-a4c2-43c79beb069a'
}
self.client.force_authenticate(user=self.admin)
response = self.client.delete(url, data)
... | [
"def test_delete_ga_failure_no_ga_id(self):\n\n url = reverse('admin_google_authenticator')\n\n data = {\n }\n\n self.client.force_authenticate(user=self.admin)\n response = self.client.delete(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a quaternion into euler angles (roll, pitch, yaw) roll is rotation around x in radians (counterclockwise) pitch is rotation around y in radians (counterclockwise) yaw is rotation around z in radians (counterclockwise) | def euler_from_quaternion(x, y, z, w):
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = math.asin(t2)
t... | [
"def euler_from_quaternion(quaternion):\n x=quaternion[\"im\"][0]\n y=quaternion[\"im\"][1]\n z=quaternion[\"im\"][2]\n w=quaternion[\"re\"]\n\n t0 = 2*(w*z + x*y)\n t1 = 1 - 2 * (x*x + y*y)\n t1 = w*w + x*x - y*y - z*z \n yaw = math.atan2(t0, t1)\n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
引数:リストのサイズ 変数:size, stack_list, count | def __init__(self, size):
self.size = size
self.stack_list = [None]*self.size
self.count = 0 | [
"def __init__(self, stack_size: int = 10):\n self.stack_size = stack_size\n self.arr = [None] * stack_size * 3\n self.bottoms = [i * stack_size for i in range(3)]\n self.tops = [i * stack_size for i in range(3)]",
"def size(self):\n return len(self.__stack)",
"def size(s): \n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create / get S3 bucket for tests | def s3_bucket(s3_resource, s3_client, account_id, boto_session):
region_name = boto_session.region_name
bucket_name = f"amazon-braket-sdk-integ-tests-{account_id}"
bucket = s3_resource.Bucket(bucket_name)
try:
# Determine if bucket exists
s3_client.head_bucket(Bucket=bucket_name)
e... | [
"def test_create_bucket(self):\n pass",
"def mock_s3_bucket():\n with moto.mock_s3():\n bucket_name = \"mock-bucket\"\n my_config = Config(region_name=\"us-east-1\")\n s3_client = boto3.client(\"s3\", config=my_config)\n s3_client.create_bucket(Bucket=bucket_name)\n yi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a dictionary with file attributes for FUSE. | def create_file_attributes(permissions, time, size):
return {
'st_mode': (stat.S_IFREG | permissions),
'st_ctime': time,
'st_mtime': time,
'st_atime': time,
'st_size': size,
'st_uid': os.getuid(),
'st_gid': os.getgid(),
'st_nlink': 1
} | [
"def _create_file_infos():\n d = {\n #'file_md5sum': None, # provided by AthFile.impl\n #'file_name': None, # ditto\n #'file_type': None, # ditto\n #'file_guid': None, # ditto\n \n 'nentries' : 0, # to handle empty files\n 'run_number': [],\n 'run... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a dictionary with directory attributes for FUSE. | def create_directory_attributes(time):
return {
'st_mode': (stat.S_IFDIR | 0o555),
'st_ctime': time,
'st_mtime': time,
'st_atime': time,
'st_uid': os.getuid(),
'st_gid': os.getgid(),
'st_nlink': 2
} | [
"def test_filesystem_can_get_attributes_of_directory(self):\n time.time = MagicMock(return_value=time.time())\n self.index.photos_directory_exists = MagicMock(return_value=True)\n self.index.photos_unique_domains = MagicMock(\n return_value=['example.com']\n )\n self.in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to resolve a path as something within a ref of a project. | def resolve_ref_prefix(self, path):
project, remainingPath = self.resolve_project_prefix(path)
if not project:
return None, None, None
for ref in self.cache.list_project_refs(project, self.tagRefs):
try:
treePath = remainingPath.relative_to(pathlib.Path(... | [
"def resolve_reference(ref):\n\n if not isinstance(ref, str):\n return ref\n if ':' not in ref:\n raise ValueError('invalid reference (no \":\" contained in the string)')\n\n modulename, rest = ref.split(':', 1)\n try:\n obj = import_module(modulename)\n except ImportError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |