query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Read and process all pdf file situated in "./fichiers source/" then inject it in the document table | def pdfProcessing():
global DATABASE
conn = db.create_connection(DATABASE)
DOCUMENT_ORIGIN_CODE = "DOSSIER_PATIENT"
pathFolder = "fichiers source/"
extension = ".pdf"
pdfFileArrayPath = glob.glob(pathFolder + "*" + extension)
print(" - Processing pdf", end="")
for file in pdfFileArrayPa... | [
"def do_preprocess(pdf_files):\n\n for pdf_file in pdf_files:\n\n base, ext = os.path.splitext(pdf_file)\n \n create_intermediate_files()\n \n # 1) split a pdf file, a page a pdf\n num_pages = pdfutil.split(os.path.join(cwd, pdf_file), DIR_PAGE)\n\n for i in xrang... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read and process all docx file situated in "./fichiers source/" then inject it in the document table | def docxProcessing():
DOCUMENT_ORIGIN_CODE = "RADIOLOGIE_SOFTWARE"
global DATABASE
conn = db.create_connection(DATABASE)
pathFolder = "fichiers source/"
extension = ".docx"
docxFileArrayPath = glob.glob(pathFolder + "*" + extension)
print(" - Processing docx", end="")
for file in docxFi... | [
"def parse_docx_file(path, name):\n document = open_file(path)\n i = 0\n with open(name, 'w', encoding='utf-8') as file:\n fieldnames = ['word', 'meaning']\n writer = csv.DictWriter(file, fieldnames=fieldnames)\n writer.writeheader()\n for table in document.tables:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test filtering hits and miss datasets. | def test_filter_exists(self):
datasets = [{"exists": True, "name": "DATASET1"}, {"exists": False, "name": "DATASET2"}]
hits = filter_exists("HIT", datasets)
misses = filter_exists("MISS", datasets)
all = filter_exists("ALL", datasets)
nothing = filter_exists("NONE", datasets)
... | [
"def test_filters():\n\n csvpath =Path('../data/daily_rate_sheet.csv')\n bank_data = fileio.load_csv(csvpath)\n current_credit_score = 750\n debt = 1500\n income = 4000\n loan = 210000\n home_value = 250000\n\n monthly_debt_ratio = 0.375\n\n loan_to_value_ratio = 0.84\n\n filtered_data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test transform DB record. | def test_transform_record(self):
response = {"frequency": 0.009112876, "info": {"accessType": "PUBLIC"},
"referenceBases": "CT", "alternateBases": "AT",
"start": 10, "end": 12,
"variantCount": 3, "variantType": "MNP"}
record = Record("PUBLIC", ... | [
"def test_record(self):\n res = mldb.create_dataset({\n 'id' : 'ds_record',\n 'type' : 'mongodb.record',\n 'params' : {\n 'uriConnectionScheme' : self.connection_scheme,\n 'collection' : 'record'\n }\n })\n res.record_row... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test transform misses record. | def test_transform_misses(self):
response = {"referenceBases": '', "alternateBases": '', "variantType": "",
"frequency": 0, "callCount": 0, "sampleCount": 0, "variantCount": 0,
"start": 0, "end": 0, "info": {"accessType": "PUBLIC"}}
record = Record("PUBLIC")
... | [
"def check_transforms_match(self, transform: Mapping) -> None:\n xform_id = transform.get(TraceKeys.ID, \"\")\n if xform_id == id(self):\n return\n # TraceKeys.NONE to skip the id check\n if xform_id == TraceKeys.NONE:\n return\n xform_name = transform.get(Tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that add handover. | def test_add_handover(self):
# Test that the handover actually is added
handovers = [{"handover1": "info"}, {"handover2": "url"}]
record = {"datasetId": "test", "referenceName": "22", "referenceBases": "A",
"alternateBases": "C", "start": 10, "end": 11, "variantType": "SNP"}
... | [
"def testadd(self):\n\n self.Sack.add(\"foo\")\n assert self.Sack.remove() == \"foo\", \\\n 'Wrong item on top of the Sack! Expected \"foo\" here.'",
"def test_introduce_actions(self):\n pass",
"def test_add_extra(_, ):\n # --- Prep ---\n\n # --- Act ---\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test db call of getting public datasets access. | async def test_datasets_access_call_public(self):
pool = asynctest.CoroutineMock()
pool.acquire().__aenter__.return_value = Connection(accessData=[{'accesstype': 'PUBLIC', 'datasetid': 'mock:public:id'}])
result = await fetch_datasets_access(pool, None)
# for now it can return a tuple of... | [
"async def test_datasets_access_call_multiple(self):\n pool = asynctest.CoroutineMock()\n pool.acquire().__aenter__.return_value = Connection(accessData=[{'accesstype': 'CONTROLLED', 'datasetid': 'mock:controlled:id'},\n {'accessty... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test db call of getting registered datasets access. | async def test_datasets_access_call_registered(self):
pool = asynctest.CoroutineMock()
pool.acquire().__aenter__.return_value = Connection(accessData=[{'accesstype': 'REGISTERED', 'datasetid': 'mock:registered:id'}])
result = await fetch_datasets_access(pool, None)
# for now it can retur... | [
"def test_finding_datasets_doesnt_query_database_excessively(\n access_type, client, django_assert_num_queries\n):\n expected_num_queries = 13\n source_tags = [factories.SourceTagFactory() for _ in range(10)]\n topic_tags = [factories.TopicTagFactory() for _ in range(10)]\n\n masters = [\n fac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test db call of getting controlled datasets access. | async def test_datasets_access_call_controlled(self):
pool = asynctest.CoroutineMock()
pool.acquire().__aenter__.return_value = Connection(accessData=[{'accesstype': 'CONTROLLED', 'datasetid': 'mock:controlled:id'}])
result = await fetch_datasets_access(pool, None)
# for now it can retur... | [
"async def test_datasets_access_call_multiple(self):\n pool = asynctest.CoroutineMock()\n pool.acquire().__aenter__.return_value = Connection(accessData=[{'accesstype': 'CONTROLLED', 'datasetid': 'mock:controlled:id'},\n {'accessty... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test db call of getting controlled and public datasets access. | async def test_datasets_access_call_multiple(self):
pool = asynctest.CoroutineMock()
pool.acquire().__aenter__.return_value = Connection(accessData=[{'accesstype': 'CONTROLLED', 'datasetid': 'mock:controlled:id'},
{'accesstype': 'PU... | [
"async def test_datasets_access_call_public(self):\n pool = asynctest.CoroutineMock()\n pool.acquire().__aenter__.return_value = Connection(accessData=[{'accesstype': 'PUBLIC', 'datasetid': 'mock:public:id'}])\n result = await fetch_datasets_access(pool, None)\n # for now it can return a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test db call of getting datasets metadata. | async def test_fetch_dataset_metadata_call(self):
pool = asynctest.CoroutineMock()
pool.acquire().__aenter__.return_value = Connection()
result = await fetch_dataset_metadata(pool, None, None)
# for now it can return empty dataset
# in order to get a response we will have to mock... | [
"def test_dataset_get(self):\n response = self.client.get('/dataset')\n self.assert200(response)\n self.assertEquals(\n dict(name=dataset_name, tableNames=table_names), response.json)",
"def test_get_metadata(self):\n pass",
"def test_retrieve_db_metadata(self):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test PostgreSQL wildcard handling. | def test_handle_wildcard(self):
sequence1 = 'ATCG'
sequence2 = 'ATNG'
sequence3 = 'NNCN'
self.assertEqual(handle_wildcard(sequence1), ['ATCG'])
self.assertEqual(handle_wildcard(sequence2), ["%AT_G%"])
self.assertEqual(handle_wildcard(sequence3), ["%__C_%"]) | [
"def test_match_any_wildcard_in_literal(self):\n qs = '\"Foo t*\"'\n qs_escaped, wildcard = wildcard_escape(qs)\n\n self.assertEqual(\n qs_escaped, r'\"Foo t\\*\"', \"Wildcard should be escaped\"\n )\n self.assertFalse(wildcard, \"Wildcard should not be detected\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Built the error Message from a key with specific params | def built_error_message(self, key: str, params: List[str]) -> str:
if key in self.errors:
error_msg = self.errors[key]
error_msg = re.sub("{..}", "", error_msg)
return error_msg.format(*params)
else:
return "" | [
"def make_error(self, key: str, **kwargs) -> ValidationError:\n try:\n msg = self.error_messages[key]\n except KeyError as error:\n class_name = self.__class__.__name__\n message = (\n \"ValidationError raised by `{class_name}`, but error key `{key}` doe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a dataframe and adds the 3top tags associated with the LDA model prediction over a corpus of interest. | def add_tags(df,lda,corpus,pmin):
vector =[]
for doc in corpus:
prediccion = lda[doc]
prediccion.sort(reverse= True,key=lambda x: x[1])
prediccion = (filtro_probs(prediccion,pmin))
vector.append(prediccion)
M1_glob = [item[0] for item in vector]
M1_final = [item[0] ... | [
"def get_top_keywords_from_articles(self, kwords_list):\n _all_keywords = []\n for a in kwords_list:\n if a != []:\n for w in a:\n _all_keywords.append([w['keyword'],w['weight'],w['label']])\n _df_g = pd.DataFrame(_all_keywords, columns=[\"Keyword\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an itirator over all ngrams for n in range(ngramRange) given a list of tokens. | def range_ngrams(tokens, ngramRange=(1,2)):
return chain(*(n_grams(tokens, i) for i in range(*ngramRange))) | [
"def ngram(n, iter_tokens):\n z = len(iter_tokens)\n return (iter_tokens[i:i+n] for i in range(z-n+1))",
"def __call__(self, ngram_range=(1, 1)):\n min_n, max_n = ngram_range\n ngrams = self.__class__({ngram: val for ngram, val in\n self._ngrams.iteritems()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear the summary dictionary. | def clear_summary(self):
self._summary.clear() | [
"def clear_summaries(self):\n\n\t\tself.summaries = [0, 0]",
"def clear_summaries(self):\n\n\t\tself.summaries = [0, 0, 0]",
"def clearSummary(self):\n self.summary(DiagnosticStatus.OK, '')",
"def reset_statistics(self):\n self._statistics = {}",
"def clear_summaries(self):\n if tf.gfil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regrid ORAS4 to MOM. | def test_oras4_to_mom(self, input_dir, output_dir):
output = os.path.join(output_dir, 'mom_oras4_temp.nc')
if os.path.exists(output):
os.remove(output)
src_name = 'ORAS4'
src_data_file = os.path.join(input_dir, 'thetao_oras4_1m_2014_grid_T.nc')
dest_name = 'MOM'
... | [
"def test_oras4_to_mom1(self, input_dir, output_dir):\n\n output = os.path.join(output_dir, 'mom1_oras4_temp.nc')\n if os.path.exists(output):\n os.remove(output)\n\n src_name = 'ORAS4'\n src_data_file = os.path.join(input_dir, 'so_oras4_1m_2014_grid_T.nc')\n dest_name ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regrid ORAS4 to MOM 1 degree. | def test_oras4_to_mom1(self, input_dir, output_dir):
output = os.path.join(output_dir, 'mom1_oras4_temp.nc')
if os.path.exists(output):
os.remove(output)
src_name = 'ORAS4'
src_data_file = os.path.join(input_dir, 'so_oras4_1m_2014_grid_T.nc')
dest_name = 'MOM1'
... | [
"def test_oras4_to_mom(self, input_dir, output_dir):\n\n output = os.path.join(output_dir, 'mom_oras4_temp.nc')\n if os.path.exists(output):\n os.remove(output)\n\n src_name = 'ORAS4'\n src_data_file = os.path.join(input_dir, 'thetao_oras4_1m_2014_grid_T.nc')\n dest_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update amqp client relation hooks IFF leader node is ready. Client nodes are considered ready once the leader has already run amqp_changed. | def update_clients():
if rabbit.leader_node_is_ready() or rabbit.client_node_is_ready():
for rid in relation_ids('amqp'):
for unit in related_units(rid):
amqp_changed(relation_id=rid, remote_unit=unit) | [
"def client_relation_changed():\n if ceph.is_quorum():\n settings = relation_get()\n if 'broker_req' in settings:\n if not ceph.is_leader():\n log(\"Not leader - ignoring broker request\", level=DEBUG)\n else:\n rsp = process_requests(settings['br... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Affiche les nombres impairs entre `n` et `m` inclus. >>> affiche_impairs(42, 51) 43 45 47 49 51 | def affiche_impairs(n: int, m: int) -> None:
# Trois versions proposées
## Version itérative classique
i = n
if i % 2 == 0:
i += 1
while i <= m:
print(i, end=" ")
i += 2
print()
## Version fonctionnelle ; 1 ligne
#print(" ".join(map(str, range(n - n%2 + 1, m + 1... | [
"def nombres_impairs(début : int , fin : int) -> list:\n if début > fin:\n return \n if début % 2 == 1:\n print(début,end=\" \")\n return nombres_impairs(début+1,fin)\n else:\n return nombres_impairs(début+1,fin)",
"def findPrimeImplicants(self):\n newimp = self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots an individual chip in a subaxis | def plot_chip(self, aid, nRows, nCols, px, fulldraw=True, **kwargs):
ibs = self.ibs
if aid in [self.aid1, self.aid2]:
# Bold color for the matching chips
lw = 5
text_color = np.array((135, 206, 235, 255)) / 255.0
else:
lw = 2
text_color... | [
"def plot(self, plot_core=True, interactive=True, subplot_height=700, subplot_width=200):\n init_notebook_mode(connected=True)\n\n # Approximate size of the left margin of a plot, that will be added to the calculated\n # figsize in order to prevent figure shrinkage in case of small number of su... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
All the annotations are given nid | def merge_all_into_nid(self, nid, event=None):
aid_list = self.all_aid_list
self.ibs.set_annot_name_rowids(aid_list, [nid] * len(aid_list))
self.update_callback()
self.backend_callback()
self.show_page() | [
"def get_annotations(self, entity):\n if isinstance(entity, str):\n entity = self.get_by_label(entity)\n d = {'comment': getattr(entity, 'comment', '')}\n for a in self.annotation_properties():\n d[a.label.first()] = [\n o.strip('\"') for s, p, o in\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
All nonjunk annotations are given the SAME new name | def merge_nonjunk_into_new_name(self, event=None):
# Delete all original names
aid_list = self.all_aid_list
aid_list_filtered = ut.filterfalse_items(
aid_list, self.ibs.get_annot_isjunk(aid_list)
)
# Rename annotations
self.ibs.set_annot_names_to_same_new_name... | [
"def test_case_annotations_update(self):\n pass",
"def ensure_merged_annotations(self):\n pass",
"def Annotate(self, annotations):\n self._annotations.update(annotations)",
"def rename_annotations(args):\n\n project = ChildProject(args.source)\n\n perform_validation(project, require_suc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the ip address of the host default exterior access port/adapter. | def get_default_ip_address():
gws = netifaces.gateways() # get all gateways
default = gws['default'] # get the default gw
adapter = default[2][1] # get the adapter identifier
realadapter = netifaces.ifaddresses(adapter) # get the adapter
addr_dict = realadapter[2][0] # get the first ipv4 a... | [
"def getLocalhostIP():\n return socket.getaddrinfo('localhost', 0)[0][4][0]",
"def get_local_host_ip(self) -> str:",
"def local_address():\r\n \r\n adapter = None \r\n ifconfig = getoutput(\"/sbin/ifconfig\")\r\n if state.listener:\r\n ifconfig = ifconfig.split(\"\\n\")\r\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accesses the training checkpoint. | def checkpoint(self):
return self._checkpoint | [
"def checkpoint():",
"def load_checkpoint(self):\r\n if self.ckpt:\r\n self.step = int(self.ckpt.split('-')[1])\r\n print('Restoring from epoch:{}'.format(self.step))\r\n self.logger.info(\"Restoring from {}\".format(self.ckpt))\r\n self.saver.restore(self.sessio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Access training loss metric objects for all tasks. | def training_losses(self):
if self._training_losses is None:
# Builds the per-task metrics and losses.
# This the total summed training loss of tasks in the joint training.
self._training_losses = dict(
total_loss=tf.keras.metrics.Mean("training_loss", dtype=tf.float32))
for ... | [
"def training_metrics(self):\r\n if self._training_metrics is None:\r\n # Builds the per-task metrics and losses.\r\n self._training_metrics = {}\r\n for name, task in self.multi_task.tasks.items():\r\n self._training_metrics[name] = task.build_metrics(training=True)\r\n return self._tra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Access training metric metric objects for all tasks. | def training_metrics(self):
if self._training_metrics is None:
# Builds the per-task metrics and losses.
self._training_metrics = {}
for name, task in self.multi_task.tasks.items():
self._training_metrics[name] = task.build_metrics(training=True)
return self._training_metrics | [
"def get_training_metrics():\n return _GLOBAL_TRAINING_METRICS",
"def get_metrics(task='classification'):\n\n if task == 'classification':\n metrics = {\n # (name, metric)\n 'categorical_cross_entropy':\n tf.keras.metrics.CategoricalCrossentropy(),\n 'top_1_accuracy':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unpickle and execute task. | def work(pickled_task):
task = pickle.loads(pickled_task)
return task.execute() | [
"def run_task(self) -> Task:",
"def task_runner(obj, *args, **kwargs):\n obj = workers.TurbiniaTask.deserialize(obj)\n return obj.run_wrapper(*args, **kwargs)",
"def execute_task(self):\n raise NotImplementedError(\"Execute Task method not implemented\")",
"def execute_task(self, task):\n t = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pickle tasks and distribute work over parallel processes. | def execute(self, tasks: List[Task], progress_bar: bool = True):
n_tasks = len(tasks)
pickled_tasks = [pickle.dumps(task) for task in tasks]
n_procs = min(self.n_procs, n_tasks)
logger.info(f"Performing parallel task execution on {n_procs} "
f"processes.")
... | [
"def execute(self, tasks: List[Task], progress_bar: bool = True):\n pickled_tasks = [pickle.dumps(task) for task in tasks]\n\n n_procs = MPI.COMM_WORLD.Get_size() # Size of communicator\n logger.info(f\"Performing parallel task execution on {n_procs-1} \"\n f\"workers with ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets up this window with a simulator, a display and optionally a control widget. | def __init__(self, simulator, display, control=None, **kwargs):
super(ZasimMainWindow, self).__init__(**kwargs)
self.setAttribute(Qt.WA_DeleteOnClose)
self.simulator = simulator
self.display = display
self.control = control
central_widget = QWidget(self)
if se... | [
"def __set_up_display(self) -> None:\n root = tk.Tk()\n self.display = display.Display(root, self, self.board)\n self.display.pack(side=\"top\", fill=\"both\", expand=\"true\", padx=4, \n pady=4)\n root.mainloop()",
"def _display_setup(self):\r\n display... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach an extra display to the control. Those displays are updated whenever a step occurs. | def attach_display(self, display):
self.extra_displays.append(display)
self.addDockWidget(Qt.RightDockWidgetArea, display)
#self.display_attached.emit(display) | [
"def add_display(self, display):\n self.logger.debug(\"running\")\n self.__list_of_displays.append(display)\n self.__refresh()\n self.logger.debug(\"done\")",
"def start_displayhook(self):\n pass",
"def bs_addHeadsUpDisplay():\n # remove all headsUpDisplay.\n if pm.windo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detach an extra attached display from the control. | def detach_display(self, display):
self.extra_displays.remove(display)
self.removeDockWidget(display)
#self.display_detached.emit(display) | [
"def _detach_hidden_field(self) -> None:\r\n for i in range(3):\r\n self.field.pop(0)\r\n self.hiddenFieldAttached = False",
"def remove_display(self, display):\n self.logger.debug(\"running\")\n if display in self.__list_of_displays:\n self.__list_of_displays.rem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs the given functions using the code in the given directory. Returns True if all went well, together with a string for the user | def run_functions( functions, dir ):
res = []
for i in range(0, len(functions)):
res.append(functions[i].execute(dir))
return summarize_as_html(res) | [
"def check_programs_in_directory(directory):\n files = [f for f in os.listdir(directory) if f.endswith(DECAF_SUFFIX)]\n files.sort()\n files = [os.path.join(directory, f) for f in files]\n\n all_passed = True\n for f in files:\n if not check_return_value(f):\n all_passed = False\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to generate dataset_name for tests. Will either use the name defined in the test configuration ("dataset_name"), or generate one using the Expectation name and index. In cases where the dataset is a list, then an additional index will be used. | def generate_dataset_name_from_expectation_name(
dataset: dict, expectation_type: str, index: int, sub_index: int | None = None
) -> str:
dataset_name: str
if not sub_index:
dataset_name = dataset.get(
"dataset_name", f"{expectation_type}_dataset_{index}"
)
else:
dat... | [
"def construct_dataset_name(self, *args) -> str:\n raise NotImplementedError",
"def dataset_name(self):\n ...",
"def construct_dataset_name(self, *args):\n raise NotImplementedError",
"def dataset_name(self) -> str:\n return self._data.get(\"datasetName\")",
"def dataset_name(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that dataset_name (ie. table name) is valid before adding data to table. | def _check_if_valid_dataset_name(dataset_name: str) -> str:
if not re.match(r"^[A-Za-z0-9_]+$", dataset_name):
raise ExecutionEngineError(
f"dataset_name: {dataset_name} is not valid, because it contains non-alphanumeric and _ characters."
f"Please check your configuration."
... | [
"def _validate_dataset_name(self, dataset_name: Optional[str]) -> str:\n if dataset_name is None:\n if self.num_datasets > 1:\n raise ValueError(\"`dataset_name` is required if there are \"\n \"more than one datasets.\")\n dataset_name = ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copied get_redshift_connection_url func from tests/test_utils.py | def _get_redshift_connection_string() -> str:
host = os.environ.get("REDSHIFT_HOST") # noqa: TID251
port = os.environ.get("REDSHIFT_PORT") # noqa: TID251
user = os.environ.get("REDSHIFT_USERNAME") # noqa: TID251
pswd = os.environ.get("REDSHIFT_PASSWORD") # noqa: TID251
db = os.environ.get("REDSH... | [
"def get_redshift_connection_url() -> str:\n host = os.environ.get(\"REDSHIFT_HOST\")\n port = os.environ.get(\"REDSHIFT_PORT\")\n user = os.environ.get(\"REDSHIFT_USERNAME\")\n pswd = os.environ.get(\"REDSHIFT_PASSWORD\")\n db = os.environ.get(\"REDSHIFT_DATABASE\")\n ssl = os.environ.get(\"REDSH... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copied get_awsathena_connection_url and get_awsathena_db_name funcs from tests/test_utils.py | def _get_athena_connection_string(db_name_env_var: str = "ATHENA_DB_NAME") -> str:
ATHENA_DB_NAME: Optional[str] = os.getenv(db_name_env_var)
ATHENA_STAGING_S3: Optional[str] = os.getenv("ATHENA_STAGING_S3")
if not ATHENA_DB_NAME:
raise ValueError(
f"Environment Variable {db_name_env_va... | [
"def test_retrieve_db_url(self):\n self.assertEqual(\n self.db.database_url,\n '/'.join((self.client.server_url, self.test_dbname))\n )",
"def get_awsathena_connection_url(db_name_env_var: str = \"ATHENA_DB_NAME\") -> str:\n ATHENA_DB_NAME: str = get_awsathena_db_name(db_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copied get_snowflake_connection_url func from tests/test_utils.py | def _get_snowflake_connection_string() -> str:
sfUser = os.environ.get("SNOWFLAKE_USER") # noqa: TID251
sfPswd = os.environ.get("SNOWFLAKE_PW") # noqa: TID251
sfAccount = os.environ.get("SNOWFLAKE_ACCOUNT") # noqa: TID251
sfDatabase = os.environ.get("SNOWFLAKE_DATABASE") # noqa: TID251
sfSchema ... | [
"def get_snowflake_connection_url() -> str:\n sfUser = os.environ.get(\"SNOWFLAKE_USER\")\n sfPswd = os.environ.get(\"SNOWFLAKE_PW\")\n sfAccount = os.environ.get(\"SNOWFLAKE_ACCOUNT\")\n sfDatabase = os.environ.get(\"SNOWFLAKE_DATABASE\")\n sfSchema = os.environ.get(\"SNOWFLAKE_SCHEMA\")\n sfWare... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a temporary directory and absolute path to an ephemeral sqlite_db within that temp directory. Used to support testing of multitable expectations without creating temp directories at import. | def generate_sqlite_db_path():
tmp_dir = str(tempfile.mkdtemp())
abspath = os.path.abspath( # noqa: PTH100
os.path.join( # noqa: PTH118
tmp_dir,
"sqlite_db"
+ "".join(
[random.choice(string.ascii_letters + string.digits) for _ in range(8)]
... | [
"def db_dir(tmp_path_factory):\n return tmp_path_factory.mktemp(\"tmp_db_dir\")",
"def tempdir():\n\n # Create a directory and return the path\n return tempfile.mkdtemp()",
"def mock_db(tmpdir_factory):\n filename = str(tmpdir_factory.mktemp(\"data\").join(\"test.db\"))\n create_test_db(filename)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple check to ensure the transations is greater than zero. | def validate(self):
if self.amount > 0:
return True
return False | [
"def _check_cost(self, cr, uid, ids, context=None):\n for enrich in self.browse(cr, uid, ids, context=context):\n if enrich.amount <= 0:\n raise osv.except_osv(_('ValidateError'), _('The Cost Must Be Greater Than Zero!'))\n return True",
"def validate_gt_zero(self, data: Se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function read cpi rate csv then returns dataframe | def get_cpi_rates():
df = pd.read_csv('cpi_usa.csv', index_col=0)
df.index = pd.to_datetime(df.index)
df = df.resample('BAS').mean() # change sampling to business year start
df.index = df.index.year # datetime to year
df.columns = ['cpi_rate']
return df | [
"def GetRateData(directory):\n\n rt_data = pd.read_csv(directory)\n return rt_data",
"def _load_csv(self, csv_url: str) -> pd.DataFrame:\n # Reading CSV File containing 1 min candlestick data\n data = pd.read_csv(csv_url, index_col='Timestamp')\n # Converting Timestamp numbers into a ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function D=l2distance(X,Z) Computes the Euclidean distance matrix. | def l2distance(X, Z=None):
if Z is None:
n, d = X.shape
s1 = np.sum(np.power(X, 2), axis=1).reshape(-1,1)
D1 = -2 * np.dot(X, X.T) + repmat(s1, 1, n)
D = D1 + repmat(s1.T, n, 1)
np.fill_diagonal(D, 0)
D = np.sqrt(np.maximum(D, 0))
else:
n, d = X.shape
... | [
"def compute_l2_distance_matrix(features_queries, features_dataset):\n sx = np.sum(features_queries ** 2, axis=1, keepdims=True)\n sy = np.sum(features_dataset ** 2, axis=1, keepdims=True)\n\n return np.sqrt(-2 * features_queries.dot(features_dataset.T) + sx + sy.T)",
"def distance(x, y):\r\n return m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator that returns nothing | def emptyGenerator():
return
yield | [
"def __emptygen(self):\n if False:\n yield",
"def __emptygen():\n if False:\n yield",
"def noneGenerator():\n while True:\n yield None",
"def nothing():\n while True:\n yield",
"def null():\n\n while True:\n yield None",
"def test_passes_on... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET method Get an instant task information. | def get(self, request):
feedback = {
'permission': True
}
try:
task_id = request.GET.get('task_id', None)
if task_id is None:
feedback['data'] = ErrorCode.parameter_missing('task_id')
raise natrix_exception.ParameterMissingExcep... | [
"def getTask():\n\tcontent = requests.get(MANAGER_URL+\"task\", params={\"apiKey\": API_KEY}).text\n\tif content == \"null\":\n\t\treturn None\n\telse:\n\t\treturn json.loads(content)",
"def getTask():\n content = requests.get(MANAGER_URL+\"task\", params={\"apiKey\": API_KEY}).text\n\n print(\"Task call %s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ingest from a particular sequence | def sequence_ingest(self,sequence):
data=self.data
counter=0
for item in data[sequence]:
datestring=item['specimenDate']
date=fetchdate(datestring)
row,created=DailyCases.objects.get_or_create(specimenDate=date,areacode=item['areaCode'])
row.areaname=item['areaName']
row.dailyLabConfirmedCases=... | [
"def final_ingest(self, block):\n if len(block) == 10:\n self.ingest(block)\n self.ingest('\\x80' + '\\x00'*8 + '\\x01')\n elif len(block) == 9:\n self.ingest(block + '\\x81')\n else:\n self.ingest(block + '\\x80' + '\\x00'*(8-len(block)) + '\\x01')",
"def sequence_ingest(self,areacod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ingest from a particular areacode | def sequence_ingest(self,areacode):
data=self.data[self.data['Area code']==areacode]
areaname=data['Area name'].unique().item()
log.debug(f'Ingesting cases from {areacode}: {areaname}')
counter=0
for day in data['Specimen date']:
date=fetchdate(day)
row,created=DailyCases.objects.get_or_create(specim... | [
"def define_areas(\n pixel_filtered_map: np.ndarray, district_heating_zone_threshold: float\n):\n structure = np.ones((3, 3)).astype(int)\n expanded_map = binary_dilation(input=pixel_filtered_map, structure=structure)\n eroded_map = binary_erosion(input=expanded_map, structure=structure)\n labels_arr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add up total cases for a nation for integrity checks | def sum_cases(nation='England'):
_sum=0
for _code in ons_week.stored_names:
if ons_week.nation[_code]==nation:
place=ons_week.stored_names[_code]
_total=DailyCases.objects.filter(areaname=place).aggregate(Max('totalLabConfirmedCases')).get('totalLabConfirmedCases__max')
... | [
"def get_total_cases(self):\n world_data = self.get_world_data()\n count = world_data['total_cases']\n self.covid_bot.speak(\"The total number of cases in the world are %s\" % count)",
"def get_total_active_cases(self):\n world_data = self.get_world_data()\n count = world_data['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function registers the parameters of the model to Pypet. Parameters can be nested dictionaries. They are unpacked and stored recursively. | def _addParametersToPypet(self, traj, params):
def addParametersRecursively(traj, params, current_level):
# make dummy list if just string
if isinstance(current_level, str):
current_level = [current_level]
# iterate dict
for key, value in params.i... | [
"def install_parameters(self, params):\n for name, param in params.items():\n param.name = name\n self._install_parameter(param)\n\n # Install param as a property, so that it can be accessed via\n # object-dot notation.\n setattr(self.__class__, name, pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If not evaluation function is given, we assume that a model will be simulated. This function will be called by pypet directly and therefore wants a pypet trajectory as an argument | def _runModel(self, traj):
if self.useRandomICs:
logging.warn("Random initial conditions not implemented yet")
# get parameters of this run from pypet trajectory
runParams = self.getParametersFromTraj(traj)
if self.parameterSpace.star:
runParams = flatten_nested_d... | [
"def evaluate(self, trained_model, model_input, *args, **kwargs):\r\n pass",
"def evaluate_model(self, t, scaling_parameters, system_parameters):\n raise NotImplementedError",
"def make_predict_step(self):\n return self.make_eval_step()",
"def eval_model(t,lat,lon,head,pitch,tide=0,temp=None,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to handle None's in pypet parameters (used for random number generator seed) | def _validatePypetParameters(self, runParams):
# fix rng seed, which is saved as a string if None
if "seed" in runParams:
if runParams["seed"] == "None":
runParams["seed"] = None
return runParams | [
"def test_rng_null(self):\n assert check_random_state(None) is np.random.mtrand._rand",
"def check_not_none(param):\n misc.check_not_none(param)",
"def test_get_with_None_value(self):\n self.assertEqual(self.config.get('none_types','some_value'),None)\n self.assertEqual(self.config.get('... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Aggregate all results in to dfResults dataframe. | def aggregateResultsToDfResults(self, arrays=True, fillna=False):
nan_value = np.nan
# defines which variable types will be saved in the results dataframe
SUPPORTED_TYPES = (float, int, np.ndarray, list)
SCALAR_TYPES = (float, int)
ARRAY_TYPES = (np.ndarray, list)
loggin... | [
"def aggregate_results(self):\n\n raise NotImplementedError",
"def aggregate_data():\n # pylint: disable=redefined-variable-type\n # pandas behaviour - variation of the same object\n data_frame = pandas.DataFrame(columns=['model_name',\n 'algorithm',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return `xr.Dataset` from the exploration results. | def xr(self, bold=False):
def _sanitize_nc_key(k):
return k.replace("*", "_").replace(".", "_").replace("|", "_")
assert self.results is not None, "Run `loadResults()` first to populate the results"
assert len(self.results) == len(self.dfResults)
# create intrisinsic dims f... | [
"def get_results(self):\n self.store.consolidate()\n\n # TODO: replace index variables data with simulation data\n # (could be advanced Index objects that don't support serialization)\n\n ds_out = (\n self.store.open_as_xr_dataset()\n # rebuild multi-indexes\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new SRPAuthenticationPolicy from a settings dict. | def from_settings(cls, settings={}, prefix="srpauth.", **kwds):
# Grab out all the settings keys that start with our prefix.
auth_settings = {}
for name, value in settings.iteritems():
if not name.startswith(prefix):
continue
auth_settings[name[len(prefix)... | [
"def create_policy(**kwargs):\n parameters = kwargs.keys()\n try:\n PolicyClass = POLICY_KWARGS_MAPPING.get(frozenset(parameters))\n return PolicyClass(**kwargs)\n except KeyError:\n raise AmbiguousSettingsError(\"Can not initialize any policy class with parameters %s\" % kwargs)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the unauthenticated userid for this request. When using HTTPSRPHMACAuth, this involves looking in the HTTP Authorization header to find the reported username. | def unauthenticated_userid(self, request):
params = self._get_auth_params(request)
if params is None:
return None
return params.get("username") | [
"def unauthenticated_userid(self, request):\n return None",
"def unauthenticated_userid(self, request):\n\n # Prepare the return value.\n canonical_id = None\n\n # If there's a bearer token in the request, use it to lookup the\n # corresponding canonical id.\n access_toke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the list of effective principals for this request. | def effective_principals(self, request):
principals = [Everyone]
params = self._get_auth_params(request)
if params is None:
return principals
if not self._authenticate(request, params):
return principals
username = params["username"]
if self.groupf... | [
"def effective_principals(self, request):\n debug = self.debug\n effective_principals = [Everyone]\n userid = self.authenticated_userid(request)\n\n if userid is None:\n debug and self._log(\n 'authenticated_userid returned %r; returning %r' % (\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View that challenges for credentials with a "401 Unauthorized". This method can be used as a pyramid "forbidden view" in order to challenge for auth credentials when necessary. | def challenge_view(self, request):
headerlist = [("Content-Type", "text/plain")]
headerlist.extend(self._get_challenge_headers(request))
return Response("Unauthorized", status="401 Unauthorized",
headerlist=headerlist) | [
"def error_handler_unauthorized(request, response, exception):\n response.set_status(401)\n response.out.write(template.render(\n 'ndb_users/templates/401-unauthorized.html',\n template_values(query_options={\n 'continue': request.path\n })\n ))",
"def permission_denied(error):\n return re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get headers necessary for a fresh srphmacauth challenge. This method generates a new srphmacauth challenge for the given request, including a fresh nonce. If the environment is marked as having a stale nonce then this is indicated in the challenge. | def _get_challenge_headers(self, request, check_stale=True):
params = {}
params["realm"] = self.realm
if self.domain is not None:
params["domain"] = self.domain
# Escape any special characters in those values, so we can send
# them as quoted-strings. The extra values... | [
"def get_request_headers(self):\n\n date_header = time.asctime(time.gmtime())\n # We sign the time string above with the user's AWS secret access key\n # in order to authenticate our request.\n signing_key = self._hmac_sign_string(date_header)\n\n # Amazon's super fun auth token.\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract srphmacauth parameters from the request. This method extracts srphmacauth parameters from the Authorization header and returns them as a dict. If they are missing then None is returned. | def _get_unvalidated_auth_params(self, request):
try:
params = parse_authz_header(request)
except ValueError:
params = None
if params is None:
return None
if params["scheme"].lower() != "srp-hmac":
return None
return params | [
"def _get_auth_params(self, request):\n params = self._get_unvalidated_auth_params(request)\n if params is None:\n return None\n # Check that they're valid srp-hmac-auth parameters.\n if not validate_parameters(params, self.realm):\n return None\n # Check tha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract srphmacauth parameters from the request. This method extracts srphmacauth parameters from the Authorization header and returns them as a dict. If they are missing then None is returned. | def _get_auth_params(self, request):
params = self._get_unvalidated_auth_params(request)
if params is None:
return None
# Check that they're valid srp-hmac-auth parameters.
if not validate_parameters(params, self.realm):
return None
# Check that the digest... | [
"def _get_unvalidated_auth_params(self, request):\n try:\n params = parse_authz_header(request)\n except ValueError:\n params = None\n if params is None:\n return None\n if params[\"scheme\"].lower() != \"srp-hmac\":\n return None\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain the password verifier data to use for the given user. This method returns a tuple (algorithm, salt, verifier) giving the necessary information to verify the user's password. If no information is available for the user then a tuple of Nones is returned. | def _get_verifier(self, username):
# If we have a get_verifier callback, use it directly.
if self.get_verifier is not None:
verifier = self.get_verifier(username)
if verifier is not None and verifier[0] is not None:
return verifier
# Otherwise, we need t... | [
"def get_verified_password(self):\n return self.controller.dbfilter.db.get('passwd/user-password-again')",
"def generate_salt_and_verifier(identity: str, password: str) -> Tuple[bytes, int]:\n\n salt = _generate_random_bytes(32)\n generator = _get_srp_generator()\n prime = _get_srp_prime()\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the serverside private key for a given nonce. | def _get_privkey(self, nonce):
privkey = self.nonce_manager.get_prandom_bytes(nonce, 32)
return int_from_bytes(privkey) | [
"def nonce_key(self, nonce):\n return sha256(str(self.entity['ID'].value) + nonce).hexdigest()",
"def get_server_priv_key(self):\n with open(\"server_priv.PEM\", 'r') as key_file:\n return key_file.read()",
"def generate_key_data_from_nonce(server_nonce, new_nonce):\n server_nonce = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Include default srpauth settings into a pyramid config. This function provides a hook for pyramid to include the default settings | def includeme(config):
# Grab the pyramid-wide settings, to look for any auth config.
settings = config.get_settings().copy()
# Use the settings to construct an AuthenticationPolicy.
authn_policy = SRPAuthenticationPolicy.from_settings(settings)
config.set_authentication_policy(authn_policy)
# H... | [
"def config(settings):\n\n T = current.T\n\n # -------------------------------------------------------------------------\n # System Name\n #\n settings.base.system_name = T(\"Resource Management System\")\n settings.base.system_name_short = T(\"RMS\")\n\n # -------------------------------------... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dictionarylike object representing the filesystem structure starting at the given root directory. | def get_fs_dict (
initial_root, create_item=None, dict_cls=dict,
dirname_filter=None, filename_filter=None,
include_root=False, toplevel_files=True, prune_empty=False, file_key=None,
):
# TODO(could-do): max_depth=N
fsdict = dict_cls()
get_file_key = ( lambda x: x ) if file_key is None else file... | [
"def directory_tree(base_path):\n path_ndict_data = []\n\n path_stub_len = len(split_path(base_path))\n for dirpath, dirnames, filenames in list(os.walk(base_path)):\n dir_stub_tup = tuple(split_path(dirpath)[path_stub_len:])\n for filename in filenames:\n path_ndict_data.append(\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator that iterates over the content of a filesystem tree starting at source and compares it to the filesystem tree starting at dest (which doesn't have to exist). The subdir_root can be used to control whether source should be a subdir of dest or not (which means that walk_copy_tree (source, dest, subdir_root=True... | def walk_copy_tree ( source, dest, subdir_root=False, **walk_kwargs ):
source_path = os.path.abspath ( source )
dest_path = os.path.abspath ( dest )
get_entry = lambda path: (
path, os.lstat ( path ) if os.path.lexists ( path ) else None
)
get_stat_list = lambda s, d, names: (
[ ( get_entr... | [
"def assertFileTree(self, source, tree):\n dirs_tree = [e for e in tree if not isinstance(e, str)]\n\n dirs, files = self.storage.listdir(source)\n expected_dirs = [e[0] for e in dirs_tree]\n expected_files = [e for e in tree if isinstance(e, str)]\n self.assertCountEqual(dirs, ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares the given mode with a list of r/w/x bits and creates a RWX object for it. | def from_bitmask ( cls, mode, rwx_bits ):
return cls (
mode & rwx_bits[0], mode & rwx_bits[1], mode & rwx_bits[2],
) | [
"def from_stat_mode ( cls, stat_mode ):\n return cls (\n RWX.from_bitmask ( stat_mode, cls.USR_BITS ),\n RWX.from_bitmask ( stat_mode, cls.GRP_BITS ),\n RWX.from_bitmask ( stat_mode, cls.OTH_BITS ),\n )",
"def mode_to_flags(mode): # pylint: disable=too-many-branches\n if not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an integer representing the rwx mode for the given rwx bits. | def get_bitmask ( self, rwx_bits ):
ret = 0
if self.readable:
ret |= rwx_bits[0]
if self.writable:
ret |= rwx_bits[1]
if self.executable:
ret |= rwx_bits[2]
return ret | [
"def from_bitmask ( cls, mode, rwx_bits ):\n return cls (\n mode & rwx_bits[0], mode & rwx_bits[1], mode & rwx_bits[2],\n )",
"def getRgbMode(r: int, g: int, b: int) -> int:\n mode = 0\n if r:\n mode |= 4\n\n if g:\n mode |= 2\n\n if b:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new permissions object for the given string. | def from_str ( cls, s, strict=False ):
rwx_user = RWX.from_str ( s[0:3], strict=strict )
rwx_group = RWX.from_str ( s[3:6], strict=strict )
rwx_others = RWX.from_str ( s[6:9], strict=strict )
return cls ( rwx_user, rwx_group, rwx_others ) | [
"def from_string(cls, permission):\n p_read = 'r' in permission\n p_add = 'a' in permission\n p_update = 'u' in permission\n p_process = 'p' in permission\n\n parsed = cls(p_read, p_add, p_update, p_process)\n\n return parsed",
"def create(cls, init=None):\n # type... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a permissions object for the given stat mode. | def from_stat_mode ( cls, stat_mode ):
return cls (
RWX.from_bitmask ( stat_mode, cls.USR_BITS ),
RWX.from_bitmask ( stat_mode, cls.GRP_BITS ),
RWX.from_bitmask ( stat_mode, cls.OTH_BITS ),
) | [
"def create(cls, init=None):\n # type: (Union[int, Iterable[Text], None]) -> Permissions\n if init is None:\n return cls(mode=0o777)\n if isinstance(init, cls):\n return init\n if isinstance(init, int):\n return cls(mode=init)\n if isinstance(init,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls chmod(fspath) and chown(fspath) after creating an intermediate ChownChmod instance. | def chown_chmod ( fspath, uid=None, gid=None, mode=None, pretend=False ):
return ChownChmod ( uid, gid, mode, pretend ).chown_chmod ( fspath ) | [
"def chown_dir ( self, fspath ):\n return",
"def chown_stat ( self, fspath, mode ):\n if stat.S_ISDIR ( mode ):\n return self.chown_dir ( fspath )\n else:\n return self.chown_file ( fspath )",
"def chmod ( self, fspath ):\n if os.path.isdir ( fspath ):\n return self.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Similar to "touch ". | def do_touch ( self, fspath ):
return | [
"def touch(filePath):\n os.system('touch \"%s\"' % filePath)",
"def _touch( f, mtime=None ):\n cmd = [ 'touch' ]\n opts = None\n args = [ '-h' ]\n if mtime:\n args.extend( [ '-t', mtime.strftime( '%Y%m%d%H%M.%S' ) ] )\n args.append( str( f ) )\n output, errput = runcmd( cmd, opts, args... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls chown_dir(fspath) or chown_file(fspath), depending on whether fspath is a directory or not. | def chown ( self, fspath ):
if os.path.isdir ( fspath ):
return self.chown_dir ( fspath )
else:
return self.chown_file ( fspath ) | [
"def chown_dir ( self, fspath ):\n return",
"def chown_stat ( self, fspath, mode ):\n if stat.S_ISDIR ( mode ):\n return self.chown_dir ( fspath )\n else:\n return self.chown_file ( fspath )",
"def chown(path, uid, gid):\n pass",
"def chown_chmod ( fspath, uid=None, gid=None,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Similar to chown(fspath), but checks the given mode in order to decide whether fspath is a dir. | def chown_stat ( self, fspath, mode ):
if stat.S_ISDIR ( mode ):
return self.chown_dir ( fspath )
else:
return self.chown_file ( fspath ) | [
"def chmod_chown_stat ( self, fspath, mode ):\n if stat.S_ISDIR ( mode ):\n return (\n self.chmod_dir ( fspath ), self.chown_dir ( fspath )\n )\n else:\n return (\n self.chmod_file ( fspath ), self.chown_file ( fspath )\n )",
"def chmod_stat ( self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the owner of a directory. | def chown_dir ( self, fspath ):
return | [
"def UpdateOwnership(filename_or_directory):\r\n\r\n # By default, do nothing as not all shells support running as sudo\r\n pass",
"def adapt_owner(target):\n par_stat = os.stat(os.path.dirname(target))\n os.chown(target, par_stat.st_uid, par_stat.st_gid)",
"def chown(self, tarinfo, targetpa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls chmod_dir(fspath) or chmod_file(fspath), depending on whether fspath is a directory or not. | def chmod ( self, fspath ):
if os.path.isdir ( fspath ):
return self.chmod_dir ( fspath )
else:
return self.chmod_file ( fspath ) | [
"def chmod_stat ( self, fspath, mode ):\n if stat.S_ISDIR ( mode ):\n return self.chmod_dir ( fspath )\n else:\n return self.chmod_file ( fspath )",
"def chmod_chown_stat ( self, fspath, mode ):\n if stat.S_ISDIR ( mode ):\n return (\n self.chmod_dir ( fspath ), s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Similar to chmod(fspath), but checks the given mode in order to decide whether fspath is a dir. | def chmod_stat ( self, fspath, mode ):
if stat.S_ISDIR ( mode ):
return self.chmod_dir ( fspath )
else:
return self.chmod_file ( fspath ) | [
"def check_permissions(path, mode):\n return oct(os.stat(path).st_mode)[-3:] == mode",
"def chmod_chown_stat ( self, fspath, mode ):\n if stat.S_ISDIR ( mode ):\n return (\n self.chmod_dir ( fspath ), self.chown_dir ( fspath )\n )\n else:\n return (\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Similar to chmod_chown(), but checks mode in order to decide whether fspath is a dir. | def chmod_chown_stat ( self, fspath, mode ):
if stat.S_ISDIR ( mode ):
return (
self.chmod_dir ( fspath ), self.chown_dir ( fspath )
)
else:
return (
self.chmod_file ( fspath ), self.chown_file ( fspath )
) | [
"def chown_stat ( self, fspath, mode ):\n if stat.S_ISDIR ( mode ):\n return self.chown_dir ( fspath )\n else:\n return self.chown_file ( fspath )",
"def chmod_stat ( self, fspath, mode ):\n if stat.S_ISDIR ( mode ):\n return self.chmod_dir ( fspath )\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies a file from source to dest. | def _copy_file ( self, source, dest ):
return | [
"def copyFile( src, dest ):\n\tinFile = open( src, 'r' )\n\toutFile = open( dest, 'w' )\n\tfor line in inFile:\n\t\toutFile.write( line )\n\toutFile.close()\n\tinFile.close()",
"def copy_file(src, dest):\r\n # Check if destination file exist or not, if not, create a new file\r\n if not os.path.exists(dest):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies a file from source to dest and calls chmod(),chown() afterwards. | def copy_file ( self, source, dest, chown=True, chmod=True ):
if self._copy_file ( source, dest ):
if chmod:
self.chmod_file ( dest )
if chown:
self.chown_file ( dest )
return True
else:
return False | [
"def copy_file(src, dest):\r\n # Check if destination file exist or not, if not, create a new file\r\n if not os.path.exists(dest):\r\n create_new_file(dest)\r\n else:\r\n if os.path.isdir(dest):\r\n dest = os.path.join(dest, os.path.basename(src))\r\n create_new_file(de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls dodir(dir) for each dir in dirs. | def dodirs ( self, *dirs, **kwargs ):
for dirpath in dirs:
self.dodir ( dirpath, **kwargs ) | [
"def dir_visitor(dirname, visitor):\n visitor(dirname)\n for obj in os.listdir(dirname):\n obj_path = os.path.join(dirname, obj)\n if os.path.isdir(obj_path):\n dir_visitor(obj_path, visitor)",
"def change_alldir(dir_list):\n for dir_name in dir_list: # For each class dir\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes fspath if it is an empty directory or a file (or link). | def wipe ( self, fspath ):
return self.rmdir ( fspath ) or self.unlink ( fspath ) | [
"def clean_path(file_path):\n\n pass",
"def clear_path(path):\n\n stripped_path = strip_path(path)\n directories = stripped_path[0]\n filename = stripped_path[1]\n if filename == '':\n raise exceptions.CstashCriticalException(message=\"helpers.clear_path() was given a \" \\\n \"di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively copies files from source_root to dest_root (while keeping its directory structure). Ownership and permissions are not preserved, instead copied files and created dirs will have to permissions set during initialization of this object. | def copy_tree ( self,
source_root, dest_root, overwrite=True, followlinks=False
):
dodir = self.dodir
copy_file = self.copy_file
if overwrite:
for source, dest, relpath, dirs, files, dirnames in walk_copy_tree (
source_root, dest_root, followlinks=followlinks
... | [
"def _recursive_copy(self, src, dest):\n for item in os.listdir(src):\n file_path = os.path.join(src, item)\n\n # if item is a file, copy it\n if os.path.isfile(file_path):\n shutil.copy(file_path, dest)\n\n # else if item is a folder, recurse\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates symlinks to source_root's content in dest_root. | def copy_dirlink_tree ( self,
source_root, dest_root, overwrite=False, followlinks=False
):
unlink = self.unlink
symlink = self.symlink
source, dest, relpath, dirs, files, dirnames = next (
walk_copy_tree ( source_root, dest_root, followlinks=followlinks )
)
self.dodi... | [
"def create_symlinks(config, source_directory, target_directory):\n process_directories(config, source_directory, target_directory, symlink)",
"def link(self, src, dst, label=None):\n self._tag(dst, label)\n self._mkdir_for(dst)\n abs_src = self._rootjoin(src)\n abs_dst = os.path.join(self.chroot, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A trivial test of the StatsModelsWrapper | def test_stats_models_wrapper():
X = np.array([[1], [2], [3]])
y = np.array([1.1, 2, 3])
glm_gaussian = functools.partial(sm.GLM, family=sm.families.Gaussian())
sm_est = StatsModelsWrapper(glm_gaussian)
assert sm_est.fit(X, y) is sm_est, "fit did not return self"
assert sm_est.predict(X).shape... | [
"def testGetModelsData(self):\n models = models_logic._getModelsData()\n self.assertTrue(models)",
"def test_get_stats(self):\n pass",
"def test_calc_model_sparsity():\n model = iris()\n assert calc_model_sparsity(model)",
"def test_predictor():",
"def test_model_obj():\n # Get the amb... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the api key for the hypixel api. | def get_hypixel_key(self):
key = self.bot_data_file["apiKeys"]["hypixel"]
if self.check_empty_key(key):
return key
else:
print("ERROR GETTING THE HYPIXEL KEY (get yours from https://api.hypixel.net/) - ABORTING")
quit(1) | [
"def get_api_key(self):\r\n url = '{0}/{1}'.format(self.get_url(), 'api_key')\r\n\r\n return http.Request('GET', url), parsers.parse_json",
"def api_key(self) -> Any:\n return pulumi.get(self, \"api_key\")",
"def api_key(self) -> Optional[str]:\n return self[\"requestContext\"][\"ide... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the api key for the gif api. | def get_gif_key(self):
key = self.bot_data_file["apiKeys"]["gif"]
if self.check_empty_key(key):
return key
else:
print("ERROR GETTING THE GIF KEY (get yours from http://api.giphy.com/) - ABORTING")
quit(1) | [
"def get_api_key(api_key):\n api.get(api_key)",
"def get_api_key(self):\r\n url = '{0}/{1}'.format(self.get_url(), 'api_key')\r\n\r\n return http.Request('GET', url), parsers.parse_json",
"def api_key(self) -> Any:\n return pulumi.get(self, \"api_key\")",
"def get_apikey():\n #load ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the default weather country to use | def get_weather_country(self):
return self.bot_data_file["weather"]["default_country"] | [
"def country() -> str:",
"def get_default_country(self):\n proxy = self.env['ir.config_parameter']\n default_country = proxy.sudo().get_param('default_country')\n if not default_country:\n raise UserError('Please use Default Country as US in config parameters.')\n return def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the default weather language for the results | def get_weather_language(self):
return self.bot_data_file["weather"]["default_language"] | [
"def get_default_language() -> str:\n\n return 'en'",
"def get_fallback_language():\n return settings.DEFAULT_LANGUAGE",
"def get_default_language(model):\n return get_translation_opt(model, 'default_language')",
"def get_single_language(kanton):\n if (kanton == \"TI\"):\n return \"IT\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the default rocket league platform to use | def get_rocket_league_platform(self):
return self.bot_data_file["rocketleague"]["default_platform"] | [
"def get_platform():\n pl = 'common'\n\n if 'PLATFORM' in os.environ:\n pl_low = PLATFORM.lower()\n if pl_low in platform_map.keys():\n pl = platform_map[pl_low]\n elif pl_low in platform_map.values():\n pl = pl_low\n elif PLATFORM == '':\n print(\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the api key for the youtube api. | def get_youtube_api_key(self):
key = self.bot_data_file["youtube"]["key"]
if self.check_empty_key(key):
return key
else:
print(
"ERROR GETTING THE YOUTUBE KEY (check bot documentation) - ABORTING")
quit(1) | [
"def get_youtube_dev_key():\r\n return getenv('YOUTUBE_DEV_KEY')",
"def get_api_key(self):\r\n url = '{0}/{1}'.format(self.get_url(), 'api_key')\r\n\r\n return http.Request('GET', url), parsers.parse_json",
"def load_api_key():\n try:\n __location__ = os.path.realpath(os.path.join(os.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the list of the youtube channels to check, with all the details about the notification | def get_list_youtube_channels_check(self):
return self.bot_data_file["youtube"]["channels"] | [
"def _channels_list(self):\n result = self.slack.api_call(\"channels.list\")\n\n if not result.get(\"ok\"):\n logging.error(result['error'])\n return None\n\n return result['channels']",
"def get_user_channels(self):\n\n request = self.youtube.subscriptions().list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the current version of the bot. | def get_version(self):
return self.bot_data_file["version"] | [
"async def version():\n\t\treal_version = pingbot.updater().value_download('https://dl.dropboxusercontent.com/s/1welpdvy23ycyih/realver.json?dl=0', 'real_version', './core/sys/realver.json')\n\t\tpingbot.updater().file_delete('./core/sys/realver.json')\n\t\tif bot_version == real_version:\n\t\t\tversion_msg = \"(Up... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the current build number of the bot. | def get_build(self):
return self.bot_data_file["build"] | [
"def getBuildNumber(self, requestContext):\n return self.service.build() or \"\"",
"def build_number(self):\n return self.get_data(\"build_number\")",
"def nextBuildNumber(self):\n return self._info['lastBuildNumber']",
"def get_build_number():\n try:\n return int(os.getenv(*leg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the description of the bot. | def get_description(self):
return self.bot_data_file["description"] | [
"async def description(ctx, bot: typing.Union[discord.Member, discord.User]):\n data = await make_request(\"https://www.motiondevelopment.top/api/v1.2/bots/\", bot.id)\n if not bot.bot:\n return await r(ctx, \"Not a bot.\")\n\n if len(data[\"Big_desc\"]) > 2000:\n desc = data[\"Big_desc\"][:2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the current bot icon. This icon is used for embed messages | def get_bot_icon(self):
return self.bot_data_file["bot_icon"] | [
"def icon(self):\r\n return Meta.server_icon(self.guild)",
"def get_icon(self):\n return self.icon",
"def get_icon(self) -> Dict[str, Any]:\n player = self._last_sessionplayer\n assert player is not None\n return player.get_icon()",
"def icon(self):\r\n try:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the current default status of the bot. | def get_default_status(self):
return self.bot_data_file["bot_status"]["defaultStatus"] | [
"def DefaultTradeStatus():\n hook = GetCustomHook(\"DefaultTradeStatus\")\n if hook is not None:\n return hook()\n return _SETTINGS.TradeStatusOnCreation()",
"def getDefaultStatus(session_key):\n\n # Get the list of statuses\n logger.debug(\"Getting the default status\")\n sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the current command prefix of the bot. | def get_command_prefix(self):
return self.bot_data_file["commands_prefix"] | [
"def get_command_prefix() -> str:\n raise NotImplementedError(\"need to implement command prefix\")",
"def cmdprefix(self) -> str:\n return self.config[\"Core\"].get(\"CmdPrefix\", \"!\")",
"async def get_command_prefix(self, guild: Guild) -> str:\n if (prefix := self._cache[guild.id].prefi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the bot source code link. | def get_open_source_link(self):
return self.bot_data_file["open_source_link"] | [
"async def _botsource(self, ctx):\r\n source_link = \"https://github.com/Simalary/SimsVIP.Servo\"\r\n await self.bot.say('{0.message.author.mention}, my source code is available at <{1}>.'.format(ctx, source_link))",
"def getBuildbotURL():",
"async def source_github(self, ctx):\n await ctx.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the bot private chat alert message | def get_private_chat_alert(self):
return self.bot_data_file["private_chat_alert"] | [
"def handle(self, msg):\n\n flavor = telepot.flavor(msg) # Messages come in different flavors.\n # We are only interested in private\n # chat messages.\n\n if flavor != \"chat\":\n print(\"Unsupported message flavor ign... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the max_cleverbot_requests. | def get_max_cleverbot_requests(self):
return int(self.bot_data_file["maxCleverbotRequests"]) | [
"def max_wait_count(self) -> int:\n return self._config['max_wait_count']",
"def get_max_pending_requests(self) -> int:\n return int(self._send_sensor_request(\n 'GetLidarMaxPendingGpuRequests', ack='CompletedGetLidarMaxPendingGpuRequests', name=self.name)['data'])",
"def max_connection... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that return the url where to write the status. | def get_server_write_status_url(self):
write_url: str = self.bot_data_file["bot_status"]["server_state_saving"]["writeStateUrl"]
print("Api:" + self.empty_api_key)
print("Url:" + self.empty_url)
if self.get_bot_save_state_to_server() and write_url.startswith(self.empty_url):
... | [
"def get_absolute_url(self):\n return \"/status/%i/\" % self.id",
"def status_url(self, username, id):\n return urllib.parse.urljoin(self.instance, f'/p/{urllib.parse.quote(username)}/{id}')",
"def get_status_url(self):\n status_handler_view = 'appraise.evaluation.views.status_view'\n kw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |