query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Create and return a new group dance | def create_group_dance(groupname, grouptype):
group_dance = GroupDance(group_dance_name=groupname, group_dance_types=grouptype)
db.session.add(group_dance)
db.session.commit()
return group_dance | [
"def create_group():\r\n new_group = input(\"| Enter the name of the Group |\")\r\n adgroup.ADGroup.create(new_group, security_enabled=True, scope='GLOBAL')\r\n return \"| Group created |\"",
"def create_group(self):\n group_name = self.line_grp.text().strip() # removes whitespaces from left and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and return a dance event | def create_dance_event(eventname, location, description, date, reoccuring_event):
#dance_event_photo
dance_event = DanceEvent(dance_event_name=eventname,
dance_event_location=location,
dance_event_description=description,
danc... | [
"def generate_event():\n pass",
"def create_event(self, *args, **kwargs):\n return asyncio.Event(*args, **kwargs)",
"def createEvent(self):\n\n raise NotImplementedError( \"Should have implemented this\" )",
"def create(self, event):\n raise NotImplementedError('create event is not imp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all the dance event locations for google map API | def return_dance_event_locations(locations):
event_locations=DanceEvent.query.filter_by(dance_event_location=locations).all
return event_locations | [
"def list_locations():",
"def locations():\n status, body = api.locations(city='Delhi')\n return str(body['results'])",
"def location_list(self):\n \n self._send(\"location_list\")\n return [e2string(x) for x in self._read_json(220)]",
"async def get_dining_locations(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets payload for external text GCA. | def _get_text_payload(model):
payload = {
"title": "GCA Text",
"attribute_type": "Text",
"definition_type": model._inflector.table_singular,
"mandatory": False,
"helptext": "GCA Text",
"placeholder": "",
"context": None,
"external_id": 1,
"exte... | [
"def GetText(self):",
"def get_text(source):\n if source.startswith(\"http\"):\n import requests\n\n return requests.get(source).text\n with open(source, \"r\") as file:\n return file.read()",
"def get_text(self):\r\n\t\treturn self.text",
"def text(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates model on the given test data and returns specified metrics. | def evaluate(model, x_test, y_test):
scores = model.evaluate(x_test, y_test, verbose=0)
return scores | [
"def evaluate_model(self, dataset=None):\n dataset = dataset or self.val_dataset\n predictions, ground_truth = self.predict(dataset)\n metrics = self.model.evaluate(predictions, ground_truth)\n return predictions, ground_truth, metrics",
"def run_metrics(model, data_set):\n if data_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots the accuracy of a model through training time (epoches). | def plot_accuracy(history):
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Accuracy of the Model')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show() | [
"def accuracy_plot(train_accuracy, test_accuracy):\n plt.plot(range(len(train_accuracy)), train_accuracy, 'b', label='Training Accuracy')\n plt.plot(range(len(train_accuracy)), test_accuracy, 'r', label='Test Accuracy')\n plt.title('Training and Test Accuracy')\n plt.xlabel('Epochs ', fontsize=16)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plans using Jacobianbased obstacle avoidance. | def plan(baxter_kinematics, goal, obstacles, end_effector_pose, joint_angles, avoid_velocity=0.3):
# validate parameters
params = [goal, obstacles, end_effector_pose, joint_angles, side, avoid_velocity]
status = OK
for param in params:
if param is None:
status = ERROR
br... | [
"def prepareJacobian(self):\n self.jac.clear()\n self.nm = self.regionManager().parameterCount()\n self.nf = len(self.fops)\n print(self.nm, \"model cells\")\n nd = 0\n for i, fop in enumerate(self.fops):\n self.jac.addMatrix(fop.jacobian(), nd, i*self.nm)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve and display the results for each document (paragraph) | def display_document_results(scoring_fnc, run_file_loc):
qrel_file_loc = "cbor_files/train.pages.cbor-article.qrels"
with open(qrel_file_loc, 'r') as f_qrel:
qrel = pytrec_eval.parse_qrel(f_qrel)
with open(run_file_loc, 'r') as f_run:
run = pytrec_eval.parse_run(f_run)
evaluator = pyt... | [
"def docParse(self):\n text = self.text\n text = self.simplify(text)\n nlp = self.nlp\n full_doc = nlp(text)\n \n # Slit into sentences and find Simple sentences\n sent_doc_ls = list(sent for sent in full_doc.sents)\n spl_ls = self.simple_find(sent_doc_ls)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Confirm that DirectoryResourceMapping doesn't use pathlib.Path methods outside of the Traversable interface. | def test_directory_resource_mapping_with_traversable():
class MockTraversable(importlib.abc.Traversable):
def __init__(self, name, value):
self._name = name
self._value = value
def iterdir(self):
if isinstance(self._value, dict):
for key, child i... | [
"def test_pathIterable(self):\n url = URL(path=[u'hello', u'world'])\n self.assertEqual(url.path, (u'hello', u'world'))",
"def __iter__(self) -> _PathIterator[Any]:\n raise NotImplementedError",
"def test_path_iterator(monkeypatch):\n\n @classmethod\n def _fake_open_file(cls, name):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ajax view returning network list. | def cma_networks_ajax_get_table(request, user_id):
if request.method == 'GET':
networks = prep_data(('admin_cm/network/list_user_networks/', {'user_id': int(user_id)}), request.session)
return messages_ajax.success(networks) | [
"def cma_ajax_get_pool_table(request):\n if request.method == 'GET':\n pools = prep_data('admin_cm/network/list_available_networks/', request.session)\n\n for pool in pools:\n pool['stateName'] = unicode(pool_states_reversed[pool['state']])\n\n return messages_ajax.success(pools)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ajax view fetching network details. | def cma_networks_ajax_network_details(request, network_id, template_name='admin_cm/ajax/network_details.html'):
if request.method == 'POST':
net = prep_data(('admin_cm/network/list_leases/', {'network_id': network_id}), request.session)
return messages_ajax.success(render_to_string(template_name, {... | [
"def cma_networks_ajax_get_table(request, user_id):\n if request.method == 'GET':\n networks = prep_data(('admin_cm/network/list_user_networks/', {'user_id': int(user_id)}), request.session)\n return messages_ajax.success(networks)",
"def cma_ajax_get_pool_table(request):\n if request.method =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ajax view fetching pool list. | def cma_ajax_get_pool_table(request):
if request.method == 'GET':
pools = prep_data('admin_cm/network/list_available_networks/', request.session)
for pool in pools:
pool['stateName'] = unicode(pool_states_reversed[pool['state']])
return messages_ajax.success(pools) | [
"def get_pools():\n global f5rest_url\n return (get_f5json(f5rest_url + 'ltm/pool'))",
"def list_json(self):\n args = request.args\n echo = int(args.get(\"sEcho\", 0))\n length = int(args.get(\"iDisplayLength\", 10))\n start = int(args.get(\"iDisplayStart\", 0))\n end = start + length\n\n tota... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to make sure this rule does trigger with a document that is only level 1 unordered lists starting with dash and the configuration is also set to asterisk. | def test_md004_bad_asterisk_dash_single_level():
# Arrange
scanner = MarkdownScanner()
source_path = os.path.join(
"test", "resources", "rules", "md004", "good_list_dash_single_level.md"
)
supplied_arguments = [
"--set",
"plugins.md004.style=asterisk",
"scan",
... | [
"def test_md004_bad_dash_asterisk_single_level():\n\n # Arrange\n scanner = MarkdownScanner()\n source_path = os.path.join(\n \"test\", \"resources\", \"rules\", \"md004\", \"good_list_asterisk_single_level.md\"\n )\n supplied_arguments = [\n \"--set\",\n \"plugins.md004.style=da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to make sure this rule does trigger with a document that is only level 1 unordered lists starting with plus and the configuration is also set to asterisk. | def test_md004_bad_asterisk_plus_single_level():
# Arrange
scanner = MarkdownScanner()
source_path = os.path.join(
"test", "resources", "rules", "md004", "good_list_plus_single_level.md"
)
supplied_arguments = [
"--set",
"plugins.md004.style=asterisk",
"scan",
... | [
"def test_md004_bad_plus_asterisk_single_level():\n\n # Arrange\n scanner = MarkdownScanner()\n source_path = os.path.join(\n \"test\", \"resources\", \"rules\", \"md004\", \"good_list_asterisk_single_level.md\"\n )\n supplied_arguments = [\n \"--set\",\n \"plugins.md004.style=pl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to make sure this rule does trigger with a document that is only level 1 unordered lists starting with asterisks and the configuration is also set to dash. | def test_md004_bad_dash_asterisk_single_level():
# Arrange
scanner = MarkdownScanner()
source_path = os.path.join(
"test", "resources", "rules", "md004", "good_list_asterisk_single_level.md"
)
supplied_arguments = [
"--set",
"plugins.md004.style=dash",
"scan",
... | [
"def test_md004_bad_asterisk_dash_single_level():\n\n # Arrange\n scanner = MarkdownScanner()\n source_path = os.path.join(\n \"test\", \"resources\", \"rules\", \"md004\", \"good_list_dash_single_level.md\"\n )\n supplied_arguments = [\n \"--set\",\n \"plugins.md004.style=asteri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to make sure this rule does trigger with a document that is only level 1 unordered lists starting with plus and the configuration is also set to dash. | def test_md004_bad_dash_plus_single_level():
# Arrange
scanner = MarkdownScanner()
source_path = os.path.join(
"test", "resources", "rules", "md004", "good_list_plus_single_level.md"
)
supplied_arguments = [
"--set",
"plugins.md004.style=dash",
"scan",
source... | [
"def test_md004_bad_plus_dash_single_level():\n\n # Arrange\n scanner = MarkdownScanner()\n source_path = os.path.join(\n \"test\", \"resources\", \"rules\", \"md004\", \"good_list_dash_single_level.md\"\n )\n supplied_arguments = [\n \"--set\",\n \"plugins.md004.style=plus\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to make sure this rule does not trigger with a document that is only level 1 unordered lists starting with asterisk and the configuration is also set to plus. | def test_md004_bad_plus_asterisk_single_level():
# Arrange
scanner = MarkdownScanner()
source_path = os.path.join(
"test", "resources", "rules", "md004", "good_list_asterisk_single_level.md"
)
supplied_arguments = [
"--set",
"plugins.md004.style=plus",
"scan",
... | [
"def test_md004_bad_asterisk_plus_single_level():\n\n # Arrange\n scanner = MarkdownScanner()\n source_path = os.path.join(\n \"test\", \"resources\", \"rules\", \"md004\", \"good_list_plus_single_level.md\"\n )\n supplied_arguments = [\n \"--set\",\n \"plugins.md004.style=asteri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to make sure this rule does trigger with a document that is only level 1 unordered lists starting with dash and the configuration is also set to plus. | def test_md004_bad_plus_dash_single_level():
# Arrange
scanner = MarkdownScanner()
source_path = os.path.join(
"test", "resources", "rules", "md004", "good_list_dash_single_level.md"
)
supplied_arguments = [
"--set",
"plugins.md004.style=plus",
"scan",
source... | [
"def test_md004_bad_dash_plus_single_level():\n\n # Arrange\n scanner = MarkdownScanner()\n source_path = os.path.join(\n \"test\", \"resources\", \"rules\", \"md004\", \"good_list_plus_single_level.md\"\n )\n supplied_arguments = [\n \"--set\",\n \"plugins.md004.style=dash\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to make sure this rule does trigger with a document that is only level 1 unordered lists starting with each of the valid starts. | def test_md004_bad_single_level_consistent():
# Arrange
scanner = MarkdownScanner()
source_path = os.path.join(
"test", "resources", "rules", "md004", "bad_list_different_single_level.md"
)
supplied_arguments = [
"--disable-rules",
"md032",
"scan",
source_pat... | [
"def test_md004_bad_plus_dash_single_level():\n\n # Arrange\n scanner = MarkdownScanner()\n source_path = os.path.join(\n \"test\", \"resources\", \"rules\", \"md004\", \"good_list_dash_single_level.md\"\n )\n supplied_arguments = [\n \"--set\",\n \"plugins.md004.style=plus\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns raw transaction bytes. | def get_public_tx(self) -> bytes:
assert self._file is not None
# remember where the pointer is in the file before we go back for the transaction bytes
header = self._file.tell()
self._file.seek(self._tx_offset)
buffer = _byte_read_safe(self._file, self._total_size)
# re... | [
"def get_raw_transaction(self, tx_id, height):\n return self.get_response('blockchain.transaction.get', [tx_id, height])",
"def serialize(self) -> bytes: # noqa: E501 pylint: disable=line-too-long\n if not self.signatures:\n raise AttributeError(\"transaction has not been signed\")\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the GET and PUT of push rules' `enabled` endpoints. Tests that a rule is enabled upon creation, even though a rule with that ruleId existed previously and was disabled. | def test_enabled_on_creation(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
body = {
"conditions": [
{"kind": "event_match", "key": "sender", "pattern": "@user2:hs"}
],
"actions": ["notify", {"set_tweak": ... | [
"def test_enabled_disable(self) -> None:\n self.register_user(\"user\", \"pass\")\n token = self.login(\"user\", \"pass\")\n\n body = {\n \"conditions\": [\n {\"kind\": \"event_match\", \"key\": \"sender\", \"pattern\": \"@user2:hs\"}\n ],\n \"act... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the GET and PUT of push rules' `enabled` endpoints. Tests that a rule is disabled and enabled when we ask for it. | def test_enabled_disable(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
body = {
"conditions": [
{"kind": "event_match", "key": "sender", "pattern": "@user2:hs"}
],
"actions": ["notify", {"set_tweak": "hig... | [
"def test_enabled_on_creation(self) -> None:\n self.register_user(\"user\", \"pass\")\n token = self.login(\"user\", \"pass\")\n\n body = {\n \"conditions\": [\n {\"kind\": \"event_match\", \"key\": \"sender\", \"pattern\": \"@user2:hs\"}\n ],\n \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `enabled` gives 404 when the serverdefault rule doesn't exist. | def test_enabled_404_when_get_non_existent_server_rule(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
# check 404 for never-heard-of rule
channel = self.make_request(
"GET", "/pushrules/global/override/.m.muahahaha/enabled", access_token... | [
"def test_enabled_404_when_put_non_existent_server_rule(self) -> None:\n self.register_user(\"user\", \"pass\")\n token = self.login(\"user\", \"pass\")\n\n # enable & check 404 for never-heard-of rule\n channel = self.make_request(\n \"PUT\",\n \"/pushrules/global/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `enabled` gives 404 when we put to a rule that doesn't exist. | def test_enabled_404_when_put_non_existent_rule(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
# enable & check 404 for never-heard-of rule
channel = self.make_request(
"PUT",
"/pushrules/global/override/best.friend/enabled",... | [
"def test_enabled_404_when_put_non_existent_server_rule(self) -> None:\n self.register_user(\"user\", \"pass\")\n token = self.login(\"user\", \"pass\")\n\n # enable & check 404 for never-heard-of rule\n channel = self.make_request(\n \"PUT\",\n \"/pushrules/global/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `enabled` gives 404 when we put to a serverdefault rule that doesn't exist. | def test_enabled_404_when_put_non_existent_server_rule(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
# enable & check 404 for never-heard-of rule
channel = self.make_request(
"PUT",
"/pushrules/global/override/.m.muahahah/en... | [
"def test_enabled_404_when_get_non_existent_server_rule(self) -> None:\n self.register_user(\"user\", \"pass\")\n token = self.login(\"user\", \"pass\")\n\n # check 404 for never-heard-of rule\n channel = self.make_request(\n \"GET\", \"/pushrules/global/override/.m.muahahaha/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `actions` gives you what you expect on a fresh rule. | def test_actions_get(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
body = {
"conditions": [
{"kind": "event_match", "key": "sender", "pattern": "@user2:hs"}
],
"actions": ["notify", {"set_tweak": "highlig... | [
"def test_failing_action(self):\n dummy_calls = []\n\n self.action_fail.side_effect = dummy_calls.append\n self._get_action_name.side_effect = lambda: \"foo\"\n\n def dummy_action(args):\n raise ValueError(\"uh oh\")\n\n self.get_action_parser = lambda: argparse.Argumen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `actions` gives 404 when the serverdefault rule doesn't exist. | def test_actions_404_when_get_non_existent_server_rule(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
# check 404 for never-heard-of rule
channel = self.make_request(
"GET", "/pushrules/global/override/.m.muahahaha/actions", access_token... | [
"def test_actions_404_when_put_non_existent_server_rule(self) -> None:\n self.register_user(\"user\", \"pass\")\n token = self.login(\"user\", \"pass\")\n\n # enable & check 404 for never-heard-of rule\n channel = self.make_request(\n \"PUT\",\n \"/pushrules/global/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `actions` gives 404 when putting to a rule that doesn't exist. | def test_actions_404_when_put_non_existent_rule(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
# enable & check 404 for never-heard-of rule
channel = self.make_request(
"PUT",
"/pushrules/global/override/best.friend/actions",... | [
"def test_actions_404_when_get_non_existent_server_rule(self) -> None:\n self.register_user(\"user\", \"pass\")\n token = self.login(\"user\", \"pass\")\n\n # check 404 for never-heard-of rule\n channel = self.make_request(\n \"GET\", \"/pushrules/global/override/.m.muahahaha/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `actions` gives 404 when putting to a serverdefault rule that doesn't exist. | def test_actions_404_when_put_non_existent_server_rule(self) -> None:
self.register_user("user", "pass")
token = self.login("user", "pass")
# enable & check 404 for never-heard-of rule
channel = self.make_request(
"PUT",
"/pushrules/global/override/.m.muahahah/ac... | [
"def test_actions_404_when_get_non_existent_server_rule(self) -> None:\n self.register_user(\"user\", \"pass\")\n token = self.login(\"user\", \"pass\")\n\n # check 404 for never-heard-of rule\n channel = self.make_request(\n \"GET\", \"/pushrules/global/override/.m.muahahaha/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `contains_user_name` rule is present and have proper value in `pattern`. | def test_contains_user_name(self) -> None:
username = "bob"
self.register_user(username, "pass")
token = self.login(username, "pass")
channel = self.make_request(
"GET",
"/pushrules/global/content/.m.rule.contains_user_name",
access_token=token,
... | [
"def test_some_names(self, _, __, username, realname, success,):\n try:\n validate_username(username, realname)\n except ValidationWarning as ex:\n if success:\n pytest.fail(\n 'Received unexpected error: {error}'.format(error=ex),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that `is_user_mention` rule is present and have proper value in `value`. | def test_is_user_mention(self) -> None:
user = self.register_user("bob", "pass")
token = self.login("bob", "pass")
channel = self.make_request(
"GET",
"/pushrules/global/override/.m.rule.is_user_mention",
access_token=token,
)
self.assertEqua... | [
"def is_user_mention(self):\n temp = nltk.TweetTokenizer(strip_handles=True)\n result = temp.tokenize(self.token)\n if result == []:\n return True\n else:\n return False",
"def test__put_mentionable_into():\n for input_value, defaults, expected_output in (\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing that empty lists give zero. | def test_empty_lists():
check_sum_of_four([], [], [], []) == 0 | [
"def test_empty_lists_case():\n assert check_sum_of_four([], [], [], []) == 0",
"def test_returns_zero_if_list_is_empty(self):\n result = island_counter([])\n self.assertEqual(result, 0)",
"def test_empty_list(self):\n empty = []\n self.assertEqual(max_integer(empty), None)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing that lists consisting of zeroes give len of decart product of all elements. | def test_zero_lists():
arr = [0, 0, 0]
check_sum_of_four(arr, arr, arr, arr) == len(arr) ** 4 | [
"def test_empty_lists():\n check_sum_of_four([], [], [], []) == 0",
"def test_empty_lists_case():\n assert check_sum_of_four([], [], [], []) == 0",
"def test_all_zeroes():\n zeroArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n assert [0] == findLongestLength(zeroArray)",
"def test_calculate_la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Infer PCFG parses for `sentence` by the insideoutside algorithm. | def parse(self, sentence):
pcfg = self.pcfg
alpha, backtrace = self._inside(sentence)
beta = self._outside(sentence, alpha)
return alpha, beta, backtrace | [
"def parse_with_bindops(sentence, grammar: Optional[Any] = ..., trace=...):\n ...",
"def demo():\n\n from nltk import CFG, parse\n\n grammar = CFG.fromstring(\n \"\"\"\n S -> NP VP\n NP -> Det N | Det N PP\n VP -> V NP | V NP PP\n PP -> P NP\n NP -> 'I'\n N -> 'man' | 'park' | 't... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate outside scores for a sentence given inside scores `alpha`. | def _outside(self, sentence, alpha):
pcfg = self.pcfg
beta = np.zeros((len(pcfg.nonterminals) + len(pcfg.preterminals),
len(sentence), len(sentence)))
# base case
beta[pcfg.nonterm2idx[pcfg.start], 0, len(sentence) - 1] = 1.0
# recursive case
for i, node in enumerate(pcfg.no... | [
"def negvalenceavg (score):\n ng = []\n for n in score:\n ng.append(n['neg'])\n return sum(ng) / len (ng)",
"def normalize(score, alpha=15):\n norm_score = score / math.sqrt((score * score) + alpha)\n if norm_score < -1.0:\n return -1.0\n elif norm_score > 1.0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate marginal distributions over grammar weights, marginalizing out all possible parses of `sentence` under `pcfg` via insideoutside. | def expected_counts(pcfg, sentence):
# Run inside-outside inference.
alpha, beta, _ = parse(pcfg, sentence)
# Calculate expected counts.
binary_counts = np.zeros((len(pcfg.nonterminals), len(pcfg.productions)))
unary_counts = np.zeros((len(pcfg.preterminals), len(pcfg.terminals)))
# Calculate binary count... | [
"def calculateSentenceProbs(sentences, n, n_1gram, ngram, mode, zero_prob):\n\tdict_p = {}\n\tfor sentence in sentences:\n\t\tif sentence != \"\":\n\t\t\t# Split sentence into words\n\t\t\tseq = sentence.split()\n\t\t\t# calculate probability of sentence\n\t\t\tp = calculateSentenceProb(seq, n, n_1gram, ngram, mode... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test replication of example Card object | def test_replicate_primitive(self):
card = examples.Card(1, 'clubs')
self.assertEqual(card.rank, 1)
self.assertEqual(card.suit, 'clubs')
card_copy = self.replicator.replicate(card)
self.assertNotEqual(id(card), id(card_copy))
self.assertEqual(card, card_copy)
se... | [
"def test_2_club(self):\n card = cards.Card(1, 2)\n self.assertEqual(card.suit_name, \"Clubs\")",
"def test_player_add_card(player):\n new_card = card_game.Card(14, \"Clubs\")\n assert (len(player.cards) == 1) == (player.score == 56\n )",
"def test_Cons... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a string for team. This is required to display in the Admin view. | def team_display(self):
return ', '.join(
team.team_name for team in self.team.all()) | [
"def encode(self):\n return (\"Team\",[self.name])",
"def create_team():\n \n return render_template(\"createteam.html\")",
"def __repr__(self):\n return f'<Team id={self.id}>'",
"def team():\n click.echo('Playing with: {}.'.format(mySquad.current_team.name))",
"def test_team_repr(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a string for season. This is required to display in the Admin view. | def season_display(self):
return ', '.join(
str(season.season_year) for season in self.season.all()) | [
"def season_type(self):\n if self.game_id[2] == \"4\":\n return PLAYOFFS_STRING\n elif self.game_id[2] == \"2\":\n return REGULAR_SEASON_STRING",
"def current_season(self):\n return datetime.datetime.strftime(self.date, \"%Y\")",
"def _getSeason(self):\n # T... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for mouse click on bet buttons before a deal | def check_bet_buttons(stats, mouse_x, mouse_y):
for button in stats.bet_buttons:
button_clicked = button.rect.collidepoint(mouse_x, mouse_y)
if button_clicked:
# stats.bet_buttons =
# [bet_1_button, bet_5_button, bet_10_button, deal_button]
if button == stats.bet_... | [
"def check_player_buttons(settings, stats, mouse_x, mouse_y):\n for button in stats.player_buttons:\n button_clicked = button.rect.collidepoint(mouse_x, mouse_y)\n if button_clicked:\n # stats.player_buttons = [hit_button, stay_button]\n if button == stats.player_buttons[0]:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for mouse click on player buttons after a deal | def check_player_buttons(settings, stats, mouse_x, mouse_y):
for button in stats.player_buttons:
button_clicked = button.rect.collidepoint(mouse_x, mouse_y)
if button_clicked:
# stats.player_buttons = [hit_button, stay_button]
if button == stats.player_buttons[0]:
... | [
"def handleMouseRelease(self, event):\n if self._board.determineIfBought():\n if self._type == \"purchase\":\n self._board.purchaseButton()\n else:\n self._board.passButton()",
"def on_mouse_press(self, _x, _y, _button, _modifiers):\n if self.butto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dealer finishes his round, holding at 17 or above | def dealer_round(settings, stats):
# Hit until dealer hand value is 17 or above
while stats.dealer_hand_value < 17:
deal_dealer(settings, stats)
end_round(stats)
stats.end_round = True | [
"def dealer_turn(self):\n while sum(self.hand_value) < 17:\n self.player_response = \"H\"\n print(\"DEALER HITS\")\n return self.player_response\n self.player_response = \"S\"",
"def on_end_buying_round(self, player_state, round_history):\n pass",
"def fundi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tools to check current state of deck. | def check_deck(stats):
# Delete function once game is finished
for pcard in stats.deck:
print(str(pcard.rank) + " " + pcard.suit)
print("There are " + str(len(stats.deck)) + " cards left in the deck.")
print("Dealer hand value: " + str(stats.dealer_hand_value))
print("Player hand vaule: " + ... | [
"def testDecks(self):\n deck = Card.getStandardDeck()\n #length check\n self.assertEqual(len(deck), 52)\n #joker check\n self.assertFalse(Card(0, None) in deck)\n joker_deck = Card.getJokerDeck()\n #length check\n self.assertEqual(len(joker_deck), 54)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test get bootloader cmdline | def test_get_bootloader_cmdline(self):
cmdline = Cmdline(self.user)
root = cmdline.get("root")
assert root is not None | [
"def test_get_bootloader_grub2(self):\n try:\n grub2 = Grub2(self.user)\n grub2.get(\"bootloader\")\n assert False\n except GetConfigError:\n assert True",
"def bootloader(server, gtype = 0):\n if fv_cap(server) and gtype == 1:\n bootloader = \"/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates the login credentials of the user. | def validate_login(self):
is_user_valid = None
try:
if self.redmine.auth():
self.__valid_redmine_login = True
is_user_valid = True
except Exception as error:
print(error)
return is_user_valid | [
"def validate_user_login(self):\n\t\tcookie_user = self.request.cookies.get('username')\n\t\tcookie_h = self.request.cookies.get('password')\n\t\tif validate_user(cookie_user, h=cookie_h, passwrd=\"\"):\n\t\t\treturn cookie_user\n\t\telse:\n\t\t\tself.redirect('/login')",
"def validate_login_input(request, valida... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all the trackers added to the project in redmine. | def get_project_trackers(self, project_name):
if self.__valid_redmine_login:
trackers_list = []
all_projects = self.redmine.project.all()
for project in all_projects:
if project.name == project_name:
for tracker in project.trackers:
... | [
"def load_trackers(self):\n updated_trackers = \\\n self._trackers_api.get_trackers(modified_since=None)\n\n for tracker in updated_trackers:\n tracker.set_storage(self.storage)\n self.scheduler.add_tracker(tracker)\n\n sender.fire(LoggerInfoEvent,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the total number of projects. | def total_projects_count(self):
total_projects = str(len(self.get_projects()))
return total_projects | [
"def total_projects(self) -> int:\n return Project.objects.filter(client=self).count()",
"def _get_count(self) -> \"size_t\" :\n return _core.DataProjects__get_count(self)",
"def get_num_projects(conn):\n c = conn.cursor()\n sql = \"SELECT COUNT(*) AS count FROM projects;\"\n c.execute(sq... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the total number of issues created by the user. | def total_issues_count(self):
if self.__valid_redmine_login:
total_issues = str(len(self.get_issues()))
return total_issues | [
"def total_issues_resolved_count(self):\n if self.__valid_redmine_login:\n total_resolved = 0\n for issue_key in self.issues_dict:\n if self.issues_dict[issue_key]['status'] == constants.RESOLVED_STATUS:\n total_resolved += 1\n total_resolved... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the total number of issues whose status is resolved. | def total_issues_resolved_count(self):
if self.__valid_redmine_login:
total_resolved = 0
for issue_key in self.issues_dict:
if self.issues_dict[issue_key]['status'] == constants.RESOLVED_STATUS:
total_resolved += 1
total_resolved = str(tota... | [
"def total_issues_pending_count(self):\n if self.__valid_redmine_login:\n total_pending = 0\n for issue_key in self.issues_dict:\n if self.issues_dict[issue_key]['status'] != constants.RESOLVED_STATUS:\n total_pending += 1\n total_pending = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the total number of issues whose status is not resolved. | def total_issues_pending_count(self):
if self.__valid_redmine_login:
total_pending = 0
for issue_key in self.issues_dict:
if self.issues_dict[issue_key]['status'] != constants.RESOLVED_STATUS:
total_pending += 1
total_pending = str(total_pe... | [
"def total_issues_resolved_count(self):\n if self.__valid_redmine_login:\n total_resolved = 0\n for issue_key in self.issues_dict:\n if self.issues_dict[issue_key]['status'] == constants.RESOLVED_STATUS:\n total_resolved += 1\n total_resolved... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Factores para calcular el TDEE Sedentary = BMR x 1.2 Light Active = BMR x 1.375 Moderately Active = BMR x 1.55 Very Active = BMR x 1.725 | def tdee(bmr):
# Segunda parte: cálculo del TDEE (Total Daily Energy Expenditure).
factortxt = """
** Segunda parte: cálculo del gasto calórico total **
Elija el número, de acuerdo a su nivel *REAL* de actividad física DIARIA:
OBS: "ejercicio intenso" significa correr o levantar pesas.
... | [
"def diffusion():\n return 5.1412512431",
"def _calc_tdee(self, rmr: float) -> int:\n\n ACTIVITY_FACTORS = {\n 1: 1.2, # Little or no exercise\n 2: 1.375, # Light exercise 1-3 days a week\n 3: 1.55, # Moderate exercise 4-5 days a week\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the geometry of the wrapper. | def geometry(self, geometry):
self._geometry = geometry | [
"def geometry_change():\n register.geometry(str(length_scale.get()) + \"x\" + str(height_scale.get()))",
"def setGeometry(self, rect):\n QGraphicsView.setGeometry(self, rect)\n scene = QGraphicsScene(QRectF(rect), self.parent)\n w, h = rect.width(), rect.height()\n margi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a Rhino mesh to a COMPAS mesh. | def to_compas(self, cls=None):
cls = cls or Mesh
mesh = cls()
for vertex in self.geometry.Vertices:
mesh.add_vertex(attr_dict=dict(x=float(vertex.X), y=float(vertex.Y), z=float(vertex.Z)))
for face in self.geometry.Faces:
if face.A == face.D or face.C == face.D:... | [
"def convert_mesh(input_mesh, output_mesh):\n sp.Popen(['dolfin-convert', input_mesh, output_mesh]).wait()",
"def from_rhinosurface(cls, guid, **kwargs):\n from compas_rhino.geometry import RhinoSurface\n mesh = RhinoSurface.from_guid(guid).uv_to_compas(cls, **kwargs)\n if 'name' in kwargs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the closest points on the mesh to a list of input points. | def closest_points(self, points, maxdist=None):
return [self.closest_point(point, maxdist) for point in points] | [
"def closest(reference,points):\n min_dis = float('inf')\n for point in points:\n dis = distance(reference,point)\n if dis < min_dis:\n min_dis = dis\n closest_point = point\n return closest_point, min_dis",
"def brute_force_closest(point, pointlist):\n import sys\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call test on each node/leaf of combiner. | def for_each_combiner(self, combiner, res):
if combiner.children:
for child_combiner in combiner.children:
self.for_each_combiner(child_combiner, res)
# append my result
res.append((combiner.name, combiner.results['lvl']))
return res | [
"def test_tree(tree):\n for node in tree:\n if isinstance(node, CST.Node):\n test_leaf(node)\n else:\n test_branch(node)\n test_tree(node)",
"def test_combiner_results(self):\n from furious.marker_tree.identity_utils import leaf_pers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read local ancestry with .lanc format | def read_lanc(path: str) -> admix.data.Lanc:
lanc = admix.data.Lanc(path)
return lanc | [
"def import_ability_tree(filename):\n f = open(filename, 'r')\n lines = f.readlines()\n f.close()\n def parse_line(line):\n name_list = re.findall(\"(?<=]).+(?=:)\", line)\n label_list = re.findall(\"\\[.+\\]\", line)\n level_list = re.findall(\"(?<=:)[\\d\\s-]+\", line)\n if any(len(l)!=1 for l in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a matrix of integer with [09], and with no delimiter. | def read_digit_mat(path: str, filter_non_numeric: bool = False, nrows: int = None):
if nrows is None:
if filter_non_numeric:
with open(path) as f:
mat = np.array(
[
np.array([int(c) for c in re.sub("[^0-9]", "", line.strip())])
... | [
"def read_input_file():\n global rows\n global cols\n global maze\n\n with open(filename, \"r\") as fout:\n a = fout.readline()\n rows, cols = tuple(a.split())\n rows = int(rows)\n cols = int(cols)\n\n maze = fout.readlines()\n maze = [list(r.strip(\" \\n\")) fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the GRM from a GCTA formated file. | def read_gcta_grm(file_prefix) -> dict:
bin_file = file_prefix + ".grm.bin"
N_file = file_prefix + ".grm.N.bin"
id_file = file_prefix + ".grm.id"
df_id = read_csv(id_file, sep="\t", header=None, names=["sample_0", "sample_1"])
n = df_id.shape[0]
k = asarray(fromfile(bin_file, dtype=float32), f... | [
"def read_txt_grains(fname):\n\n # Note: (21) fields named below with an underscore are not yet used\n #\n # Fields from grains.out header:\n \"\"\"grain ID completeness chi2\n xi[0] xi[1] xi[2]\n tVec_c[0] tVec_c[1] tVec_c[2]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read joint PCA results. | def read_joint_pca(pca_prefix: str, ref_pfile: str):
df_pca = (
pd.read_csv(f"{pca_prefix}.eigenvec", delim_whitespace=True)
.set_index("IID")
.drop(columns=["#FID"])
)
with open(f"{pca_prefix}.eigenval") as f:
eigenval = np.array([float(l.strip()) for l in f.readlines()])
... | [
"def read_results(self):\n FileIOCalculator.read(self, self.label)\n if not os.path.isfile(self.label + '.out'):\n raise ReadError\n parser = MopacParser(self.label)\n self.parser = parser\n self.atoms = parser.atoms\n self.results = parser.get_properties()",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the ConnectomistWrapper class by setting properly the environment and checking that the Connectomist software is installed. | def __init__(self, path_connectomist=DEFAULT_CONNECTOMIST_PATH):
# Class parameters
self.path_connectomist = path_connectomist
self.environment = os.environ
# Check Connectomist can be configured
self._connectomist_version_check(self.path_connectomist)
# Check Connectom... | [
"def setup_class(self):\n module_dir = os.path.dirname(os.path.abspath(__file__))\n self.SCRIPTS = os.path.join(module_dir, 'bash_scripts')\n self.REPOS_PARENT = module_dir\n self.REPOS = os.path.join(module_dir, 'repos')\n self.TOOL_DIRECTORY = os.path.dirname(inspect.getfile(Iri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes two feature dictionaries d1 and d2 as inputs, and computes and returns their log similarity score | def compare_dictionaries(d1, d2):
score = 0
total = 0
for i in d1:
total += d1[i]
for i in d2:
if i in d1:
score += d2[i]*math.log(d1[i]/total)
else:
score += d2[i]*math.log(0.5/total)
return score | [
"def compare_dictionaries(d1, d2):\n score = 0\n total = 0\n for w in d1:\n total += d1[w]\n for w in d2:\n if w in d1:\n score += d2[w] * math.log(d1[w] / total)\n else:\n score += math.log(0.5 / total)\n return score",
"def euclidean_similarity(dic1, dic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
constructs a new TextModel object by accepting a string model_name as a parameter and initializing the following three attributes | def __init__(self, model_name):
self.name = model_name
self.words = {}
self.word_lengths = {}
self.stems = {}
self.sentence_lengths = {}
self.punctuation = {} | [
"def __init__(self, model_name):\n self.name = model_name\n self.words ={}\n self.word_lengths = {}\n self.stems = {}\n self.sentence_lengths = {}\n self.punctuation = {}",
"def __create_model(self):\n\n model_fields = []\n for field in [\n field ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a string representation of the TextModel. | def __repr__(self):
s = 'text model name: ' + self.name + '\n'
s += ' number of words: ' + str(len(self.words)) + '\n'
s += ' number of word lengths: ' + str(len(self.word_lengths)) + '\n'
s += ' number of stems: ' + str(len(self.stems)) + '\n'
s += ' number of sentence lengt... | [
"def __repr__(self):\n s = 'text model name: ' + self.name + '\\n'\n s += ' number of words: ' + str(len(self.words)) + '\\n'\n s += ' number of word lengths: ' + str(len(self.word_lengths)) + '\\n'\n s += ' number of stems: ' + str(len(self.stems)) + '\\n'\n s += ' number of ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reads the stored dictionaries for the called TextModel object from their files and assigns them to the attributes of the called TextModel | def read_model(self):
wordsfile = open(self.name + '_' + 'words', 'r')
words_str = wordsfile.read()
wordsfile.close()
d1 = dict(eval(words_str))
self.words = d1
word_lengths_file = open(self.name + '_' + 'word lengths', 'r')
word_lengths_str = word_length... | [
"def read_model(self):\r\n dic1=self.name+'_'+'words'\r\n dic2=self.name+'_'+'word_lengths'\r\n dic3=self.name+'_'+'stems'\r\n dic4=self.name+'_'+'sentence_lengths'\r\n dic5=self.name+'_'+'three_adjacent'\r\n f = open(dic1, 'r') \r\n words = f.read()\r\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
computes and returns a list of log similarity scores measuring the similarity of self and other between every feature dictionary | def similarity_scores(self,other):
word_score = compare_dictionaries(other.words,self.words)
word_lengths_score = compare_dictionaries(other.word_lengths,self.word_lengths)
stems_score = compare_dictionaries(other.stems, self.stems)
sentence_lengths_score = compare_dictionaries(... | [
"def similarity_scores(self, other):\n word_score = compare_dictionaries(other.words, self.words)\n word_lengths_scores = compare_dictionaries(other.word_lengths, self.word_lengths)\n stems_scores = compare_dictionaries(other.stems, self.stems)\n sentence_lengths_socre = compare_dictiona... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see if the user has entered in a valid alarm time | def check_alarm_input(alarm_time):
if len(alarm_time) == 1:
if alarm_time[0] < 24 and alarm_time[0] >= 0:
return True
if len(alarm_time) == 2:
if alarm_time[0] < 24 and alarm_time[0] >= 0 and alarm_time[1] < 60 and alarm_time[1] >= 0:
return True
elif len(alarm_time)... | [
"def check_time_correct(self):\r\n if self.get_hour() == '' or self.get_min() == '' or len(str(self.get_hour())+str(self.get_min())) != 4:\r\n messagebox.showerror(\"Ok\", \"Please enter a valid time. Use the format HH:MM\")\r\n self.refresh()\r\n else:\r\n if int(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the status of the websocket (WS_INIT|WS_OPEN|WS_CLOSED) | def status(self):
if self._ws and self._ws.status:
return self._ws.status
return WS_CLOSED | [
"def test_getWebSocketState() -> json:\r\n\r\n # Action\r\n status, result = u.getWebSocketState()\r\n\r\n # Assertion\r\n AssertNotEmptyOrError(status, result)",
"def get_state(self):\n if self.connected is True:\n return self.__request(\n WemoSwitch.body_status, Wemo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subscribe to the InterApplication Bus, running the on_message callback whenever a message is sent to the given source | def subscribe(self, source, on_message=None, on_register=None):
self._check_status()
key = SubKey.from_string(source)
self._ws.subscriptions.append((key, on_message))
self._ws('subscribe', args=(key,), callback=on_register) | [
"def subscribe(self, source):\n sub_impl = pn_messenger_subscribe(self._mng, source)\n if not sub_impl:\n self._check(PN_ERR)",
"def listen(publisher):\n global client\n client.subscribe(SUBSCRIBER_TOPIC, 1, on_message)\n print('Subscribed to topic.')\n while listening:\n time.sleep(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle HR users and officers recipients that can validate or refuse holidays directly from email. | def _notification_recipients(self, message, groups):
groups = super(HrHolidays, self)._notification_recipients(message, groups)
self.ensure_one()
hr_actions = []
if self.state == 'confirm' and self.state=='refuse':
app_action = self._notification_link_helper('controller', co... | [
"def send_employee_notifications(user, department, date, business_data,\n live_calendar, view_rights, notify_all,\n notify_by_sms, notify_by_email):\n client = Client(account_sid, auth_token)\n\n # Get employees who have new/edited schedules who ha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when the goniometer used changes. | def on_goniometer_changed(self, *args):
#Re-do the controls
self.make_angle_controls()
#Update the list calcualted
self.OnTextbox_Text(None) | [
"def gauge(self, name, val):\n self.calls.append((\"gauge\", name, round(val, 3)))",
"def gsd_changed(self, value):\n self.poly_sigma_new = float(value) / 10.\n self.gsd_label_display.setText(str(self.poly_sigma_new))",
"def refresh_power(self):",
"def sending_gauge_msg(self,g_msg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when any of the 3 angle textboxes are changed. | def OnTextbox_Text(self, event):
angles_lists = list()
for text in self.textAngles:
angles_lists.append(text.GetValue())
self.evaluate(angles_lists, self.panel.checkIgnoreGonio.GetValue() )
if not event is None: event.Skip() | [
"def on_goniometer_changed(self, *args):\n #Re-do the controls\n self.make_angle_controls()\n #Update the list calcualted\n self.OnTextbox_Text(None)",
"def onTextChange(self, event):\r\n self.textChangeFlag = True;",
"def __refBoxesChanged(self):\n if self.refLayers() ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Message handler for the calculations of coverage. Runs when calculation is finished (or aborted). | def calculation_done(self, message):
#Reset GUI elements.
self.panel.buttonCalculate.SetLabel("Begin Calculation")
self.panel.buttonCancel.SetLabel("Cancel Calculation")
self.panel.buttonCalculate.Enable(True)
self.panel.buttonCancel.Enable(False)
self.panel.gaugeProgress... | [
"def runCoverage(self):\n cov = \"\"\n wid = \"\"\n notes = []\n dele = True\n\n self.__ifVerbose(\"Running Genome Coverage Statistics\")\n samDir = self.outdir + \"/SamTools\"\n i = datetime.now()\n self.__CallCommand(['coverage estimator', self.fOut + \"/\" ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Abort the calculation thread, if any. | def abort(self):
if not (self.calculationThread is None):
self.calculationThread.abort() | [
"def Abort(self):\n\t\tself.abort.set()\n\t\tfor _ in range(len(self.threads)):\n\t\t\tself.queue.Put(ThreadPool.exitEvent)\n\t\t_ = [t.join() for t in self.threads]\n\t\tself.callbackQueue.Put(ThreadPool.exitEvent)",
"def abort(self):\n result = self.lastTransaction.abort()\n self.lastTransaction =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Eliminate all the other values (except d) from values[s] and propagate. Return values, except return False if a contradiction is detected. | def assign(values, s, d):
other_values = values[s].replace(d, '')
if all(eliminate(values, s, d2) for d2 in other_values):
#print(values)
return values
else:
return False | [
"def eliminate(values, s, d):\n if d not in values[s]:\n return values ## Already eliminated\n values[s] = values[s].replace(d,'')\n ## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers.\n if len(values[s]) == 0:\n return False ## Contradiction: removed last va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Eliminate d from values[s]; propagate when values or places <= 2. Return values, except return False if a contradiction is detected. | def eliminate(values, s, d):
if d not in values[s]:
return values ## Already eliminated
values[s] = values[s].replace(d,'')
## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers.
if len(values[s]) == 0:
return False ## Contradiction: removed last value
eli... | [
"def eliminate(values, s, d):\n if d not in values[s]:\n return values ## Already eliminated\n values[s] = values[s].replace(d,'')\n ## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers.\n if len(values[s]) == 0:\n return False ## Contradiction: removed last va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a random puzzle with N or more assignments. Restart on contradictions. Note the resulting puzzle is not guaranteed to be solvable, but empirically about 99.8% of them are solvable. Some have multiple solutions. | def random_puzzle(N=17):
global already_generated_boards
values = dict((s, digits) for s in squares)
for s in shuffled(squares):
if not assign(values, s, random.choice(values[s])):
break
ds = [values[s] for s in squares if len(values[s]) == 1]
if len(ds) >= N and len(set(... | [
"def make_solution():\n while True:\n try:\n puzzle = [[0]*9 for i in range(9)] # start with blank puzzle\n rows = [set(range(1,10)) for i in range(9)] # set of available\n columns = [set(range(1,10)) for i in range(9)] # numbers for each\n squares = [set(ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate html with parameter use in obj (e.g., estimator). | def _gen_est_summary(obj, out_filename):
params_dict = obj.get_params()
est_params = {k: v for k, v in params_dict.items() if not k.startswith("kernel_transformer")}
ker_params = {k: v for k, v in params_dict.items() if k.startswith("kernel_transformer__")}
ker_params_text = ["<ul>"]
ker_params_tex... | [
"def _display_(_obj_=object):\n html = (\"\"\"\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>MathJax example</title>\n <scri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Traverse the reports config definition and instantiate reportlets. This method also places figures in their final location. | def index(self, config):
for subrep_cfg in config:
reportlets = [Reportlet(self.out_dir, config=cfg) for cfg in subrep_cfg["reportlets"]]
if reportlets := [r for r in reportlets if not r.is_empty()]:
sub_report = SubReport(
subrep_cfg["name"],
... | [
"def setup_plots(): # todo arguments for latexify\n from blhelpers.plot_helpers import latexify\n latexify()",
"def __init__(self,*arg,**kwargs):\n self.black, self.env, self.mlab, self.file_name, self.line_spacing = process_kwargs([\n ('black',0.9),\n ('env',''),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
install syslinux6 from the fedora21 release | def install_syslinux6(self):
key = 'http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-21-primary'
rpms = [
'http://mirror.onelab.eu/fedora/releases/21/Everything/x86_64/os/Packages/s/syslinux-6.03-1.fc21.x86_64.rpm',
'http://mirror.onelab.eu/fedora/releases/21/Everything/x86_64/os... | [
"def install_python_26():\n # Python 2.6 is already installed by default, we just add compile headers\n sudo('apt-get -yq install python2.6-dev')\n\n # install Distribute\n sudo('curl -O http://python-distribute.org/distribute_setup.py')\n sudo('python2.6 distribute_setup.py')\n sudo('rm -f distri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
yum install mod_python, useful on f18 and above so as to avoid broken wsgi | def mod_python(self):
return self.dnf_install( ['mod_python'] ) | [
"def install_python_27():\n\n sudo('add-apt-repository ppa:fkrull/deadsnakes')\n sudo('apt-get update')\n sudo('apt-get -yq install python2.7-dev')\n\n # install Distribute\n sudo('curl -O http://python-distribute.org/distribute_setup.py')\n sudo('python2.7 distribute_setup.py')\n sudo('rm -f d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check to see if dir is a subdirectory of (or matches) check_dir directories. Return True if the dir is a subdirectory of or matches any of the check directories. | def is_dir_inside(dir, check_dirs):
for check_dir in check_dirs:
if os.path.commonprefix([dir, check_dir]) == check_dir:
return True
return False | [
"def contains_directory(path_to_directory, glob):\n return contains_glob(path_to_directory, glob, os.path.isdir)",
"def _is_in_directory(directory, path, recursive):\n start = len(directory)\n\n # The directory itself or anything shorter is not a match.\n if len(path) <= start:\n return False\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fetch the number of votes this user has had on his/her comments | def get_comment_karma(self):
comment_ids = [c.id for c in self.comments]
select = CommentUpvote.select(db.and_(
CommentUpvote.comment_id.in_(comment_ids),
CommentUpvote.user_id != self.id
)
)
rs = db.engine.execute(select)
return rs.rowcount | [
"def count_votes_comments(self):\n logging.info(\"Ending and counting votes via comments for Art-Battle %s\" % self.date)\n user = get_state().get_admin()\n (post, comments) = user.get_post_and_comments(self.poll_post_id)\n user_votes = {} # Maps username to their vote\n for comment in comments.iterv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the raw age of this post in seconds | def get_age(self):
return (self.created_at - datetime(1970, 1, 1)).total_seconds() | [
"def get_age(self):\n return (self.created_at - datetime.datetime(1970, 1, 1)).total_seconds()",
"def age(self):\n return time.time() - self.create_epoch",
"def age(self):\n birth_date = self.patient.get('birth_date', None)\n if birth_date:\n diff = self.created.date() - b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the reddit hotness algorithm (votes/(age^1.5)) | def get_hotness(self):
order = log(max(abs(self.votes), 1), 10) # Max/abs are not needed in our case
seconds = self.get_age() - 1134028003
return round(order + seconds / 45000, 6) | [
"def _update_hotness(self):\n # algorithm from code.reddit.com by CondeNet, Inc.\n delta = self.date - datetime(1970, 1, 1)\n secs = (delta.days * 86400 + delta.seconds +\n (delta.microseconds / 1e6)) - 1134028003\n order = log(max(abs(self.votes), 1), 10)\n sign = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return ids of users who voted this post up | def get_voter_ids(self):
select = PostUpvote.select(PostUpvote.post_id == self.id)
rs = db.engine.execute(select)
ids = rs.fetchall() # list of tuples
return ids | [
"def get_already_voted(request):\n ip = request.META.get('REMOTE_ADDR', '0.0.0.0')\n posted = [feedback.id()\n for feedback in Feedback.all(keys_only=True).filter('ip', ip)]\n voted = [vote.feedback_id()\n for vote in Vote.all().filter('ip', ip)]\n # logging.debug('posted=%s vot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
allow a user to vote on a post. if we have voted already (and they are clicking again), this means that they are trying to unvote the post, return status of the vote for that user | def vote(self, user_id):
already_voted = self.has_voted(user_id)
vote_status = None
if not already_voted:
# vote up the post
db.engine.execute(
PostUpvote.insert(),
user_id=user_id,
post_id=self.id
)
... | [
"async def downvote(self) -> None:\n await self._state.http.vote_on_user_post(self.author.id64, self.id, 0)",
"def upvotePost(self):\n self.votes = self.votes + 1\n self.save()",
"def _try_adding_vote(self, post_data, user_id):\n clear_screen()\n print('ADD VOTE')\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the raw age of this post in seconds | def get_age(self):
return (self.created_at - datetime.datetime(1970, 1, 1)).total_seconds() | [
"def get_age(self):\n return (self.created_at - datetime(1970, 1, 1)).total_seconds()",
"def age(self):\n return time.time() - self.create_epoch",
"def age(self):\n birth_date = self.patient.get('birth_date', None)\n if birth_date:\n diff = self.created.date() - birth_date... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To get the icon path | def icon_path(self):
return self.__icon_path | [
"def icon_path(self):\n return os.path.join(settings.MEDIA_ROOT, settings.ICON_DIR, self.icon_file_name)",
"def get_individual_icon_path(self):\n path = self.get_path()\n if path is None:\n return None\n\n # Try to read diricon.\n icon_path = os.path.join(path, '.DirI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To delete the saved memory lines layer | def __memoryLinesLayerDeleted(self):
self.__memoryLinesLayer = None
QgsProject.instance().writeEntry("VDLTools", "memory_lines_layer", None) | [
"def connectionLost(self):\n del self.lines",
"def del_line0(self):\n self._del_line0()",
"def del_kb(self):\n self.kb = None",
"def _erase(self):\n ds9Cmd(\"regions delete all\", flush=True, frame=self.display.frame)",
"def clear_slctns(self):\n for mrkr in self.mrkrs: se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To delete the saved memory points layer | def __memoryPointsLayerDeleted(self):
self.__memoryPointsLayer = None
QgsProject.instance().writeEntry("VDLTools", "memory_points_layer", None) | [
"def delete_lens_model_cach(self):\n for model in self._point_source_list:\n model.delete_lens_model_cache()",
"def cleanup(self):\n os.system(\"rm -rf /dev/shm/images/kinect_rgb\")\n os.system(\"rm -rf /dev/shm/images/kinect_depth\")",
"def delete_all_on_layer(self):\n bp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To get the saved memory points layer | def pointsLayer(self):
return self.__memoryPointsLayer | [
"def savepoints(self):\n raise NotImplementedError()",
"def saveFeatures(self):\n return self.all_features, self.featureParams, self.featureDim",
"def saved_tensors(self):\n return self.__args__",
"def get_checkpoint_data(self):\n pass",
"def output(self):\n return self.layers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To get the saved memory lines layer | def linesLayer(self):
return self.__memoryLinesLayer | [
"def getDrawing(self):\r\n return (self.lineList)",
"def _get_model_dump(self):\n self.model.dump_model(self.TREE_DUMP_FILENAME)\n with open(self.TREE_DUMP_FILENAME, \"r\") as infile:\n dump_lines = infile.read().split(\"\\n\")[:-1]\n os.remove(self.TREE_DUMP_FILENAME)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To get the saved config table (for import tool) | def configTable(self):
return self.__configTable | [
"def load_config(self):\n cur = self.con.cursor()\n cur.execute('SELECT key, value FROM {}'.format(self.config_tab))\n\n return {x[0]: x[1] for x in cur.fetchall()}",
"def get_configured_tables():\r\n try:\r\n return CONFIGURATION['tables'].keys()\r\n except KeyError:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To set the saved memory points layer | def setPointsLayer(self, pointsLayer):
self.__memoryPointsLayer = pointsLayer
id = None
if pointsLayer is not None:
id = pointsLayer.id()
self.__memoryPointsLayer.layerDeleted.connect(self.__memoryPointsLayerDeleted)
QgsProject.instance().writeEntry("VDLTools", "m... | [
"def savepoints(self):\n raise NotImplementedError()",
"def saveViewportSettings():\n pass",
"def save(self):\n self.vis.save([self.vis.env])",
"def storeCamera(self):\n self.camera.store()",
"def saveToolSettings():\n pass",
"def hook_save_checkpoint_path(self, x):\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To set the saved config table | def setConfigTable(self, configTable):
self.__configTable = configTable
QgsProject.instance().writeEntry("VDLTools", "config_table", configTable) | [
"def setup(self):\n scripts = []\n script = '''CREATE TABLE settings (\n id INTEGER PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n value TEXT NOT NULL) WITHOUT ROWID\n '''\n scripts.append(script)\n script = '''INSER... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Add optional flags to GooGet command. | def _AddFlags(self,
flags: List[str],
branch: Optional[str] = None) -> List[str]:
if not isinstance(flags, list):
raise GooGetFlagError('GooGet flags were not passed as a list')
# URL should be kept separate from other optional flags
url, options = [], []
if re.se... | [
"def request_fewer_flags(self, req, msg):",
"def add_opts(self, optparser):\n return",
"def _cli_extras(self):\n kwargs = self.kwargs or {}\n extras = [\n \"--silent\",\n ]\n for k, v in kwargs.items():\n extras.append(\"--\" + k.replace(\"_\", \"-\"))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initialize weight matrices theta1 and theta2 via choosing a good epsilon value to break the symmetry | def initialize_weights(self):
eps = np.sqrt(6) / (np.sqrt(self.inp_nodes + self.output_nodes))
theta1 = np.random.rand(self.hidden_nodes, self.inp_nodes + 1) * (2 * eps) - eps
theta2 = np.random.rand(self.output_nodes, self.hidden_nodes + 1) * (2 * eps) - eps
return theta1, theta2 | [
"def randInitializeWeights(L_in, L_out):\n epsilon_init = 0.12\n W = np.random.rand(L_out, 1+L_in)*2*epsilon_init-epsilon_init\n return W",
"def randInitializeWeights(L_in, L_out):\n\n # Initialize W randomly so that we break the symmetry while training the neural network.\n # Sample W from Uniform... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set number of input, hidden, and output nodes that define the network and set dictionary of y labels | def architecture(self, inp_nodes, hidden_nodes, output_nodes):
self.inp_nodes = inp_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
self.labels = np.eye(self.output_nodes, dtype=int) | [
"def setupNetwork(self, input_size, hidden_size):\r\n self.inputSize = input_size\r\n self.hiddenSize = hidden_size\r\n \r\n self.input = [0.0] * input_size # value of input node\r\n self.input.append(1.0) # bias for hidden layer\r\n \r\n self.hidden = [0.0] * hid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create matrix that represents each y label as a row vector in this matrix | def create_y_matrix(self):
self.y_matrix = np.zeros((self.m, self.output_nodes), dtype=int)
for i in range(self.m):
label = int(self.y[i])
self.y_matrix[i] = self.encode_label(label)
self.labels = np.eye(self.output_nodes, dtype=int) | [
"def __get_y_mat(self, yval):\n\n y = np.zeros((10,1))\n y[yval,0] = 1\n return y",
"def expandY(y,n):\n m = np.size(y)\n yset = np.eye(n)\n # convert class label to its index in vector. \n y = (y - 1).astype(int)\n # the result matrix\n yres = np.zeros((m,n))\n for i in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return predicted class for new instance | def predict(self, instance):
instance = np.array([[1] + instance])
z2 = instance.dot(self.opt_theta1.T)
a2 = np.append(arr=np.array([[1]]), values=self.sigmoid(z2), axis=1)
z3 = a2.dot(self.opt_theta2.T)
a3 = self.sigmoid(z3)
h = a3[0].tolist()
idx = h.index(max(h... | [
"def make_prediction(pred_head):\n print(\"predicting---------------------------------\")\n print(\"head is \", pred_head)\n print(\"body is \", pred_body)\n\n res = model.predict([pred_head], pred_body)\n print(classes[res[0]])\n return classes[res[0]]",
"def predict(self, test_example):\r\n\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |