query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Creation of a Concrete Model, specify the countries and sectors to include. | def __init__(self, name, list_countries,list_sectors,list_products,EORA=False):
self.name = name
self.m = ConcreteModel()
self.countries = list_countries
self.total_countries = len(list_countries)
self.sectors = list_sectors
self.products = list_products
... | [
"def __init__(self, name, list_countries,list_sectors,EORA=False,list_fd_cats=[]):\n self.name = name\n self.m = ConcreteModel()\n self.countries = list_countries\n self.total_countries = len(list_countries)\n self.sectors = list_sectors\n self.fd_cat = list_fd_cats\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creation of the various sets. First step in futureproofing by allowing for own specification of set inputs | def create_sets(self,FD_SET=['FinalD'],VA_SET=['VA']):
self.m.S = Set(initialize=self.sectors, doc='sectors')
self.m.P = Set(initialize=self.products, doc='sectors')
self.m.row = Set(initialize=self.products, doc='products')
self.m.col = Set(initialize=self.sectors+['FinalD'], do... | [
"def create_sets(self,FD_SET=[],VA_SET=[]):\n \n self.m.S = Set(initialize=self.sectors, doc='sectors')\n\n if self.EORA is True:\n self.m.rROW = Set(initialize=self.countries+['ROW'],ordered=True, doc='regions including export')\n self.m.R = Set(initialize=self.countries+... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the 'index'th row of 'dataframe' as a json formated string. If 'index' is not set or out of bounds, and random row is extracted. | def get_data(dataframe,index=None):
dflen = len(dataframe)
if index==None or index <0 or index >= dflen:
index = randint(0,dflen)
return dataframe.iloc[index].to_json() | [
"def getFullRow(self, index):\n try:\n if len(self.data[index]) < self._numAttributes:\n for _ in range(self._numAttributes - len(self.data[index])):\n self.data[index].append(\"?\")\n return self.data[index]\n except Exception as e:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper function to resize list of np.ndarray (of possibly different size) to single np array of same size this is the same as BaseRuntime implementation, apart from h,w is flipped | def resize_batch(images : List[np.ndarray], size : Tuple[int,int,int,int], resize_kind='stretch') :
assert resize_kind in ['stretch'] and len(size) == 4
n, w, h, c = size if size[-1]==3 else tuple(size[i] for i in [0,3,1,2])
resize = lambda x: BaseRuntime.resize_stretch(x, (h,w))
dtype =... | [
"def _resize(self):\n temp = None\n if len(self) == len(self._items):\n temp = Array(2 * len(self._items))\n \n elif len(self) <= len(self._items) // 4 and \\\n len(self._items) >= 2 * ArrayList.DEFAULT_CAPACITY:\n temp = Array(len(self._items) // 2)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
่ฝๅค่ฐ็จไปปไฝๅฝขๅผ็นๅพ็นๆฃๆตใๅฏไปฅๅ
ทไฝ่ฏ้ๅผ,ๆฏๅฆๆๅผๆๅถใ ็ธ้ป,ๆไธ็งๆ ๅฟ: cv2.FAST_FEATURE_DETECTOR_TYPE_5_6 cv2.FAST_FEATURE_DETECTOR_7_12 cv2.FAST_FEATURE_DETECTOR_TYPE_9_16 | def fast_feature_detector():
img = cv2.imread('image/cube.jpg', 0)
# initiate FAST object with default values
fast = cv2.FastFeatureDetector_create()
# find and draw the keypoints
kp = fast.detect(img, None)
imgCy = img.copy()
img2 = cv2.drawKeypoints(img, kp, outImage=imgCy, color=(255,... | [
"def detect(self, features):\n pass # TODO",
"def detect(self, detect_img):\n features = self.classifier.detectMultiScale(detect_img,1.3,5)\n self.features = features\n self.features_detected = True",
"def extract_features(self, img):\r\n raise NotImplementedError",
"def h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
general method used to catch all excetions and data will be pushed to database collection named "toolLogs". | def catchError(custom_message = ""):
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback_details = {
'filename': exc_traceback.tb_frame.f_code.co_filename,
'lineno' : exc_traceback.tb_lineno,
'name' : exc_trace... | [
"def LogDbError():\n pass",
"def logtool(ctx):",
"def capture_exception():\n\n pm_logger.exception()\n exc_type, exc_value, exc_tb = sys.exc_info()\n exc_type_string = \"%s.%s\" % (exc_type.__module__, exc_type.__name__)\n exc_message = traceback.format_exception_only(exc_type... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a specific ComputedFile based on id | def get(cls, id):
response = get_by_endpoint("computed_files/" + str(id)).json()
return ComputedFile(**response) | [
"def get(self, id):\n return File.query.filter(File.fileid == id).one()",
"def _get_file_by_id(id):\n query = \"\"\"SELECT * FROM files WHERE id = (:id) LIMIT 1\"\"\"\n param_obj = {'id': id}\n return _execute(query, param_obj)",
"def get_file_by_id(id):\n return my_query(construct_get_file_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a list of a ComputedFiles based on filters | def search(cls, **kwargs):
response = get_by_endpoint("computed_files", params=kwargs)
return create_paginated_list(cls, response) | [
"def get_catalog_files(self):\n files = map(catalog_path,self.build_search_order())\n files = filter(lambda x: x is not None,files)\n return files",
"def generate_filtered_files(raw_files):\n with open(\"./cloud/lambda_functions/Crawler-Master/IBX50.txt\") as f:\n stock_list = f.rea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract a downloaded ComputedFile | def extract(self):
if not self._downloaded_path:
raise MissingFile(
"ComputedFile downloaded file",
"Make sure you have successfully downloaded the ComputedFile before extracting.",
)
shutil.unpack_archive(self._downloaded_path)
return sel... | [
"def get(cls, id):\n response = get_by_endpoint(\"computed_files/\" + str(id)).json()\n return ComputedFile(**response)",
"def _download_and_extract(self) -> None:\n\n # To be implemented here, the code to download from self._archive_url and to extract the\n # data into the self._path.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a list of all the words in a text file | def get_words_in_file(file_name):
lines = get_file_contents(file_name)
all_words = []
for line in lines:
# remove lines that don't have words on them
if len(line) < 2:
continue
line = line.rstrip() # removes \n at the end of each line
words = line.split()
for word in words:
all_words.append(word)
... | [
"def read_txt(filename):\n file_object = open(filename, 'r')\n file_as_string = file_object.read()\n return create_word_list(file_as_string)",
"def get_word_list(filename):\n f = open(filename,'r')\n word_list = list()\n for line in f:\n for word in line.split():\n word_list.ap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the count of all the words in a text file | def count_words_in_file(file_name):
return len(get_words_in_file(file_name)) | [
"def count_words(filename):",
"def count_all_words(file_name):\n\n return len(separate_words(file_name))",
"def countWords(filename):\n with open(filename) as f:\n filetext = f.read()\n #words = re.findall(r'\\w+', filetext)\n words = re.findall(r'[a-zA-Z]+', filetext)\n return Counter(wor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the number of instances of a specific word in a text file | def count_word_instances_in_file(file_name, target_word):
count = 0
words = get_words_in_file(file_name)
for word in words:
if target_word == word:
count += 1
return count | [
"def findword(filename, word):\r\n #open the file\r\n fp = open(filename)\r\n #read the file\r\n data = fp.read().split()\r\n #count the number of words\r\n s = len([item for item in data if item == word])\r\n #close the file\r\n fp.close()\r\n #return the count\r\n return(s)",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepares an appropriate form for submitting a rangebased action. | def action_form(is_check, is_raise, can_raise, min_raise, max_raise):
passive_label = "Check range:" if is_check else "Call range:"
aggressive_label = "Raise range:" if is_raise else "Bet range:"
total_label = "Raise total:" if is_raise else "Bet total:"
min_raise = min_raise if min_raise is not None el... | [
"def custom_actions(self, form_entry, request=None):",
"def make_form(self):",
"def query_form_data(self) -> FlaskResponse: # pylint: disable=no-self-use\n form_data = {}\n slice_id = request.args.get(\"slice_id\")\n if slice_id:\n slc = db.session.query(Slice).filter_by(id=slic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implements rosnode 'list' command. | def _rosnode_cmd_list(argv):
args = argv[2:]
parser = OptionParser(usage="usage: %prog list", prog=NAME)
parser.add_option("-u",
dest="list_uri", default=False,
action="store_true",
help="list XML-RPC URIs (NOT IMPLEMENTED)")
parser.add_o... | [
"def list():\n rino.remote.list()",
"def list_node(self, *args, **kwargs) -> List[models.Node]:\n return self._backend.list(schemas.Type.Node)",
"def list(self):\r\n return self.vmrun('list')",
"def cmd_list(cls, args):\n\n hc2 = cls.get_args_hc2(args)\n hc2.room_list()",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints rosnode usage information. return_error whether to exit with error code os.EX_USAGE | def _fullusage(return_error=True):
print("""rosnode is a command-line tool for printing information about ROS Nodes.
Commands:
\trosnode ping\ttest connectivity to node (NOT IMPLEMENTED)
\trosnode list\tlist active nodes
\trosnode info\tprint information about node (NOT IMPLEMENTED)
\trosnode machine\tlist nodes ru... | [
"def usage(prtflag):\n\n\t#\n\t# Set up our usage string.\n\t#\n\toutstr = \"\"\"hostxref [options]\n\n where [options] are:\n\n\t\t-find - base protocol for searching other protocols\n\t\t-nozero - only display matches\n\t\t-originator - specify originator address list to search for\n\t\t-re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update rules within a rule group. Return the updated rules. | def update_rules(self: object,
body: dict,
cs_username: str = None # pylint: disable=W0613 # cs_username is deprecated
) -> dict:
# [PATCH] https://assets.falcon.crowdstrike.com/support/api/swagger.html#/custom-ioa/update-rules
return proc... | [
"def update_rules():\n update_all_rules()\n return \"OK\"",
"def update_rule_group_rules(client: boto3.client,\n kwargs: dict,\n lock_token: str,\n updated_rules: list,\n rule_group_visibility_config:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all rule groups matching the query with optional filter. | def query_rule_groups_full(self: object, parameters: dict = None, **kwargs) -> dict:
# [GET] https://assets.falcon.crowdstrike.com/support/api/swagger.html#/custom-ioa/query-rule-groups-full
return process_service_request(
calling_object=self,
endpoints=Endpoints,
ope... | [
"def searchGroups(**criteria):",
"def get_group_filter():",
"def filter_groups(self):\n return self._filter_groups",
"def matches_groups_all(self, request):\n matches_group_a = get_group_matches('A')\n matches_group_b = get_group_matches('B')\n matches_group_c = get_group_matches('... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Infer which device this policy lives on by inspecting its parameters. If it has no parameters, the 'cpu' device is used as a fallback. | def device(self) -> torch.device:
for param in self.parameters():
return param.device
return get_device("cpu") | [
"def device(self) -> th.device:\n for param in self.parameters():\n return param.device\n return get_device(\"cpu\")",
"def get_device():\n is_device_available = {\n 'cuda': torch.cuda.is_available(),\n 'mlu': is_mlu_available()\n }\n device_list = [k for k, v in is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load parameters from a 1D vector. | def load_from_vector(self, vector: np.ndarray) -> None:
nn.utils.vector_to_parameters(torch.FloatTensor(
vector).to(self.device), self.parameters()) | [
"def load_from_vector(self, vector: np.ndarray) -> None:\n th.nn.utils.vector_to_parameters(th.FloatTensor(vector).to(self.device), self.parameters())",
"def loadVector(vector):\n expVecCmmd = 'v.out.ascii format=standard input=' + vector\n# JL p = Popen(expVecCmmd, shell=True, stdin=PIPE, stdout=PIP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert the parameters to a 1D vector. | def parameters_to_vector(self) -> np.ndarray:
return nn.utils.parameters_to_vector(self.parameters()).detach().cpu().numpy() | [
"def parameters_to_vector(self) -> np.ndarray:\n return th.nn.utils.parameters_to_vector(self.parameters()).detach().cpu().numpy()",
"def to_vector(self):\n return self.params",
"def make_vector(x):\n return np.array(x).flatten()",
"def ones() -> \"Vec2d\":\r\n return Vec2d(1, 1)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(bool) Getter for squash_output. | def squash_output(self) -> bool:
return self._squash_output | [
"def secure_output(self) -> Optional[bool]:\n return pulumi.get(self, \"secure_output\")",
"def has_output(self):\n status = self.is_running()\n self.write_queued_output()\n return status",
"def logging_outputs_can_be_summed() -> bool:\n return True",
"def no_root_squash(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rescale the action from [low, high] to [1, 1] (no need for symmetric action space) | def scale_action(self, action: np.ndarray) -> np.ndarray:
low, high = self.action_space.low, self.action_space.high
return 2.0 * ((action - low) / (high - low)) - 1.0 | [
"def rescale_action(self, scaled_action):\n return self.low + (0.5 * (scaled_action + 1.0) * (self.high - self.low))",
"def rescale_action(self, action: np.ndarray) -> np.ndarray:\n action_rescaled = (\n action * (self.action_max - self.action_min) / 2.0\n + (self.action_max + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve action distribution given the latent codes. | def _get_action_dist_from_latent(self, latent_pi: torch.Tensor) -> Distribution:
mean_actions = self.action_net(latent_pi)
if isinstance(self.action_dist, DiagGaussianDistribution):
return self.action_dist.proba_distribution(mean_actions, self.log_std)
elif isinstance(self.action_di... | [
"def get_action_distribution(self, state):\n return self.sess.run(self.outputs, feed_dict={self.s: [state]})[0]",
"def _get_action_dist_from_latent(self, latent_pi: th.Tensor, latent_sde: Optional[th.Tensor] = None) -> Distribution:\n mean_actions = self.action_net(latent_pi)\n\n if isinstanc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test to check if we can find a credential entry by account name and display the details of the credential | def test_find_credentials(self):
self.new_credentials.save_credentials()
new_account= Credentials("Twitter","josephat_otieno", "joseotis45")
new_account.save_credentials()
found_credential= Credentials.find_credentials("Twitter")
self.assertEqual(found_credential.account_name,n... | [
"def test_find_creds(self):\n self.new_acc.save_acc()\n testacc4 = AccountDetails(\"peter123\", \"Gmail\", \"qwert123\")\n testacc4.save_acc()\n \n found_creds = AccountDetails.find_creds(\"peter123\")\n self.assertEqual(found_creds.acc_username,testacc4.acc_username)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute a vector stabilized by an element of the monster Le ``g`` be an element of the monster group of order ``n`` and ``v`` a vector in a represention of the monster. We return the vector ``sum(v gi for i in range(n))`` which is stabilized by ``g``. We always return ``None`` if that sum is 0 or a multiple of the 1 el... | def stabilizer_vector(v, g, n):
vg = v.copy()
w = v.copy()
for i in range(1, n):
vg *= g
w += vg
assert v == vg * g
if (w['B'] == 0).all():
return None
return w | [
"def _eval(self, v):\n\n # Positivity penalty\n if np.min(v) < -1e-3:\n return np.inf\n\n # Other penalties\n vsum = v.copy()\n vsum -= self.bp * np.log(np.maximum(v, 1e-9))\n return vsum.sum()",
"def g(s, v):\n\n if len(s) == 0:\n return cost(v_start... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return ``g1 == g2`` for elements ``g1, g2`` of the monster. If ``mode == 0`` (default) we first try to check equality inside in the subgroup ``N_0`` of the monster, which may be considerbly faster. If ``mode != 0`` or this is not possible we check if ``v g1 g2(1) == v`` holds for the ORDER_VECTOR ``v``. We just check t... | def check_mm_equal(g1, g2, mode = 0):
assert isinstance(g1, (MM, MM0))
assert isinstance(g2, (MM, MM0))
g3 = np.zeros(2 * (g1.length + g2.length) + 1, dtype = np.uint32)
status = mm_group_words_equ(g1._data, g1.length,
g2._data, g2.length, g3)
if status < 2:
return not status
v ... | [
"def check_mm_order_old(g, max_order = 119, mode = 0):\n assert isinstance(g, (MM0, MM))\n g.reduce()\n if mode == 0:\n n0 = np.zeros(5, dtype = np.uint32)\n status = mm_group_check_word_n(g._data, g.length, n0)\n if status == 0:\n return 1\n if status == 1:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return order of monster group element ``g``. if ``order(g) < max_order`` return ``order(g)``; else return ``0``. If mode is ``0`` (default) we first check if ``g`` is in the subgroup ``N_0 of`` the monster. If this is the case the we check the order of ``g`` by calculating in ``N_0``. Othewise we compute the minimum ``... | def check_mm_order_old(g, max_order = 119, mode = 0):
assert isinstance(g, (MM0, MM))
g.reduce()
if mode == 0:
n0 = np.zeros(5, dtype = np.uint32)
status = mm_group_check_word_n(g._data, g.length, n0)
if status == 0:
return 1
if status == 1:
n1 = np.co... | [
"def check_mm_order(g, max_order = 119):\n assert isinstance(g, (MM0, MM))\n g.reduce()\n v = get_order_vector().data\n o = mm_op15_order(g._data, g.length, ORDER_TAGS, v, max_order)\n return chk_qstate12(o)",
"def elementorder(self, elem):\n assert hasattr(self, grouporder), \"tell me the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return order of monster group element ``g``. ``g`` must be an instance of class ``MM``. The function returns the order of ``g`` if ``max_order`` is set to its default value. Computing the order of an element of the monster is time consuming; and in some cases we are interested in small orders only. If ``max_order``is g... | def check_mm_order(g, max_order = 119):
assert isinstance(g, (MM0, MM))
g.reduce()
v = get_order_vector().data
o = mm_op15_order(g._data, g.length, ORDER_TAGS, v, max_order)
return chk_qstate12(o) | [
"def check_mm_order_old(g, max_order = 119, mode = 0):\n assert isinstance(g, (MM0, MM))\n g.reduce()\n if mode == 0:\n n0 = np.zeros(5, dtype = np.uint32)\n status = mm_group_check_word_n(g._data, g.length, n0)\n if status == 0:\n return 1\n if status == 1:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return (halved) order of monster group element ``g``. ``g`` must be an instance of class ``MM``. The function returns a pair ``(o, h)`` where ``o`` is the order of ``g``, and ``h = g(o/2)`` for an even ``o``. We put ``h = None`` if ``o`` is odd. Parameter ``max_order`` is as in function ``check_mm_order``. | def check_mm_half_order(g, max_order = 119):
assert isinstance(g, (MM0, MM))
g.reduce()
h = np.zeros(10, dtype = np.uint32)
v = get_order_vector().data
o1 = mm_op15_order_Gx0(g._data, g.length, ORDER_TAGS, v, h, max_order)
chk_qstate12(o1)
if o1 == 0:
return 0, None
h = h[:o1 & 0... | [
"def check_mm_order(g, max_order = 119):\n assert isinstance(g, (MM0, MM))\n g.reduce()\n v = get_order_vector().data\n o = mm_op15_order(g._data, g.length, ORDER_TAGS, v, max_order)\n return chk_qstate12(o)",
"def check_mm_order_old(g, max_order = 119, mode = 0):\n assert isinstance(g, (MM0, M... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if ``g`` is in the subgroup ``G_x0`` of the monster If ``g`` is in the subgroup ``G_x0`` of the monster then the function changes the word representing ``g`` to a (uniquely defined) word in the generators of the subgroup ``G_x0`` and returns ``g``. Otherwise the function does not change ``g`` and returns ``None``... | def check_mm_in_g_x0(g):
g1 = np.zeros(10, dtype = np.uint32)
v = get_order_vector().data
res = chk_qstate12(mm_op15_order_Gx0(g._data, g.length,
ORDER_TAGS, v, g1, 1))
#print("RES", hex(res))
if ((res >> 8) != 1):
return None
length = res & 0xff
assert length <= 10
g.... | [
"def contains(self, g):\n if not isinstance(g, FreeGroupElement):\n return False\n elif self != g.group:\n return False\n else:\n return True",
"def reduce_mm(g, check = True):\n global reduce_mm_time\n v = get_order_vector().data\n g1 = np.zeros(256,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The fastest reduction procedure for a monster element ``g`` | def reduce_mm(g, check = True):
global reduce_mm_time
v = get_order_vector().data
g1 = np.zeros(256, dtype = np.uint32)
t_start = time.perf_counter()
res = mm_op15_reduce_M(g._data, g.length, ORDER_TAGS, v, g1)
reduce_mm_time = time.perf_counter() - t_start
if (res < 0):
err = "Redu... | [
"def reduction1(g: nx.MultiGraph, k):\n changed = False\n vs = list(nx.nodes_with_selfloops(g))\n for v in vs:\n g.remove_node(v)\n k -= 1\n changed = True\n return k, vs, changed",
"def _compute_hard_gd_update(self, grads):",
"def average_global_efficiency(G):\n n = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
increment the count of the attacks / messages about some anomolous packet | def incr_no_of_attacks(self):
self.__anom += 1
self.__anom_lbl.setText(str(self.__anom)) | [
"def touch_packet (self, byte_count, now=None):\n if now is None: now = time.time()\n self.byte_count += byte_count\n self.packet_count += 1\n self.last_touched = now",
"def increment_etherscan_calls():\n _increment_counter(\"etherscan_calls\")",
"def __increase_counter(self):\r\n self.__c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set an icon, add a menu and add actions to the menu | def set_up_icon(self):
self.__menu = QMenu()
self.__show = QAction("Show")
self.__quit = QAction("Quit")
# signals --> slots
self.__show.triggered.connect(self.show_app_slot)
self.__quit.triggered.connect(self.close_app_slot)
self.__menu.addActions([self.__show, self.__quit])
self.setIcon(QIcon('app.p... | [
"def add(self,name,icon=None):\n if type(icon) == str:\n #print \"CREATE ICON %s\" % icon\n if os.path.exists(icon):\n icon = QtGui.QIcon(QtGui.QPixmap(icon))\n else:\n raise RuntimeError,'Icons not installed properly'\n menutext = '&' + n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set mac address at (row, 1) | def set_mac_at(self, row, mac):
self.__hh_table.item(row, 1).setText(mac) | [
"def setMacAddress(self, adr):\n self.MacAddress = adr",
"def mac(self, mac):\n self._mac = mac",
"def add_mac(self, value):\n self.__add('mac', value)\n return self",
"def mac(self, mac):\n\n self._mac = mac",
"def modify_mac(self, mac=None):\n raise",
"def setma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add mac address to black list | def add_to_blacklist(self):
# get mac
row = self.__hh_table.currentRow()
mac = self.__hh_table.item(row, 1).text()
if mac == 'unknown' or mac == 'resolving ...':
qmb = QMessageBox(self)
qmb.setText('Cannot add machine to black list. Could not resolve MAC address')
qmb.setWindowTitle('Snort Log Serv... | [
"def add_mac(self, mac_address=\"\"):\n if not mac_address:\n logging.warning(\"Incorrect MAC address\")\n return\n #TODO:What if I want to replace other chars as well. Explore regex\n self.ap_list.append(str(mac_address).lower().replace(\":\", \"\"))",
"def add_colons_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and an icon to the system tray | def create_system_tray_icon(self):
self.__sys_tray_icon = SystemTrayIcon()
self.__sys_tray_icon.setVisible(False)
self.__sys_tray_icon.show_app.connect(self.show)
self.__sys_tray_icon.close_app.connect(self.exit_app) | [
"def create_sys_tray_icon(self):\n self.tray = QtWidgets.QSystemTrayIcon()\n self.tray.setIcon(QtGui.QIcon(self.appctxt.get_resource(\"icon.png\")))\n self.tray.setVisible(True)\n self.tray_menu = QtWidgets.QMenu()\n self.tray_menu.addAction(QtGui.QIcon(self.appctxt.get_resource(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a worker thread to handle the Ssh connection | def start_ssh_client_worker(self):
self.__ssh_client_worker = Util.SshClientWorker()
self.__ssh_client_worker.finished.connect(self.__ssh_client_worker.deleteLater)
self.__ssh_client_worker.finished_closing_ssh_connection.connect(
self.__ssh_client_worker.quit)
self.__ssh_client_worker.finished_connecting_t... | [
"def launcher(i,q,cmd):\n while True:\n #grabs ip,cmd from queue\n ip = q.get()\n print \"Thread %s: Running %s to %s\" % (i,cmd,ip)\n host = \"root@%s\"%ip\n subprocess.call([\"ssh\", host, cmd])\n q.task_done()",
"def start(self):\n self.server.connect(self.remote... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate a queue of commands expected to be executed, with regard to action to be | def get_cmds_queue(self):
return Queue() | [
"def queueCommands(self, commands):\n self.queue += AdvancedMap(commands).selectivelyMapResults(lambda x: type(x) is str, lambda x: Utilities.parseCommand(x))",
"def forceQueueCommands(self, commands):\n self.queue = AdvancedMap(commands).selectivelyMapResults(lambda x: type(x) is str, lambda x: Uti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the direction vector (p2p1)/|p2p1| as a sympy matrix | def dirVector(self,p1,p2):
v=p2-p1
l=v.Length
return self.toMatrix(v)/l | [
"def get_rel_pose(self, p1, p2): \n return numpy.dot(numpy.linalg.inv(p1), p2)",
"def l2(p1, p2):\n return np.linalg.norm(np.array(p1) - np.array(p2))",
"def direction(p1, p2):\n return (p2-p1)/distance(p1[0], p1[1], p2[0], p2[1])",
"def prob2():\n x, i, j = sy.symbols('x, i, j')\n expr ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return string representation of the order object | def __str__(self):
return f'{self.order_id}' | [
"def __str__(self):\n order = \"Your order is a \"\n order += self.size + \" \"\n order += self.base\n return order",
"def __repr__(self):\n return '<Order(ID=\"%s\", ProjectID=\"%s\", ClientID=\"%s\")>' % (\n self.ID, self.ProjectID, self.ClientID)",
"def __repr__(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the automation with the given id once or in a loop, looping the optionally specified number of times, otherwise forever. | def run_automation(self, automation_id: int, loop=True, loop_count=None) -> None:
self._load_automation(automation_id)
self.maple_logger.info("Waiting for start key ({0}) to be pressed.", self.START_KEY)
self._wait_for_automation_start_key()
self.maple_logger.info(
"Starti... | [
"async def loop(self, ctx, time: int, command: str):\n\n for x in range(time):\n x = self.bot.get_command(command)\n await ctx.invoke(x)",
"def loop_test(loop_wait=0, loop_times=sys.maxsize):\n looped_times = 0\n\n while looped_times < loop_times:\n # run an API test\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load an automation based on the automation_id. | def _load_automation(self, automation_id: int) -> None:
self.maple_logger.info("Loading automation with ID {0}.", automation_id)
# TODO load the automation dynamically based on automation_id
hand_automation = HandAutomation123()
self.loaded_automation_sequence = hand_automation.get_aut... | [
"def load_experiment(self, experiment_id: str) -> Experiment:\n assert experiment_id in list(self.list_experiments()), f'Error: no experiment {experiment_id} found'\n return Experiment.objects(experiment_id=experiment_id).get()",
"def load(cls, id):\n key = cls.get_key_prefix()+\"#\"+str(id)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the next loop of the loaded automation sequence .. only running the subsequent step if automation is not paused | def _run_next_automation_sequence(self) -> None:
sequence_iterator = iter(self.loaded_automation_sequence)
while True:
# sleep for a bit if we are paused to save resources
if self.paused:
time.sleep(0.1)
else:
sequence_finished = self... | [
"def next_step(self):\n self.proceed()\n self.execute_current()",
"def run(self):\n while self.state is not self.SLEEPING:\n self.step()",
"def run(self):\n\n while not self.__done:\n self.single_cycle()\n\n \"\"\"\n while not self.__done:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save an array of logits to a file | def save_logits(path: str, logits: np.ndarray):
with open(path, 'w') as fh:
for example_logits in logits:
fh.write(' '.join(str(logit) for logit in example_logits) + '\n') | [
"def save_data_to_file(self,file,pixel,class_index):\n \n for i in range(self._n_input):\n \n file.write(str(pixel[i])+',')\n \n file.write(str(class_index+1)+'\\n')",
"def save_array(array, filename):\n np.save(filename, array)",
"def save_tiles(self, tiles,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Trim a sequence of input ids by removing all padding tokens and keeping at most a specific number of mask tokens. | def trim_input_ids(input_ids: torch.tensor, pad_token_id, mask_token_id, num_masks: int):
assert input_ids.shape[0] == 1
input_ids_without_pad = [x for x in input_ids[0] if x != pad_token_id]
trimmed_input_ids = []
mask_count = 0
for input_id in input_ids_without_pad:
if input_id == mask_to... | [
"def apply_trim(alms, idxs):\n return [[row[i] for i in range(len(row)) if i not in idxs] for row in alms]",
"def trimSequences(sequences):\n starts = []\n ends = []\n for s in sequences:\n starts.append(re.search('[atcgATCG]', str(s.seq)).start())\n ends.append(len(s) - re.search('[atcg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
duplicate samples. train_Y has N 1,0 tuples. dup_target_y in [0,N). multiplier must be >=2. append to end of input arrays | def duplicate_train_samples(train_X, train_Y, dup_target_y, multiplier=2):
target_y = train_Y[:,dup_target_y]
#print(target_y)
mask = ma.make_mask(target_y)
additional_X = train_X[mask]
#print(additional_X)
additional_Y = train_Y[mask]
#print(additional_Y)
for i in range(1, multiplier):
train_X = np.conca... | [
"def get_train_dataset(self, X, y, new_cls=None):\n\n # First determine the number of instances per class to sample\n if new_cls:\n n_old_classes = np.unique(y).shape[0] - 1\n n_old_class_examples = len(np.where(y == new_cls)[0])\n samples_per_class = max(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
take two feature dictionaries d1 and d2 as inputs, and it should compute and return their log similarity score | def compare_dictionaries(d1, d2):
score = 0
gef = 0
for z in d1:
gef += d1[z]
total = gef
for x in d2:
if x in d1:
score += math.log(d1[x] / total) * d2[x]
else:
score += math.log(0.5/total) * d2[x]
return score | [
"def compare_dictionaries(d1, d2):\r\n score = 0\r\n total = 0\r\n for x in d1:\r\n total += d1[x]\r\n for x in d2:\r\n if x in d1:\r\n log_sim_score = d2[x]*log(d1[x]/total)\r\n else:\r\n log_sim_score = d2[x]*log(0.5/total)\r\n score+=log_sim_score\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
accepts a string as a parameter. The function should then return the stem of s. The stem of a word is the root part of the word, which excludes any prefixes and suffixes. | def stem(s):
if len(s) < 5 :
return s
if s[-3:] == 'ing':
if s[-4] == s[-5]:
if s[-4] == 'l' :
s = s[:-3]
s = s[:-4]
else:
s = s[:-3]
elif s[-2:] == 'er':
s = s[:-2]
elif s[-1] == 's' :
s = s[... | [
"def stemString(s):\n\ts = clearString(s)\n\treturn stemList(s.split())",
"def stem_word(word):\n\treturn stemmer.stem(word)",
"def stem_singular_word(word):\n return stemku.stem(word)",
"def stemSentence(sentence):\n return stemmer.stem(sentence)",
"def stem_term(self, word):\n if word[0] != '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
computes and returns a list of log similarity scores measuring the similarity of self and other โ one score for each type of feature (words, word lengths, stems, sentence lengths, and your additional feature) | def similarity_scores(self, other):
word_score = []
word_score += [compare_dictionaries(other.words, self.words)]
word_score += [compare_dictionaries(other.word_lengths, self.word_lengths)]
word_score += [compare_dictionaries(other.stems, self.stems)]
word_score += [compare_... | [
"def similarity_scores(self, other):\n lst = []\n word_score = compare_dictionaries(other.words, self.words)\n lst += [word_score]\n wls = compare_dictionaries(other.word_lengths, self.word_lengths)\n lst += [wls]\n stem_score = compare_dictionaries(other.stems, self.stems)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the user ID for later use in logging. | def set_user_id(uid):
local.user_id = uid | [
"def set_userId(self, userId):\n self.authentication.userId = userId",
"def user_id(self, user_id):\n self._user_id = user_id",
"def user_id(self, user_id):\n \n self._user_id = user_id",
"def id_user(self, id_user):\n\n self._id_user = id_user",
"def user_id(self, user_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator returning a Producer instance from a generating function. Producers are multitransversal iterables (not iterators). Generators are 'oneshot' transversal objects. Therefore to support multiple data transversals, Producers can be built from generating functions. This decorater converts any generating function t... | def as_producer(func):
# only decorate generator functions
if not inspect.isgeneratorfunction(func):
msg = 'as_producer requires a generating function not {}'
raise TypeError(msg.format(type(func)))
@functools.wraps(func)
def decorated(pro, *args, **kwargs):
"""Returns a produc... | [
"def kafka_producer(kafka_producer_factory):\n yield kafka_producer_factory()",
"def consumer(func):\n\n from functools import wraps\n\n @wraps(func)\n def wrapper(*args,**kw):\n gen = func(*args, **kw)\n gen.next()\n return gen\n return wrapper",
"def _create_producer(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pads the edges of a producer along its axis. | def pad_producer(pro, pad, value):
#convert int pad to seq. of pads & place along axis of pads
pads = [pad, pad] if isinstance(pad, int) else pad
def genfunc():
left_shape, right_shape = list(pro.shape), list(pro.shape)
left_shape[pro.axis] = pads[0]
right_shape[pro.axis] = pads[1... | [
"def pad_edges(self, pad):\n weights=[]\n for dim, xy in zip([0, 1], [self.x, self.y]):\n xy0 = np.mean(xy)\n W = xy[-1]-xy[0]\n dist = np.abs(xy-xy0)\n wt=np.ones_like(dist)\n wt[ dist >= W/2 - pad] = 0\n weights += [wt]\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the chunksize of this Producer. | def chunksize(self):
return self._chunksize | [
"def chunksize(self):\n\n return self.data.chunksize",
"def getsize(self):\n return self.chunksize",
"def ChunkSize(self):\n if self.force_auto_sync:\n self.get('ChunkSize')\n return self._ChunkSize",
"def chunk_size(self):\r\n return int(self.frame_length * self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets this Producer's chunksize attr ensuring it is int type. | def chunksize(self, value):
self._chunksize = int(value) | [
"def chunksize(self, value):\n\n self.data.chunksize = int(value)\n self.mask.chunksize = int(value)",
"def set_chunk_size(self, n):\n self.chunk_size = n",
"def SET_CHUNK_SIZE(datatype, stream_id, new_size):\n msg = {'msg': datatype, 'stream_id': stream_id, 'chunk_size': new_size}\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a tuple of slice objs. between start and stop indexes. | def _slice(self, start, stop, step=None):
slices = [slice(None)] * self.data.ndim
slices[self.axis] = slice(start, stop, step)
return tuple(slices) | [
"def build_slices(start: Sequence[int], stop: Sequence[int] = None) -> Tuple[slice, ...]:\n if stop is not None:\n check_len(start, stop)\n return tuple(map(slice, start, stop))\n\n return tuple(map(slice, start))",
"def _data_slice(data, start, stop):\n output = []\n \n for scan in r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize this producer with additional required shape. | def __init__(self, data, chunksize, axis, shape, **kwargs):
if shape is None:
msg = 'A {} from a generating function requires a shape.'
raise ValueError(msg.format('Producer'))
super().__init__(data, chunksize, axis, **kwargs)
self._shape = tuple(shape) | [
"def __shape_setup__(cls, **kwargs):\n return ()",
"def __init__(self, shape):\n self.eyes = [(), ()]\n self.shape = shape\n self.state = 0\n self.new_frame()",
"def __init__(self, reference=None):\n if reference is not None and not isinstance(reference, Point):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an iterator yielding ndarrays of chunksize along axis. Since the shape of the arrays yielded from the generating function (i.e. data) may be very small compared to chunksize, we store generated arrays to a temporary array to reduce the number of fifo 'put' calls (see note in FIFOArray.put). | def __iter__(self):
# collector will fetch chunksize array for each 'get' call
collector = FIFOArray(self.chunksize, self.axis)
# make tmp array to hold generated subarrs
tmp = []
tmp_size = 0
for subarr in self.data(**self.kwargs):
tmp.append(subarr)
... | [
"def iterchunks(self, chunklen, stepsize=None, startindex=None,\n endindex=None, include_remainder=True, accessmode=None):\n with self._open_array(accessmode=accessmode) as (ar, _):\n for framestart, frameend in \\\n self.iterindices(chunklen, stepsize=stepsize... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the chunksize of this MaskedProducer. | def chunksize(self):
return self.data.chunksize | [
"def chunksize(self):\n\n return self._chunksize",
"def getsize(self):\n return self.chunksize",
"def ChunkSize(self):\n if self.force_auto_sync:\n self.get('ChunkSize')\n return self._ChunkSize",
"def chunk_size(self):\r\n return int(self.frame_length * self.samp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
On change, set chunksize for both producer and mask. | def chunksize(self, value):
self.data.chunksize = int(value)
self.mask.chunksize = int(value) | [
"def SET_CHUNK_SIZE(datatype, stream_id, new_size):\n msg = {'msg': datatype, 'stream_id': stream_id, 'chunk_size': new_size}\n return msg",
"def _change_block_size(self):\n # Get the current value of the block size \n block_size = int(self.block_size_var.get())\n\n # Set the block size... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate parameters list of the trainings Gets the parameters of SupervisedTrain Add to these parameters the max miss parameter | def prms(widget: QWidget) -> List:
parameters = SupervisedTrain.prms(widget)
parameters.append(
StdPrm("max miss", "", False, StdPrmInput.spinBox, [10],
widget.spinValueChanged, []))
return parameters | [
"def learnable_params(self) -> List[dict]:\n\n extra_learnable_params: List[dict] = [\n {\"params\": self.projector.parameters()},\n {\"params\": self.predictor.parameters(), \"static_lr\": True},\n ]\n return super().learnable_params + extra_learnable_params",
"def make... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scores the result of a step performed by the algorithm Compare the StepResults and the ResultPresentation and get the number of wrong values Get the percent of these values | def score(self) -> Tuple[bool, str, float]:
num_miss = np.sum(self.algorithm_data[:,FieldRolls.StepResult] != self.algorithm_data[:,FieldRolls.ResultPresentation])
num_miss_perc = num_miss * 100/self.algorithm_data.shape[0]
return True, "", num_miss_perc | [
"def accuracy(results):\n return results[1] / (results[0] + results[1]) * 100",
"def get_percentage_false_class(arr_of_results):\n\n count_success = np.zeros_like(arr_of_results[:,0], dtype=float)\n count_correct_prediction = 0\n\n for i in range(len(arr_of_results[0])):\n use = True\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the algorithm study ended Decide if the study finished The study finished if the score (which is the percent of missed) is less then the the algorithm parameter | def finished(self, score) -> Tuple[bool, str, bool]:
finish_level = self.parameters["max miss"]["value"]
return True, "", score < finish_level | [
"def score(self) -> Tuple[bool, str, float]:\n\n num_miss = np.sum(self.algorithm_data[:,FieldRolls.StepResult] != self.algorithm_data[:,FieldRolls.ResultPresentation])\n num_miss_perc = num_miss * 100/self.algorithm_data.shape[0]\n return True, \"\", num_miss_perc",
"def _while_progress(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers an icon name from files found in a directory | def add_icon_name_from_directory(self, icon_name, directory):
for size in self._sizes:
try:
sizedir = '%dx%d' % (size, size)
except TypeError:
sizedir = size
filepath = os.path.join(directory, sizedir, "apps", icon_name)
files = gl... | [
"def find_files():\n directory = os.fsencode( \"icons/\") # Gets folder where icons are located\n \n for file in os.listdir(directory): # Gets every file from folder\n filename = os.fsdecode(file)\n if filename.endswith(\".png\"):\n change_color(\"icons/\" + filename)\n con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers an icon name from a filename | def add_icon_name_from_file(self, icon_name, filename, size=None):
try:# TODO: Make svg actually recognized
pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
self.add_icon_name_from_pixbuf(icon_name, pixbuf, size)
except Exception as e:
print "exception in icons.py Ic... | [
"def createIcon(self, name):\n path = 'data/images/' + name\n icon = QtGui.QIcon(path)\n return icon",
"def ionfn(name):\n filename = os.path.abspath(os.path.join(_ICON_DIR, \"ionicons\", \"png\", \"512\", \"{}.png\".format(name)))\n if not os.path.exists(filename):\n raise FileN... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers an icon name from a pixbuf | def add_icon_name_from_pixbuf(self, icon_name, pixbuf, size=None):
if size is None:
size = pixbuf.get_width()
Gtk.IconTheme.add_builtin_icon(icon_name, size, pixbuf)
# print "added ",icon_name, size | [
"def seticon(iconname):\n # from an anonymous commentator to pygame docs site.\n icon=pygame.Surface((32,32))\n icon.set_colorkey((0,0,0))#and call that color transparant\n rawicon=pygame.image.load(iconname)#must be 32x32, black is transparant\n for i in range(0,32):\n for j in range(0,32):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for new updates every 8 hours and when the bot starts | async def check():
while True:
if rss.check_new():
item = rss.most_recent()
queue = format_message.format_notes(item)
for message in queue:
await client.send_message(client.get_channel("350634825516056577"), message)
await asyncio.sleep(2880... | [
"async def check_for_updates(self):\n await self.bot.wait_until_ready()\n while self.bot.get_cog(\"UpdateNotify\") == self:\n message = await self.update_check()\n if message:\n app_info = await self.bot.application_info()\n await app_info.owner.send... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves a router by any of its subnet address | def _get_router_by_ip_address(self, subnet_cidr):
router_id = None
subnets = self.neutron.list_subnets(cidr=subnet_cidr, tenant_id=self.project_id)
try:
subnet_id = subnets['subnets'][0]['id']
except (IndexError, KeyError) as e:
msg = "No subnet found with cidr a... | [
"def arp_scan(subnet):\n\n answered = scapy.arping(subnet)[0]\n\n machines = []\n for i in answered:\n ip, mac = i[1].psrc, i[1].hwsrc\n try:\n host = socket.gethostbyaddr(i[1].psrc)[0]\n except Exception:\n host = \"??\"\n machines.append({\"ip\": ip, \"ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves Floating IP router network port ID | def get_fip_router_interface(self, net_name):
nets = self.neutron.list_networks(tenant_id=self.project_id, name=net_name)
try:
net_id = nets['networks'][0]['id']
except (IndexError, KeyError) as e:
msg = "No network found with name %s!" % net_name
logger.error... | [
"def _get_nport(self):\n return self.__nport",
"def get_port_number(self):\n return self.port",
"def Port(self) -> int:",
"def get_network_id(self, req, mac, server_id=None):\n try:\n attributes_port = {\n \"mac_address\": mac\n }\n ports = self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a static route on a router which owns any interface with the router_cidr param | def configure_route(self, router_subnet_cidr, destination, next_hop):
router = self._get_router_by_ip_address(router_subnet_cidr)
logger.info("Adding static route on VIM %s router=%s destination=%s, nexthop=%s",
self.vim_name, router['id'], destination, next_hop)
routes = ... | [
"def _add_new_route(dcidr, router_ip, vpc_info, con, route_table_id):\n try:\n instance, eni = find_instance_and_eni_by_ip(vpc_info, router_ip)\n\n logging.info(\"--- adding route in RT '%s' \"\n \"%s -> %s (%s, %s)\" %\n (route_table_id, dcidr, router_ip, in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a static route on a router which owns any interface with the router_cidr param | def remove_route(self, router_subnet_cidr, destination, next_hop):
router = self._get_router_by_ip_address(router_subnet_cidr)
logger.info("Removing static route from VIM %s router=%s destination=%s, nexthop=%s",
self.vim_name, router['id'], destination, next_hop)
routes =... | [
"def del_returned_route_on_gw(self, context, router_id, subnet_id):\n LOG.debug('OVNL3RouterPlugin::')\n ovn_router_name = utils.ovn_gateway_name(router_id)\n subnet = self._plugin.get_subnet(context, subnet_id)\n route = {'destination': subnet['cidr'], 'nexthop': '169.254.128.2'}\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a security policy rule on the openstack to allow traffic incoming into VNFs and SFCs | def configure_security_policies(self, ip_proto, port_range_min=None, port_range_max=None):
# if ip_proto is None:
# ip_proto = 61 # any
# msg = "IP Protocol must have a value!"
# logger.error(msg)
# raise VIMAgentsException(ERROR, msg)
#
if ip_pro... | [
"def configure_traffic_src_policy(self, sfc_descriptor, origin, src_id, cp_out, database):\n\n if origin != INTERNAL:\n raise NFVOAgentsException(ERROR, \"OSM Agent does not allow incoming traffic from external networks!\")\n\n vnfp = database.list_catalog(vnf_pkg_id=src_id)\n vnfp_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if mongod is up and listening on defined port | def is_mongod_running(self):
try:
_connect_to_mongo_port(int(self.port))
return True
except OSError:
return False
except Exception:
return False | [
"def did_mongod_start(self, port=0, timeout=60):\r\n if port == 0:\r\n port = self.port\r\n \r\n while timeout > 0:\r\n time.sleep(1)\r\n try:\r\n _connect_to_mongo_port(int(port))\r\n return True\r\n except OSError as ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait timeout secs trying to connect to mongod defined port. Return True as soon as connection succeed or False if could not connect after timeout. | def did_mongod_start(self, port=0, timeout=60):
if port == 0:
port = self.port
while timeout > 0:
time.sleep(1)
try:
_connect_to_mongo_port(int(port))
return True
except OSError as ex:
prin... | [
"def _connect_to_mongo_port(port):\r\n \r\n sock = socket.socket()\r\n sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\r\n sock.settimeout(1)\r\n sock.connect((\"localhost\", int(port)))\r\n sock.close()",
"def check_server(ip='191.30.80.131', port=23, timeout=3):\n s = socket... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start mongod instance using defined port and db path | def start(self):
if self.is_mongod_running():
return
cmd = self.mongod_bin + " --port " + str(self.port) + " --smallfiles --dbpath " + self.db_path + " > /dev/null &"
#if self.kwargs.get('noJournal'):
#argv += ['--nojournal']
#if self.kwa... | [
"def launch_local_mongodb(self):\n import subprocess\n from pypeapp.lib.Terminal import Terminal\n from pypeapp.lib.mongo import get_default_components\n\n self._initialize()\n t = Terminal()\n\n # Get database location.\n try:\n location = os.environ[\"AV... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to connect to mongod listening port. Raise exception under failure | def _connect_to_mongo_port(port):
sock = socket.socket()
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.settimeout(1)
sock.connect(("localhost", int(port)))
sock.close() | [
"def did_mongod_start(self, port=0, timeout=60):\r\n if port == 0:\r\n port = self.port\r\n \r\n while timeout > 0:\r\n time.sleep(1)\r\n try:\r\n _connect_to_mongo_port(int(port))\r\n return True\r\n except OSError as ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses ALTextToSpeech to vocalize the given string. If "block" argument is False, makes call asynchronous. | def say(self, text, block = True):
if block:
self.tts.say(text)
else:
self.tts.post.say(text) | [
"def play(self, blocked=True):\n subprocess = ev3.Sound.speak(self.text)\n if blocked:\n subprocess.wait()",
"def speak(text):\r\n engine.say(text)\r\n engine.runAndWait()\r\n print(text)",
"def Say(self, words, block=True):\n if self.talker_simulated:\n try:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Has the robot ask a question and returns the answer | def ask(self, question):
# If you're just trying to test voice detection, you can uncomment
# the following 5 lines. Bobby will guess "yellow flashlight" and will prompt
# you to correct him by saying "blue flashlight"
# fake_answers = ["no", "yes", "yes", "yes", "no", "yes", "yes"]
# global count
# count... | [
"def ask_question(self, question):\n self.response((question))\n return input()",
"def ask_question(question):\n print('Question: {0}'.format(question))\n return prompt.string('Your answer: ')",
"def ask_and_evaluate(self):\n\n print self.question\n user_answer = raw_input(\"An... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns robot head to the specified yaw and/or pitch in radians at the given speed. Yaw can range from 119.5 deg (left) to 119.5 deg (right) and pitch can range from 38.5 deg (up) to 29.5 deg (down). | def turnHead(yaw = None, pitch = None, speed = 0.3):
if not yaw is None:
self.motion.setAngles("HeadYaw", yaw, speed)
if not pitch is None:
self.motion.setAngles("HeadPitch", pitch, speed) | [
"def turnHead(self, yaw = None, pitch = None, speed = 0.2):\n\n\t\tif not yaw is None:\n\t\t\tself.motion.setAngles(\"HeadYaw\", math.radians(yaw), speed)\n\t\tif not pitch is None:\n\t\t\tself.motion.setAngles(\"HeadPitch\", math.radians(pitch), speed)",
"def set_joystick_speed(self, speed):\n if self.tab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets face tracker to just head and starts. | def trackFace():
# start face tracker
self.track.setWholeBodyOn(False)
self.track.startTracker() | [
"def trackFace(self):\n\n\t\t# start face tracker\n\t\tself.track.setWholeBodyOn(False)\n\t\tself.track.startTracker()",
"def faceTrackingStarted(faceSize):\n\n\t# First, wake up\n\t#motionProxy.wakeUp()\n\t#motionProxy.rest()\n\n\t# Add target to track\n\ttargetName = \"Face\"\n\tfaceWidth = faceSize\n\ttracker.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subscribes to gaze analysis module so that robot starts writing gaze data to memory. Also sets the highest tolerance for determining if people are looking at the robot because those people's IDs are the only ones stored. | def subscribeGaze():
self.gaze.subscribe("_")
self.gaze.setTolerance(1) | [
"def gps_listener(self, data):\n #print(self.ready)\n #Check if this is our first GPS reading --\n # not robust but will work for now if we start test at the right spot\n if count == 0:\n #Re-defines the origins \n initial_lat = data.data[0]\n initial_lon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves people IDs from robot memory. If list of IDs was empty, return None. | def getPeopleIDs():
people_ids = self.mem.getData("GazeAnalysis/PeopleLookingAtRobot")
if len(people_ids) == 0:
return None
return people_ids | [
"def getPersonIds(withApp=False):\n with driver.session() as s:\n ids = s.write_transaction(getPersonId, withApp)\n\n pIds = []\n for idEl in ids:\n pIds.append(idEl[\"ID(p)\"])\n\n return pIds",
"def get_person_ids(self) -> np.ndarray:\n return self.person_ids",
"def getidlist(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns person's gaze as a list of yaw (left , right +) and pitch (up pi, down 0) in radians, respectively. Bases gaze on both eye and head angles. Does not compensate for variable robot head position. | def getRawPersonGaze(person_id):
try:
# retrieve GazeDirection and HeadAngles values
gaze_dir = self.mem.getData("PeoplePerception/Person/" + str(person_id) + "/GazeDirection")
head_angles = self.mem.getData("PeoplePerception/Person/" + str(person_id) + "/HeadAngles")
# extract gaze direction and head ... | [
"def getHeadAngles(self):\n\n\t\trobot_head_yaw, robot_head_pitch = self.motion.getAngles(\"Head\", False)\n\n\t\t# return adjusted robot head angles\n\t\treturn [robot_head_yaw, -robot_head_pitch]",
"def getAngles(self, *args):\n return _yarp.IGazeControl_getAngles(self, *args)",
"def angles(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns eye LEDs white. | def resetEyes(self):
self.leds.on("FaceLeds") | [
"def turn_on_white():\n OnRev(OUT_C, 50)\n Off(OUT_B)",
"def toggle_lights(exp_controller):\n exp_controller.write(b\"n\")",
"def lightsOFF():\n # TODO call a function that turns the lights off",
"def toggle_led(exp_controller):\n exp_controller.write(b\"l\")",
"def lightsON():\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Waits until either a sound is detected or until the given time limit expires. | def waitForSound(self, time_limit = 7):
self.sound.subscribe("sound_detection_client")
# give waiting a 7-second time limit
timeout = time.time() + 7
# check for new sounds every 0.2 seconds
while (self.mem.getData("SoundDetected")[0] != 1) and (time.time() < timeout):
time.sleep(0.2)
self.sound.unsu... | [
"def wait_until_played():\n\n sounddevice.wait()",
"def block_until_playing(self, media=None, timeout=None, **kwargs):\n # In case media isnt playing.\n self.play_media_event.clear()\n self.play_media(media, **kwargs)\n self.play_media_event.wait(timeout)\n self.play_media_ev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the analysis has results returned. | def has_result(self):
return len(self.__analysis_items) > 0 | [
"def _inspect_test_results(self, results):\n if len(results) == 0:\n if self.silence_warning_messages is False:\n print(\"Warning no test have been executed against the benchmark\")\n return True\n\n elif False in results:\n return False\n\n else:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Get a sublist of "analysis items" based on the given "type lists". | def get_analysis_items(self, analysis_types: List[EditingAnalysisItemType] = None,
element_types: List[SecondaryStructureElementType] = None) -> List[EditingAnalysisItem]:
# If not set, return all
if analysis_types is None and element_types is None:
return self.__... | [
"def bib_sublist(bibfile_data, val_type):\n sublist = [bibfile for bibfile in bibfile_data if isinstance(bibfile.bib, val_type)]\n return sublist",
"def get_item_list(metabook, filter_type=None):\r\n return metabook.walk(filter_type=filter_type)",
"def type_filter(self, items, types=None):\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the element can be used to analyze "contain" type. | def can_analyze_contain(cls, element):
if element is None:
return False
return element.ele_type == SecondaryStructureElementType.Stem \
or element.ele_type == SecondaryStructureElementType.Hairpin \
or element.ele_type == SecondaryStructureElementType.Interior... | [
"def can_contain(self):\n return False",
"def __contains__(self, element: Element):\n return element in self.get_elements()",
"def contains(self, element):",
"def contains(self, element) -> bool:\n\n return self.__find_node(element) is not None",
"def isElement(self):\n \n pas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the element can be used to analyze "before" type. | def can_analyze_before(cls, element):
if element is None:
return False
return element.ele_type == SecondaryStructureElementType.Stem \
or element.ele_type == SecondaryStructureElementType.Hairpin \
or element.ele_type == SecondaryStructureElementType.Multiloop... | [
"def can_handle_pre_instruction(self) -> bool:\n return False",
"def before(self):\n return self._before",
"def isElement(self):\n \n pass",
"def _is_input_element(se):\n return inspect.isclass(se) and issubclass(se, BaseField)",
"def is_before(self, other_entity) -> bool:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all geometric elements of a link, i.e. 'visual' and 'collision' objects. | def getGeometricElements(link):
visuals = []
collisions = []
if 'visual' in link:
visuals = [link['visual'][v] for v in link['visual']]
if 'collision' in link:
collisions = [link['collision'][v] for v in link['collision']]
return visuals, collisions | [
"def getAllLinkedNodes():\n return meta.findMetaNodes(className=LINK_METACLASS)",
"def _link_elements(self):\n raise NotImplementedError(\"Please implement this method\")",
"def get_linknets(self, session):\n ret = []\n linknets = session.query(Linknet).\\\n filter(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Derives a link from an object using its name, transformation and parenting. | def deriveLinkfromObject(obj, scale=1, parent_link=True, parent_objects=True,
reparent_children=True, nameformat='', scaleByBoundingBox=False):
log('Deriving link from ' + nUtils.getObjectName(obj), level="INFO")
# create armature/bone
bUtils.toggleLayer('link', True)
bpy.ops.ob... | [
"def _createLink( self, sourceObject, destinationObject, relation_type, relation_direction, extra=None ):\n if sourceObject and hasattr( sourceObject, 'failIfLocked' ):\n sourceObject.failIfLocked()\n\n id = 'link_' + str( int( random() * 1000000000) )\n while hasattr(self, id):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assigns the transformations recursively for a model parent link according to the model. This needs access to the object key of a link entry in the specified model. The transformations for each link object are extracted from the specified model and applied to the Blender object. | def setLinkTransformations(model, parent):
#todo: bpy.context.scene.layers = bUtils.defLayers(defs.layerTypes['link'])
for chi in parent['children']:
child = model['links'][chi]
# apply transform as saved in model
location = mathutils.Matrix.Translation(child['pose']['translation'])
... | [
"def apply_to_model(self, model):\n verts = model.verts\n norms = model.norms\n\n # transform all verts and norms\n newverts = []\n newnorms = []\n for i in range(len(verts)):\n group = verts[i].group\n sf = self.subframes[group]\n rot_matri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a layer from a CSV file | def addLayerFromCSV(layNumList):
rhinoLayerFilePath = "Q:\\Staff Postbox\\Tim Williams\\10 DESIGN LAYERS\\dev\\LAYERS\\RhinoLayersV3.csv"
#Read the CSV
file = open(rhinoLayerFilePath, "r")
contents = file.readlines()
file.close()
#Variables
RhinoLayerCol = 1
ColorCol = 3
Ma... | [
"def import_from_csv(self, file_name):\n with open(file_name) as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n next(reader, None)\n for row in reader:\n self.add_entry(row[0], row[1], row[2])",
"def add_file(self, csv_file: str):\n\n def han... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the projection matrix from the current viewing position. elev stores the elevation angle in the z plane azim stores the azimuth angle in the x,y plane dist is the distance of the eye viewing point from the object point. | def get_proj(self):
relev, razim = np.pi * self.elev/180, np.pi * self.azim/180
xmin, xmax = self.get_xlim3d()/self.pbaspect[0]
ymin, ymax = self.get_ylim3d()/self.pbaspect[1]
zmin, zmax = self.get_zlim3d()/self.pbaspect[2]
# transform to uniform world coordinates 0-1.0,0-1.0,0-1.0
worldM = ... | [
"def get_proj(self):\n relev, razim = np.pi * self.elev/180, np.pi * self.azim/180\n\n xmin, xmax = self.get_xlim3d()\n ymin, ymax = self.get_ylim3d()\n zmin, zmax = self.get_zlim3d()\n\n # transform to uniform world coordinates 0-1.0,0-1.0,0-1.0\n worldM = proj3d.world_tra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ask for the type of search and then lists books based of the criteria | def search_for_books(main_page): # Add information to the printout if the book is rented
type_of_search = 0
header = """
Do you want to search for books by the first letter of the title
or by the type?
"""
search_choices= (
("To search by letter", search_by_letter),
("T... | [
"def book_search(library: list) -> None:\n options = ['Author', 'Title', 'Publisher', 'Shelf', 'Category', 'Subject']\n prompt = '\\nWhat option would you like to search by?'\n choice = get_user_choice(options, prompt)\n if choice == '1':\n search_by_chosen_option(library, options[0])\n elif c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lists books that are starting with the entered letter | def search_by_letter(book_search):
print("What is the first letter of the searched title? Use uppercase")
letter = input("> ")
# books.csv = [title,author,year,ID,book_type]
with open('books.csv', 'r') as book_base:
book_list = csv.reader(book_base)
next(book_list)
pointer = 0
... | [
"def search_by_letter():\n print(\"What is the first letter of the searched title? Use uppercase\")\n letter = input(\"> \")\n\n # books.csv = [title,author,year,ID,book_type]\n with open('books.csv', 'r') as book_base:\n book_list = csv.reader(book_base)\n next(book_list)\n pointe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints books of the type | def book_printer(book_type):
# books.csv = [title,author,year,ID,book_type]
with open('books.csv', 'r') as book_base:
book_list = csv.reader(book_base)
next(book_list)
for book_data in book_list:
if book_data[-1] == book_type:
print(book_data)
... | [
"def print_catalog(self):\n for book in self.books.keys():\n print(book)",
"def display_book(self):\n print(\"List of books available is: \")\n for book in books_list :\n print(\"- \",book)",
"def display_book(self):\r\n print(\"Available Books are:\")\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks the books rented by the person in rented.csv base | def check_my_books(main_page):
login = main_page.login
# rented.csv = [ID, rental_date, return_date, login]
with open('rented.csv', 'r') as rented_base:
rented_reader = csv.reader(rented_base)
next(rented_reader)
books_table = []
for line in rented_reader:
if ... | [
"def check_my_books(login):\n\n # rented.csv = [ID, rental_date, return_date, login]\n with open('rented.csv', 'r') as rented_base:\n rented_reader = csv.reader(rented_base)\n next(rented_reader)\n\n books_table = []\n\n for line in rented_reader:\n if line[-1] == login:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
changes books data to 'rented' in rented.csv | def rent_book(main_page):
print("Which book do you wish to rent? Enter its code")
book_code = input('> ')
check_code_and_rent(main_page, book_code)
os.remove('rented.csv')
os.rename('rented_temp.csv','rented.csv') | [
"def change_books_status(login, book_code,rented_book_data):\n\n # modifying book_data:\n rental_date = datetime.date.today()\n return_date = rental_date + timedelta(days= 40)\n\n rental_date = date.strftime(rental_date,'%d.%m.%Y')\n return_date = date.strftime(return_date,'%d.%m.%Y')\n\n new_rent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if book is available and if yes, rents it | def check_if_available(main_page,rented_reader, book_code,
rented_book_data):
for line in rented_reader:
if line[0] == book_code:
if line[-2] == 'FALSE':
print('Books is unavailable')
return
else:
rented_book_da... | [
"def is_book_available(self, book):\n request_url = \"%s?q=%s\" % (self.API_URL, book)\n json_data = self.make_request(request_url)\n if json_data and len(json_data['docs']) >= 1:\n return True\n return False",
"def available_book(rentalList, idBook):\n for rent in re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets a table of rented book data | def rented_book_new_data(main_page, book_code):
login = main_page.login
# modifying book_data:
rental_date, return_date = date_setter()
new_rented_data = [book_code,
rental_date,
return_date,
'FALSE',
login
... | [
"def set_rtable(candset, table):\n # Return the rtable for a candidate set. This function is just a sugar\n\n return set_property(candset, 'rtable', table)",
"def set_table(self,new_table):\n self.table = new_table",
"def table(self, table):\n self._table = table",
"def set_data(self, inde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |