query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Select the first helper that is available from the given list. If no helper in the list is currently installed, will install the first installable helper from the list. | def helper_select(choices):
def _name_min_ver_from_choice(choice):
if isinstance(choice, str):
# Helper name only, no version constraints
name = choice
min_version = None
else:
# Tuple of (name, version)
(name, vers) = choice
mi... | [
"def androidCheckAndInstallHelper():\n\ttry:\n\t\tdevice_pkg_list = subprocess.Popen([\"adb\", \"shell\", \"pm\", \"list\", \"packages\"],stdout=subprocess.PIPE)\n\t\tif (sys.platform == 'win32'):\n\t\t\tstatus = subprocess.call([\"findstr\", glob_helper_id], stdin=device_pkg_list.stdout, stdout=stdout,stderr=stder... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List Submarine CLI Config | def list_config():
console = Console()
_config = loadConfig()
json_data = richJSON.from_data({**asdict(_config)})
console.print(Panel(json_data, title="SubmarineCliConfig")) | [
"def config(ctx):\n if not ctx.invoked_subcommand:\n cfg = ctx.obj['cfg']\n for section in cfg.sections():\n print(\"[\", section, \"]\")\n for option in cfg[section]:\n print(option, \" = \", cfg[section][option])",
"def test_config_list():\n client = Test... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Init Submarine CLI Config | def init_config():
try:
initConfig()
click.echo("Submarine CLI Config initialized")
except AttributeError as err:
click.echo(err) | [
"def ConfigInit():\n # Initialize the config system from the command line options.\n config_lib.ParseConfigCommandLine()",
"def _init_cli_config() -> None:\n conf_dir = os.path.dirname(CLI_CONFIG_PATH)\n if not os.path.exists(conf_dir):\n os.makedirs(conf_dir)\n with open(CLI_CONFIG_PATH, \"w+\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
receives employee and adds to his attendance the date from the computer | def mark_attendance(employee):
# loads date from computer
today = datetime.datetime.now()
mark = today.strftime("%d/%m/%Y %H:%M")
# adds to attendance list in object
employee.attendance.append(mark)
return employee.attendance | [
"def atten_date(list_emp, name, start_rep, end_rep):\r\n with open(\"attendance_log.txt\", \"w\") as attendance_by_emp:\r\n # writes new\\re writes attendance_log from the beginning\r\n attendance_by_emp.seek(0)\r\n attendance_by_emp.write(\"Employee Attendance Report %s-%s:\\n\" % (start_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
receives employees list and name of employee writes attendance log by the dates marked in employee attendance section from employee log | def atten_employee(list_emp, name):
with open("attendance_log.txt", "w") as attendance_by_emp:
attendance_by_emp.seek(0)
attendance_by_emp.write("Employee Attendance Report:\n")
for worker in list_emp:
if worker.name == name:
attendance_by_emp.write("%s-\n" ... | [
"def atten_date(list_emp, name, start_rep, end_rep):\r\n with open(\"attendance_log.txt\", \"w\") as attendance_by_emp:\r\n # writes new\\re writes attendance_log from the beginning\r\n attendance_by_emp.seek(0)\r\n attendance_by_emp.write(\"Employee Attendance Report %s-%s:\\n\" % (start_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
receives employees list and name of employee and dates for report writes attendance log by the dates marked in employee attendance section from employee log that are in between the dates given | def atten_date(list_emp, name, start_rep, end_rep):
with open("attendance_log.txt", "w") as attendance_by_emp:
# writes new\re writes attendance_log from the beginning
attendance_by_emp.seek(0)
attendance_by_emp.write("Employee Attendance Report %s-%s:\n" % (start_rep, end_rep))
... | [
"def atten_employee(list_emp, name):\r\n with open(\"attendance_log.txt\", \"w\") as attendance_by_emp:\r\n attendance_by_emp.seek(0)\r\n attendance_by_emp.write(\"Employee Attendance Report:\\n\")\r\n for worker in list_emp:\r\n if worker.name == name:\r\n attendan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
receives employees list and month to issue report writes attendance log by the dates marked in employee attendance section from employee log that are on the month given | def atten_month(list_emp, month):
count = 0
with open("attendance_log.txt", "w") as attendance_by_emp:
# writes new\re writes attendance_log from the beginning
attendance_by_emp.seek(0)
attendance_by_emp.write("Monthly Attendance Report:\n")
# for each worker
for w... | [
"def atten_date(list_emp, name, start_rep, end_rep):\r\n with open(\"attendance_log.txt\", \"w\") as attendance_by_emp:\r\n # writes new\\re writes attendance_log from the beginning\r\n attendance_by_emp.seek(0)\r\n attendance_by_emp.write(\"Employee Attendance Report %s-%s:\\n\" % (start_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reads latest report issued to attendance_log and makes list out of it by name of worker and dates | def read_rep():
import re
name = ''
date_list = []
attendance_list = []
with open("attendance_log.txt", "r+") as attendance_log:
# reads report from beginning
attendance_log.seek(0)
text = attendance_log.readline()
# reads till the end of file
while ... | [
"def atten_date(list_emp, name, start_rep, end_rep):\r\n with open(\"attendance_log.txt\", \"w\") as attendance_by_emp:\r\n # writes new\\re writes attendance_log from the beginning\r\n attendance_by_emp.seek(0)\r\n attendance_by_emp.write(\"Employee Attendance Report %s-%s:\\n\" % (start_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get phrase with highest match in answer | def get_fuzzy_match(object, answer, threshold=80):
answer_phrase = generate_ngrams(answer)
if answer_phrase:
best_match = [fuzz.ratio(object, phr) for phr in answer_phrase]
if np.max(best_match)>threshold:
return np.max(best_match), answer_phrase[np.argmax(best_match)]
else:
... | [
"def fuzzy_max(words, dictionary):\n score = 0\n word = \"\"\n\n for x in dictionary:\n temp = fuzzy_score(x, words)\n if temp > score:\n score = temp\n word = x\n\n return word, score",
"def get_fuzzy_match(object, answer, threshold=0.8):\n answer_phrase = gener... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find control based on criteria passed in | def find_control(class_name = None,
class_name_re = None,
title = None,
title_re = None,
top_level_only = False,
visible_only = True,
enabled_only = False,
auto_id = None,
control_type... | [
"def FindControlById(self, id):\n for ctrl in self.__controls.values():\n if ctrl.id == id:\n return ctrl\n return None",
"def find(self,*criterion):\n raise NotImplementedError(\"Subclasses should overwrite this Method.\")",
"def FindControl(self, id):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print information. The message will be displayed only when set in verbose mode | def print_info(message: str):
global verbose
if verbose:
print("%s%s%s" % (KYEL, message, KNRM)) | [
"def info(msg):\n if script.verbosity_level >= script.VERBOSITY_DEFAULT:\n print msg",
"def verbose(self, message):\n if not self.args.quiet and (self.args.verbose or self.args.debug):\n print(message)",
"def info(self, message):\n if not self.args.quiet:\n print(me... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get wb entity from wikidata querying id | def get_wbentity(id: str, language: str) -> dict:
url = "%s?format=json&action=wbgetentities&ids=%s&languages=%s" % (WIKIDATA_URL, id, language)
# Perform request
print_debug("Sending GET %s" % url)
response = requests.get(url)
data = response.json()
print_debug("%s -> %d" % (url, response.statu... | [
"def _get_wb_id_for_entrez(entry):\n id_set = re.findall(r'WormBase:(WBGene[0-9]{8})', entry)\n if len(id_set):\n return ','.join(id_set)\n return None",
"def fetchwikidata(a_wid):\n\n sparql = SPARQLWrapper(\"https://query.wikidata.org/sparql\", 'natural_earth_name_localizer v1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a human entity, gather its metadata | def process_human_entity(entity: dict, language: str) -> bool:
try:
claims = entity["claims"]
# Get ID
remote_id = entity["title"]
print("%s\t%s" % ("ID".ljust(16), remote_id))
# Get name from label
name = entity["labels"][language]["value"].lower()
print("%s\... | [
"def GetMetadata(self):\n return self.dict['meta']",
"def metadata():\n pass",
"def get_metadata(self):\n self.get_data()\n self.metadata = extract_metadata(self.model, self.data)",
"def details(self):\n return self.request(\"/details.json\")[\"Response\"][\"Data\"][\"Entity\"]",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a topic entity, gather its metadata | def process_topic_entity(entity: dict, language: str) -> bool:
try:
# Get ID
remote_id = entity["title"]
print("%s\t%s" % ("ID".ljust(16), remote_id))
# Get name from label
name = entity["labels"][language]["value"].lower()
print("%s\t%s" % ("name".ljust(16), name))
... | [
"def get_topics_atts(self, topics):\n topic_names = db.select(fields=\"words\", table=\"topic_words\", order_by=\"topic_id\")\n atts = {}\n for topic in topics:\n topic_name = topic_names[topic]\n atts[topic] = {\"label\": topic_name, \"description\": topic_name}\n\n return atts",
"def entit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test max backprop for degeneratevalued tensors | def test_degenerate_max_back(fill_val, shape, num_axes, keepdims):
a = Tensor(np.full(shape=shape, fill_value=fill_val, dtype=float))
if num_axes == 0:
axes = None
else:
axes = tuple(np.random.choice(range(0, a.ndim), size=min(num_axes, a.ndim), replace=False))
out = a.max(axis=axes, k... | [
"def test_max_back(a, num_axes, keepdims):\n if num_axes == 0:\n axes = None\n else:\n axes = np.random.choice(range(0, a.ndim), size=min(num_axes, a.ndim), replace=False)\n axes = tuple(sorted(axes))\n\n # single global maximum\n if axes is None or axes == tuple(range(a.ndim)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Tensor.max for arbitrary data, axis, and keepdim | def test_max_back(a, num_axes, keepdims):
if num_axes == 0:
axes = None
else:
axes = np.random.choice(range(0, a.ndim), size=min(num_axes, a.ndim), replace=False)
axes = tuple(sorted(axes))
# single global maximum
if axes is None or axes == tuple(range(a.ndim)):
index = ... | [
"def max(tensor, axis=None):\n raise NotImplementedError",
"def dim_zero_max(x: Tensor) ->Tensor:\n return torch.max(x, dim=0).values",
"def max(self, dim=None, keepdim=False):\n return array_funcs.max(self, dim, keepdim)",
"def reduce_max(input_tensor, axis=None):\n\n return pd.max(input_tens... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns accuracy. top_k is a dict as returned by get_top_k(). | def get_accuracy(top_k):
n_correct = [(question in paragraphs) for question, paragraphs in top_k.items()]
accuracy = sum(n_correct)/len(top_k)*100
return accuracy | [
"def accuracy(output, target, topk=(1,5)):\n maxk = max(topk)\n # sizefunction: the number of total elements\n batch_size = target.size(0) \n \n # topk function selects the number of k before output\n _, pred = output.topk(maxk, 1, True, True)\n ##########Do not understand t()k\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a similarity matrix based on the distance in the BERT encoded space | def get_BERT_similarity(questions, paragraphs):
E_Q = encoder_BERT(tokenize_BERT(questions))
E_P = encoder_BERT(tokenize_BERT(paragraphs))
sim = torch.matmul(E_Q, E_P.T)
return sim.numpy() | [
"def distance_embeddings(embeddings_matrix):\n distance = 0\n l = 0\n for row1, row2 in it.combinations(embeddings_matrix, 2):\n new_distance = np.sqrt(np.sum(np.power(row1-row2, 2)))\n distance += new_distance\n l += 1\n\n av_distance = distance / l\n return av_distance",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the process id for a currently running sl robot | def get_process_pid(robot_name):
try:
result = check_output(['pgrep', 'x{0}'.format(robot_name)])
return int(result.strip())
except:
return None | [
"def findRobot(self):\n rpid = self.robot['SCRIPTOBS_PID'].read(binary=True)\n if rpid == '' or rpid == -1:\n return rpid, False\n else:\n return rpid, True",
"def _get_process_id(self):\n for proc in psutil.process_iter():\n if self.exe in proc.name():... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the key for a semaphore from its name string | def get_semaphore_key(name, pid):
key = pid
for i in range(0, len(name)):
key += i * 100 + ord(name[i])
return key | [
"def key_for_name(name):\n return 'hotqueue:%s' % name",
"def get_key(name):\n keys = load_keys()\n return keys.get(name)",
"def get_key(command):\n return command.split(\" \")[1]",
"def lockKey(self, index):\n return self.taskNameBase + '-' + ReadWriteLock.LOCK_PARAM + '-' + str(index)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get semaphore by name, will wait until time out (default forever) | def get_semaphore(name, pid, time_out=None, pause=0.1):
semaphore_key = get_semaphore_key(name, pid)
while True:
try:
return Semaphore(semaphore_key)
except ExistentialError:
sleep(pause)
if time_out is not None:
time_out -= pause
if tim... | [
"def waitWithTimeout(self, *args):\n return _yarp.Semaphore_waitWithTimeout(self, *args)",
"def create_semaphore(value: int) -> Semaphore:\n return _get_asynclib().Semaphore(value)",
"def create_semaphore(value: int, *, max_value: Optional[int] = None) -> Semaphore:\n return Semaphore(value, max_va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
confirm if semaphore exists by key | def check_semaphore(semaphore_key):
if isinstance(semaphore_key, str):
semaphore_key = eval(semaphore_key)
keys = [eval(sem['key']) for sem in list_semaphores()]
return semaphore_key in keys | [
"def check(self):\n return _yarp.Semaphore_check(self)",
"async def _exists(self, key):\n return key in SimpleMemoryBackend._cache",
"def exists(self, key):\n r = self.mc.get(key)\n if r not in (None, _empty_slot):\n return True\n else:\n return self.db.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update self.Designs to reflect the files read from designfiles. | def updateDesigns(self, designfilenames):
self.Designs = [Design(filename) for filename in designfilenames]
self.parseDesigns()
return self.Designs | [
"def selfupdate(self):\n self.mk_designcon()\n self.mk_designmat()\n self.mk_designgrp()",
"def compareDesigns(self):\n if len(self.Designs) < 2:\n print(\"compareDesigns() ERROR: self.Designs < 2 - aborting !\")\n return\n # Finished parsing the designs, l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse all designs given by . If no design arg is provided, parses self.Designs. | def parseDesigns(self, designs=None):
if designs is None:
designs = self.Designs
for design in designs:
# code moved to design, where it is more logically placed in OOP.
design.parse_csvfile()
#designfilename = design.Filename | [
"def read_design(designfile):\r\n designtype = None\r\n if re.search(r\"\\.adm$\", designfile, flags=re.I) is not None:\r\n designtype = XMLDesign\r\n elif re.search(r\"\\.xml$\", designfile, flags=re.I) is not None:\r\n designtype = XMLDesign\r\n elif re.search(r\"\\.json$\", designfile, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares self.Designs[0] against self.Designs[1]. | def compareDesigns(self):
if len(self.Designs) < 2:
print("compareDesigns() ERROR: self.Designs < 2 - aborting !")
return
# Finished parsing the designs, let's do some initial comparison:
print(self.Designs)
self.DesignsetIntersection = self.Designs[0].Designset &... | [
"def updateDesigns(self, designfilenames):\n self.Designs = [Design(filename) for filename in designfilenames]\n self.parseDesigns()\n return self.Designs",
"def comparison(self) -> DesignComparison:\n return self._comparison",
"def allow_duplicate_design(self):\n return self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare a design in self.Designs against rackfiles. If rackfiles are not given, glob the current directory after .rack.csv files. If designfilenames are not given, use designs in self.Designs. If these are not found either, then glob for .smmc files. | def compareDesignVsRackfiles(self, designfilenames=None, rackfilenames=None):
# 1) READ RACK DATA and make oligo_racks DATASTRUCTURE:
# Copy/paste a lot from epmotion_staplemixer:
if rackfilenames is None:
ext = ".rack.csv"
#rackfilenames = [fname for fname in os.listdir... | [
"def file_matches(self, filename):\n sofar = (((\"observatory\", self.observatory),\n (\"instrument\",self.instrument),\n (\"filekind\", self.filekind),),)\n return sorted(self.selector.file_matches(filename, sofar))",
"def parseDesigns(self, designs=None):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
From epmotion_staplemixer.py Used to select a particular candidate determined from a hint, e.g. hint "seq" will find "Sequence" in candidates ("Rack","Sequence","Start") | def findFieldByHint(self, candidates, hints):
if not isinstance(hints, (list, tuple)):
hints = (hints,)
for hint in hints:
for candidate in candidates:
if hint in candidate.lower():
return candidate
# None of the hints were found in eit... | [
"def search(search, candidates):\n choicer = choices.Choice()\n for candidate in candidates:\n choicer.add(candidate)\n return choicer.search(search)",
"def candidate_selection(self, pos=None):\n\n if pos is None:\n pos = {'NOUN', 'PROPN', 'ADJ'}\n\n # select sequence of a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot historic load with indication of train/test/validation periods | def plot_historic_with_sets(historic_data, periods):
fig = (
historic_data[["load"]]
.dropna()
.iplot(
asFigure=True,
layout=dict(
xaxis=dict(title=""),
yaxis=dict(title="Belasting [MW?]"),
margin=dict(b=0, t=0, l=0, r=... | [
"def plot_training_progress(self):\r\n x = [self.record_every_nth * i for i in np.arange(len(self.train_loss))]\r\n plt.figure()\r\n plt.plot(x,self.train_loss)\r\n plt.plot(x,self.val_loss)\r\n plt.legend(['Train', 'Validation'], loc='best')\r\n plt.xlabel('Training epoch'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot typical profile for weekday / weekendday Note, this does not make much sense for windpower | def plot_typical_day(bdf):
bdf["time"] = bdf.index.time
bdf["weekday"] = bdf.index.weekday < 5
week_profile = bdf[bdf.weekday].pivot_table(
index="time", values="load", aggfunc=["mean", "max", "min"]
)
week_profile.columns = ["week_mean", "week_max", "week_min"]
weekend_profile = bdf[~b... | [
"def wtk_diurnal_plot(self):\n\n sum_df = self._df.groupby(self._df[self._t])[self._w].sum().to_frame()\n # df_temp = sum_df.copy()\n # df_temp[self._t] = df_temp.index\n\n # df_diurnal = df_temp.groupby(df_temp[self._t].dt.hour)[self._w].mean()\n df_diurnal = sum_df.groupby(sum_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates amount of congestion mitigation. This fucntion asumes congestion mitigation is always applied when the forecasts exceeds the congestion limit. | def calculate_amount_congestion_mitigation(
forecast_mw: pd.Series, congestion_limit_mw: float
) -> pd.Series:
# Depending on the sign of the congestion limit apply a different calculation
if np.sign(congestion_limit_mw) == 1: # In case of a positive congestion limit
return np.abs(np.maximum(forec... | [
"def calculate_reduced_congestion(\n congestion_before_mitigation_mw: pd.Series,\n congestion_after_mitigation_mw: pd.Series,\n) -> pd.Series:\n return congestion_before_mitigation_mw.abs() - congestion_after_mitigation_mw.abs()",
"def calculate_missed_congestion(congestion_after_mitigation_mw: pd.Series... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates how much congestion is reduced after applying the mitigation | def calculate_reduced_congestion(
congestion_before_mitigation_mw: pd.Series,
congestion_after_mitigation_mw: pd.Series,
) -> pd.Series:
return congestion_before_mitigation_mw.abs() - congestion_after_mitigation_mw.abs() | [
"def _total_chunk_size_left(self):\n if self.streaming_type == 'reshape':\n return self.N_l // self.conv_factor\n elif self.streaming_type == 'mask':\n return self.N_l // self.conv_factor * self.n_layers\n elif self.unidir:\n return 10000 // self.conv_factor\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates how much congestion is missed after applying the mitigation | def calculate_missed_congestion(congestion_after_mitigation_mw: pd.Series) -> pd.Series:
return congestion_after_mitigation_mw.abs() | [
"def calculate_reduced_congestion(\n congestion_before_mitigation_mw: pd.Series,\n congestion_after_mitigation_mw: pd.Series,\n) -> pd.Series:\n return congestion_before_mitigation_mw.abs() - congestion_after_mitigation_mw.abs()",
"def total_sdram_requirements(self):",
"def recover(self):\r\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a key to the hash table. | def add(self, key):
addition_idx = self._reduce(self._hash(key))
if self.table[addition_idx] != "_":
# collision
new_idx = self._resolve_collision(addition_idx)
if new_idx == addition_idx:
# table is full; do not insert
print("Did not ... | [
"def add_key(self, tablename, key):\n raise NotImplementedError",
"def add(key, item):\n hash_key = hash_function(key)\n hash_table[hash_key - 1] = item",
"def add_key(self, key: str) -> None:\n self._keys.add(key)",
"def add(self, key, value):\n if not key in self:\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wraps a given Keras layer baseclass, adding Runtime Weight Scaling in the `build()` method using the constant from the He initializer. | def WeightScaled(
layer_base_class: Type[tf.keras.layers.Layer],
kernel_attr: str = "kernel",
kernel_initializer_attr: str = "kernel_initializer",
):
class WeightScaledVariant(layer_base_class):
def __init__(self, gain: float = 2.0, fan_in: int = None, *args, **kwargs):
s... | [
"def __mul__(self, constant):\n return WeightedParameterization(self, constant)",
"def extend_with_decoupled_weight_decay(base_optimizer):\n\n class OptimizerWithDecoupledWeightDecay(DecoupledWeightDecayExtension,\n base_optimizer):\n \"\"\"Base_optimizer with d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split an heroku syslog encoded payload using the octet counting | def split(self, bytes):
# '''Split by lines heroku payload and apply filters.'''
# lines = []
lines = []
while len(bytes) > 0:
# find first space character
i = 0
while bytes[i] != 32: # 32 is white space in unicode
i += 1
... | [
"def parse_syslog(line):\n line = line.decode(\"ascii\") # also UTF-8 if BOM\n if line.startswith(\"<\"):\n # fields should be \"<PRI>VER\", timestamp, hostname, command, pid, mid, sdata, payload\n fields = line.split(None, 7)\n line = fields[-1]\n return line",
"def parse_syslog (s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Will update ranking result weights based on relevance feedback from user. | def update_weights_rocchio(isRelevant, result):
global global_weights
max_contributing_weight = max(result.sim_measures, key=result.sim_measures.get)
if isRelevant:
global_weights[max_contributing_weight] += alpha
for measure in result.sim_measures:
global_weights[measure] -= beta
else:
global_weights[ma... | [
"def _update_ranking(self):\n # DB calls, this operation relies on two seperate kinds.\n player = User.query(User.key == self.user).get()\n scores = Score.query(Score.user == self.user)\n\n # Take this game into account when ranking:\n player.completed_games = player.completed_gam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Representation string consisting of all schedule policies of the commcell. | def __str__(self):
representation_string = '{:^5}\t{:^20}\n\n'.format('S. No.', 'Schedule Policy')
for index, policy in enumerate(self._policies):
sub_str = '{:^5}\t{:20}\n'.format(index + 1, policy)
representation_string += sub_str
return representation_string.strip() | [
"def get_schedule_string(self):\n schedule = \"\"\n for entry in self.entries:\n schedule += entry.get_entry_string()\n\n return schedule",
"def policy_repr(self, policy):\n return policy.__repr__()",
"def print_policy(self, policy):\n\t\tpol = np.array([self.actions_symbo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the schedule policies on this commcell dict consists of all schedule policies of the commcell { | def all_schedule_policies(self):
return self._policies | [
"def _get_schedule_policy_properties(self):\n flag, response = self._commcell_object._cvpysdk_object.make_request(\n 'GET', self._SCHEDULE_POLICY)\n\n if flag:\n if response.json() and 'taskInfo' in response.json():\n _task_info = response.json()['taskInfo']\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a schedule policy exists in the commcell with the input schedule policy name. | def has_policy(self, policy_name):
if not isinstance(policy_name, basestring):
raise SDKException('Storage', '101')
return self._policies and policy_name.lower() in self._policies | [
"def schedule_exist(self, schedule_name):\r\n schedule = self.find(\"schedules\", schedule_name, attribute=\"name\")\r\n if schedule is not None:\r\n return True\r\n else:\r\n return False",
"def get(self, schedule_policy_name, schedule_policy_id=None):\n\n if sch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the subtask in schedule policy JSON | def subtasks_json(policy_type):
_backup_subtask = {
"subTaskType": SchedulePolicies.policy_to_subtask_map[policy_type][0],
"operationType": SchedulePolicies.policy_to_subtask_map[policy_type][1]
}
return _backup_subtask | [
"def schedule_json(policy_type, schedule_dict):\n schedule_options = ScheduleOptions(ScheduleOptions.policy_to_options_map[policy_type]\n ).options_json(schedule_dict.get('options', None))\n sub_task = SchedulePolicies.subtasks_json(policy_type)\n sub_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the schedule json for the given schedule options and pattern | def schedule_json(policy_type, schedule_dict):
schedule_options = ScheduleOptions(ScheduleOptions.policy_to_options_map[policy_type]
).options_json(schedule_dict.get('options', None))
sub_task = SchedulePolicies.subtasks_json(policy_type)
sub_task['subT... | [
"def schedule_json(self) -> Optional[Dict]:\n if not self.schedule:\n return None\n else:\n start_time = conv_to_schedule(\n self.start_time if self.start_time else datetime.now()\n )\n end_time = conv_to_schedule(\n self.end_ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a schedule policy object of the specified schedule policy name. | def get(self, schedule_policy_name, schedule_policy_id=None):
if schedule_policy_name and not isinstance(schedule_policy_name, basestring):
raise SDKException('Schedules', '102')
if schedule_policy_id and not isinstance(schedule_policy_id, int):
raise SDKException('Schedules', ... | [
"def get_policy_from_name(base_policy_type: Type[BasePolicy], name: str) -> Type[BasePolicy]:\n if base_policy_type not in _policy_registry:\n raise KeyError(f\"Error: the policy type {base_policy_type} is not registered!\")\n if name not in _policy_registry[base_policy_type]:\n raise KeyError(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
deletes the specified schedule policy name. | def delete(self, schedule_policy_name):
if schedule_policy_name and not isinstance(schedule_policy_name, basestring):
raise SDKException('Schedules', '102')
schedule_policy_name = schedule_policy_name.lower()
schedule_policy_id = self.all_schedule_policies.get(schedule_policy_name)... | [
"def delete(self, policy_name):\n path = self.vault.normalize(\"/sys/policies/acl/\" + policy_name)\n address = self.vault.vault_adress + \"/v1\" + path\n # Actually run vault\n logging.info(\"Deleting the policy: %s\", address)\n self.vault.requests_request(\"DELETE\", address, h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refresh the Schedule Policies associated with the Commcell. | def refresh(self):
self._policies = self._get_policies() | [
"def refresh(self):\n self._get_schedule_policy_properties()",
"def _modify_schedule_policy_properties(self):\n request_json = {\n 'taskInfo':\n {\n 'taskOperation': 1,\n 'associations': self._associations,\n 'task': ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialise the Schedule Policy class instance. | def __init__(self, commcell_obj, schedule_policy_name, schedule_policy_id=None):
self._commcell_object = commcell_obj
self.schedule_policy_name = schedule_policy_name
if schedule_policy_id:
self.schedule_policy_id = schedule_policy_id
else:
self.schedule_policy... | [
"def __init__(self,\n continuous_schedule=None,\n daily_schedule=None,\n monthly_schedule=None,\n periodicity=None,\n rpo_schedule=None,\n ):\n\n # Initialize members of the class\n self.continuous_schedule = co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a schedule ID of the schedule policy Returns (int) schedule policy ID | def _get_schedule_policy_id(self):
schedule_policies = SchedulePolicies(self._commcell_object)
return schedule_policies.get(self.schedule_policy_name).schedule_policy_id | [
"def schedule_id(self) -> str:\n return pulumi.get(self, \"schedule_id\")",
"def pipeline_schedule_id(self) -> pulumi.Output[int]:\n return pulumi.get(self, \"pipeline_schedule_id\")",
"def policy_id(self) -> pulumi.Input[int]:\n return pulumi.get(self, \"policy_id\")",
"def source_snapsh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the policy Type of the schedule policy | def policy_type(self):
return (
list(
SchedulePolicies.policy_types.keys())[
list(
SchedulePolicies.policy_types.values()).index(self._task_json['policyType'])]) | [
"def policy_type(self):\n return self._policy_type",
"def type(self) -> Optional[pulumi.Input['PlacementPolicyType']]:\n return pulumi.get(self, \"type\")",
"def schedule_type(self):\n return self._schedule_type",
"def get_resource_type(policy):\n if policy[\"policyType\"] != 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the properties of this Schedule Policy. | def _get_schedule_policy_properties(self):
flag, response = self._commcell_object._cvpysdk_object.make_request(
'GET', self._SCHEDULE_POLICY)
if flag:
if response.json() and 'taskInfo' in response.json():
_task_info = response.json()['taskInfo']
... | [
"def all_schedule_policies(self):\n return self._policies",
"def refresh(self):\n self._get_schedule_policy_properties()",
"def properties(self) -> pulumi.Output['outputs.RegistrationAssignmentPropertiesResponse']:\n return pulumi.get(self, \"properties\")",
"def properties(self) -> Optio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the schedule pattern for the provided schedule id (internal function) | def _update_pattern(self, schedule_id, pattern_dict):
existing_pattern = {}
for subtask in self._subtasks:
if subtask["subTask"]["subTaskId"] == schedule_id:
if 'pattern' in subtask:
existing_pattern = subtask['pattern']
if 'options' in... | [
"def schedule_id(self, schedule_id):\n\n self._schedule_id = schedule_id",
"def modify_schedule(self, schedule_json, schedule_id=None, schedule_name=None):\n sub_task = self.get_schedule(schedule_id, schedule_name)\n if not sub_task:\n raise SDKException('Schedules', '105')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the option for the provided schedule id (internal) | def _update_option(self, schedule_id, options):
option_allowed = ScheduleOptions.policy_to_options_map[self.policy_type]
for subtask in self._subtasks:
if subtask["subTask"]["subTaskId"] == schedule_id:
if 'options' in subtask:
existing_options = self.get... | [
"async def set(\n ctx_data: Dict[str, Any],\n *,\n id: int,\n websession: aiohttp.ClientSession,\n **kwargs: Any,\n) -> None:\n vehicle, schedules, schedule = await _get_schedule(\n websession=websession, ctx_data=ctx_data, id=id\n )\n\n update_settings(schedule, **kwargs)\n\n writ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the subtask dict for the provided schedule id or name | def get_schedule(self, schedule_id=None, schedule_name=None):
if not schedule_name and not schedule_id:
raise SDKException(
'Schedules',
'102',
'Either Schedule Name or Schedule Id is needed')
if schedule_name and not isinstance(schedule_name,... | [
"def get_schedule(self, name):\n return self.__schedules.get(name, None)",
"def _get_task(self, task_id: str) -> Mapping[str, Any]:\n return self.__get_one_by_id(\"tasks\", \"task_id\", task_id)",
"def schedule_json(policy_type, schedule_dict):\n schedule_options = ScheduleOptions(ScheduleO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a new schedule to the schedule policy | def add_schedule(self, schedule_dict):
sub_task = SchedulePolicies.schedule_json(self.policy_type, schedule_dict)
sub_task["subTaskOperation"] = 2
self._subtasks.append(sub_task)
self._modify_schedule_policy_properties() | [
"def addSchedule(self, schedule):\n\t\tassert isinstance(schedule, Schedule)\n\t\tself.schedules.append(schedule)\n\t\tself.sorted = False",
"async def add_schedule(\n self, schedule: Schedule, conflict_policy: ConflictPolicy\n ) -> None:",
"def add(self, schedule):\n try:\n if sched... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modifies the schedule with the given schedule json inputs for the given schedule id or name | def modify_schedule(self, schedule_json, schedule_id=None, schedule_name=None):
sub_task = self.get_schedule(schedule_id, schedule_name)
if not sub_task:
raise SDKException('Schedules', '105')
if 'pattern' in schedule_json:
self._update_pattern(sub_task["subTask"]["subTas... | [
"def update_schedule(schedule_name):\n data = flask.request.data\n\n try:\n new_schedule = json.loads(data)\n except json.decoder.JSONDecodeError as e:\n return 'Could not parse request', 400\n\n if not 'commands' in new_schedule:\n return 'Expecting sche... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the appgroups for the provided schedule policy | def update_app_groups(self, app_groups, operation_type):
for app_group in app_groups:
app_group["flags"] = {
operation_type: True
}
self._app_groups = app_groups
self._modify_schedule_policy_properties() | [
"def process_update_application_policy_group(self, session, data, result):\n pass",
"def _modify_schedule_policy_properties(self):\n request_json = {\n 'taskInfo':\n {\n 'taskOperation': 1,\n 'associations': self._associations,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modifies the task properties of the schedule policy | def _modify_schedule_policy_properties(self):
request_json = {
'taskInfo':
{
'taskOperation': 1,
'associations': self._associations,
'task': self._task_json,
"appGroup":
{
... | [
"def _get_schedule_policy_properties(self):\n flag, response = self._commcell_object._cvpysdk_object.make_request(\n 'GET', self._SCHEDULE_POLICY)\n\n if flag:\n if response.json() and 'taskInfo' in response.json():\n _task_info = response.json()['taskInfo']\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enable a schedule policy. | def enable(self):
enable_request = self._commcell_object._services['ENABLE_SCHEDULE']
request_text = "taskId={0}".format(self.schedule_policy_id)
flag, response = self._commcell_object._cvpysdk_object.make_request(
'POST', enable_request, request_text)
if flag:
... | [
"def enable_policy(self, enable_policy):\n self._enable_policy = enable_policy",
"def enable_schedules(cls, *schedules):\n return cls._action_on_schedules(\"Enable the selected Schedules\", schedules)",
"def schedule(self, schedule):\n\n self._schedule = schedule",
"def cpu_rule_enable(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable a Schedule Policy. | def disable(self):
disable_request = self._commcell_object._services['DISABLE_SCHEDULE']
request_text = "taskId={0}".format(self.schedule_policy_id)
flag, response = self._commcell_object._cvpysdk_object.make_request(
'POST', disable_request, request_text)
if flag:
... | [
"def disable_schedules(cls, *schedules):\n return cls._action_on_schedules(\"Disable the selected Schedules\", schedules)",
"def disable(self, name: str):\n self._get_backend().disable_alarm(name)",
"def disable_control_policy(self) -> resource_manager_20200331_models.DisableControlPolicyResponse:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refresh the properties of the Schedule Policy. | def refresh(self):
self._get_schedule_policy_properties() | [
"def _modify_schedule_policy_properties(self):\n request_json = {\n 'taskInfo':\n {\n 'taskOperation': 1,\n 'associations': self._associations,\n 'task': self._task_json,\n \"appGroup\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test particles analysis functions. | def test_particles(snaptype):
filename = DIR / snaptype.filename
snap = plonk.load_snap(filename)
snap.set_molecular_weight(2.381)
_test_particles(snap=snap, ignore=False)
_test_particles(snap=snap, ignore=True)
snap.close_file() | [
"def test_particle_selection():\n read.ParticleData(path_to_data, classes=[\"tracer\"])\n read.ParticleData(path_to_data, classes=[\"tracer_noquantities\"])",
"def test_visualize():\n # Instantiate three particles for testing\n particles = [Particle(0.3, 0.5, 1), \n Particle(0.0, -0.5, -1)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test discs analysis functions. | def test_discs(snaptype):
filename = DIR / snaptype.filename
snap = plonk.load_snap(filename)
if snap.num_sinks > 0:
snap.set_central_body(0)
discs.unit_normal(snap=snap)
discs.rotate_edge_on(snap=snap)
discs.rotate_face_on(snap=snap)
discs.position_angle(snap=snap)
discs.incl... | [
"def _test():\n if sys.argv[1:]:\n if sys.argv[2:]:\n sys.stderr.write(\"usage: python dis.py [-|file]\\n\")\n sys.exit(2)\n fn = sys.argv[1]\n if not fn or fn == \"-\":\n fn = None\n else:\n fn = None\n if fn is None:\n f = sys.stdin\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper usable with `ENMLToHTML` `media_filter` parameter to filterout resources that are not images so that output HTML won't contain such invalid element | def images_media_filter(hash_str, mime_type):
return mime_type in MIME_TO_EXTESION_MAPPING | [
"def filterImages(files, cfg):\r\n regex = \"\\.(\" + \"|\".join(cfg.image_formats) + \")$\"\r\n #filter(lambda s: re.match(regex, s), files)\r\n return [s for s in files if re.findall(regex, s)]",
"def filter_images(self):\n filter_ = list()\n\n if self.regex:\n filter_ += self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a user and a game, get previous game for user | def get_previous_game(session, user, game):
previous_game = session.query(Game).filter(
Game.deleted_at.is_(None),
sqla.or_(
Game.winner_id == user.id,
Game.loser_id == user.id
),
Game.id < game.id
).order_by(Game.id.desc()).first()
return previous_ga... | [
"def get_previous_game(team_id: int) -> dict:\n\n logging.info(\"Checking the schedule API endpoint for the previous game.\")\n url = f\"teams/{team_id}?expand=team.schedule.previous\"\n\n response = api.nhl_api(url)\n if not response:\n return None\n\n prev_game_json = response.json()\n pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse serialized example and return feature_dict and label. | def _parse(serialized_example):
feature_map = {
'dayofweek': tf.io.FixedLenFeature([], tf.int64),
'dropofflat': tf.io.FixedLenFeature([], tf.float32),
'dropofflon': tf.io.FixedLenFeature([], tf.float32),
'fare_amount': tf.io.FixedLenFeature([], tf.float32),
... | [
"def example_parser(serialized_example):\n features = tf.parse_single_example(\n serialized_example,\n features={\n 'bytesImg': tf.FixedLenFeature([], tf.string),\n 'label': tf.FixedLenFeature([], tf.int64),\n })\n image = tf.decode_raw(features['bytesImg'], tf.uint8... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add engineered features to features dict. | def add_engineered(features):
features["londiff"] = features["dropofflon"] - features["pickuplon"]
features["latdiff"] = features["dropofflat"] - features["pickuplat"]
features["euclidean"] = tf.math.sqrt(
features["londiff"]**2 + features["latdiff"]**2)
return features | [
"def add_features(self, **features):\n for fname, fvalue in features.items():\n setattr(self, fname, fvalue)\n self.features.add(fname)",
"def add_feature(self, existing_features, new_features, feature_names):\n\n\t\tfor k, v in new_features.items():\n\t\t\t# k is the node id and v is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build tf.estimator.DNNRegressor and call train_and_evaluate loop. | def train_and_evaluate(args):
feat_cols = [
tf.feature_column.numeric_column('dayofweek'),
tf.feature_column.numeric_column('hourofday'),
tf.feature_column.numeric_column('pickuplat'),
tf.feature_column.numeric_column('pickuplon'),
tf.feature_column.numeric_column('dropofflat... | [
"def my_dnn_regression_fn(features, labels, mode, params):\n\n # Extract the input into a dense layer, according to the feature_columns.\n top = tf.feature_column.input_layer(features, params[\"feature_columns\"])\n\n # Iterate over the \"hidden_units\" list of layer sizes, default is [20].\n for units in param... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download the url to dest if necessary, optionally checking file integrity. | def maybe_download(url, dest):
if not os.path.exists(dest):
logger.info('Downloading %s to %s', url, dest)
download(url, dest) | [
"def maybe_download_and_extract(data_url, dest_dir, file_path):\r\n \r\n # Check if the file already exists.\r\n # If it exists then we assume it has also been extracted,\r\n # otherwise we need to download and extract it now.\r\n if not os.path.exists(dest_dir):\r\n os.makedirs(dest_dir)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns None unless a UID was successfully parsed. Otherwise returns a positive integer. | def ParseSyntaxForUID(candidate):
if candidate.lower().startswith('uid=') and candidate.count('=') == 1:
(_, rhs) = candidate.split('=')
try:
an_integer = int(rhs, 10)
if an_integer <= 0:
raise ValueError('reraise')
return an_integer
except ValueError:
raise UIDSyntaxError(... | [
"def parse_uid(buf):\n m = re.search(\"UID (\\d+)\", buf)\n return int(m.group(1))",
"def getUIDValidity(self):\n return 42",
"def read_uid(uid_path):\n fh = open(uid_path, \"r\")\n for line in fh:\n bline = line.strip()\n if bline.isdigit():\n fh.close()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a string, returns a vector of strings, argv. Don't set posix False. Quote characters are removed by POSIX (see unittest), and we therefore do not play well with nonPOSIX. | def SplitCommandLineIntoArgv(space_delimited_argv, posix=True):
try:
return map(lambda s: s.decode('utf-8'),
shlex.split(space_delimited_argv.encode('utf-8'),
comments=FLAGS.pyatdl_allow_command_line_comments,
posix=posix))
except ValueError a... | [
"def decode_sys_argv():\n if six.PY2:\n encoding = sys.getfilesystemencoding()\n return [arg.decode(encoding) for arg in sys.argv]\n return sys.argv",
"def parseCommand(string):\n data = shlex.split(string)\n return (\"\", []) if len(data) == 0 else (data[0].lower(), data[1:] if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the thrust coefficient as a function of induction factor 'a' 'glauert' defines if the Glauert correction for heavily loaded rotors should be used; default value is false | def CTfunction(a, glauert = False):
CT = np.zeros(np.shape(a))
CT = 4*a*(1-a)
if glauert:
CT1=1.816;
a1=1-np.sqrt(CT1)/2
if a>a1:
CT = CT1-4*(np.sqrt(CT1)-1)*(1-a)
return CT | [
"def accelThrust(torque):\n return (torque * gearRatio * driveEfficiency) / tireRadius",
"def time_familiarity_check(distance, wordlength, frequency, predictability, eccentricity, alpha1=104, alpha2=3.4, alpha3=39):\n tL1 = alpha1 - alpha2*math.log(frequency) - alpha3*predictability\n tL1 = tL1 * pow (ec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calcualte steh combined tip and root Prandtl correction at agiven radial position 'r_R' (nondimensioned by rotor radius), given a root and tip radius (also nondimensioned), a tip speed ratio TSR, the number lf blades NBlades and the axial induction factor | def PrandtlTipRootCorrection(r_R, rootradius_R, tipradius_R, TSR, NBlades, axial_induction):
temp1 = -NBlades/2*(tipradius_R-r_R)/r_R*np.sqrt( 1+ ((TSR*r_R)**2)/((1+axial_induction)**2))
Ftip = np.array(2/np.pi*np.arccos(np.exp(temp1)))
Ftip[np.isnan(Ftip)] = 0
temp1 = NBlades/2*(rootradius_R-r_R)/r... | [
"def GE_41RT_newton(xy_in, params, invert=False):\n\n if params[0] == 0 and params[1] == 0 and params[2] == 0:\n return xy_in\n else:\n # canonical max radius based on perfectly centered beam\n rhoMax = 204.8\n\n polar = to_polar(np.copy(xy_in, order='F'))\n npts = len(polar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the keys from the configuration file of the blog. | def get_keys():
config = ConfigParser.ConfigParser()
config.read('config.ini')
cfg = {}
cfg['access_token'] = config.get('Twitter', 'AccessToken')
cfg['access_token_secret'] = config.get('Twitter', 'AccessTokenSecret')
cfg['consumer_key'] = config.get('Twitter', 'ConsumerKey')
cfg['consumer_... | [
"def read_keys(self):\n with open(\"flickr_api.yaml\") as f:\n api = yaml.load(f)\n return (api[\"key\"], api[\"secret\"])",
"def keys(self):\n return self.config.keys()",
"def config_keys(self):\n return self._keys",
"def keys(self):\n return self.configdict.keys... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Posts a thread of tweets based on the text of a post. | def send_tweet(data):
# Fill in the values noted in previous step here
cfg = get_keys() # grab keys
api = get_api(cfg) # setup API
in_reply_to = None
twitter_url = 'https://twitter.com'
if data['in_reply_to'] is not None: # if post is reply ...
for reply i... | [
"async def postthread(self,cxt, count=10):\r\n thr = chanUtils.getthread()\r\n for p in range(1, count + 1):\r\n post = thr.posts[p]\r\n await self.bot.send_message(cxt.message.channel, embed=chanUtils.posttoembed(post))",
"def post_tweet(status_text, twitter_api):\n twitter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn off the robot. | def turn_off(self):
self.robot.stop_simulation() | [
"def turn_off(self, **kwargs):\n set_sonoff_state(self._host, \"off\")\n self._state = False",
"def turn_off(self, **kwargs):\n self.smartplug.turn_off()",
"def turn_off(self):\n GPIO.output(self.gpio, False) # turn off light",
"def set_mode_off(self):\n self.comman... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start the navigation thread, that will guide the robot towards the goal set using the goto function. | def start_navigation(self):
# starting the navigation thread if it is not running
if not self.navigation_status:
print("Starting navigation thread")
try:
self.navigation_stop = False
navigation_thread = thread.Thread(target=self.navigation)
... | [
"def nav(self):\n print(\"-----------! NAVIGATION ACTIVATED !------------\\n\")\n print(\"-------- [ Press CTRL + C to stop me ] --------\\n\")\n print(\"-----------! NAVIGATION ACTIVATED !------------\\n\")\n #print(\"Wait a second. \\nI can't navigate the maze at all. Please give my pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop the navigation thread. | def stop_navigation(self):
print("Stopping the navigation thread")
self.navigation_stop = True
self.locomotion_stop = True | [
"def stop(self):\n\n self.is_killswitch_on = False\n self.navigation.stop()",
"def stop(self):\n self._Thread__stop()",
"def stop_thread(self):\r\n self.thread.active = False\r\n self.thread.join()",
"def stop_thread(self):",
"def stop(self):\n self.running = False\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Openloop navigation towards a selected goal. | def goto(self, goal: Pose):
self.navigation_lock.acquire()
self.navigation_goal = goal
self.navigation_lock.release() | [
"def navigate_to():\n return Navi.navigate_to(\"Bill Of Lading\")",
"def navigate_to(self, route):\n pass",
"def navigate_to(self):\n #self._kernel.navigate_to(route)\n pass",
"def choose_next_link(self):",
"def goto(self, item):\n command = 'goto ' + str(item)\n self.run_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Drops the current goal and (almost) stops the movement. | def stop(self):
self.move(None) | [
"def stop(self):\n self.__pos = self.__update()\n self.__motion = None",
"def stop(self):\n self.move(0, 0)",
"def cancel_goal(self):\n self.jgp.cancel_goal()",
"def stop(self):\n self.direction_x = 0\n self.direction_y = 0",
"def drop(self):\n if (pyxel.fram... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs in a trainer using their email address | def post(self):
try:
email = request.json["email"]
return TrainerService.login(email).json()
except ResourceNotFound as r:
return r.message, 404 | [
"def login_bot(self):\n pass",
"def login_on_activation(sender, user, request, **kwargs):\n user.backend = 'storybase_user.auth.backends.EmailModelBackend'\n login(request, user)",
"def login(self):\n self.client.login(username='john', password='john')",
"def email_login_url(self, url):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve trainer information using their ID | def get(self, trainer_id):
try:
return TrainerService.get_trainer_by_id(int(trainer_id)).json()
except ValueError:
return INVALID_ID_ERROR, 400 # Bad Request
except ResourceNotFound as r:
return r.message, 404 | [
"async def trainer(ctx, trainer=None):\n # gets the total number of unique pokemon caught\n if trainer:\n trainer = str(ctx.message.mentions[0])\n else:\n trainer = ctx.message.author\n return await get_trainer_info(ctx, trainer)",
"def get_trainer_by_id(self, id):\n # Validates i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves all trainers associated in the batch with given ID | def get(self, batch_id):
try:
trainers = TrainerService.get_trainers_in_batch(int(batch_id))
except ValueError:
return INVALID_ID_ERROR, 400 # Bad Request
except ResourceNotFound as r:
return r.message, 404
trainers_as_json... | [
"def load_friend_training_set(api, id, num = 5):\n result = []\n for status in tweepy.Cursor(api.user_timeline,id).items(num):\n result.append(status.text)\n return result",
"def trainers ( self ) :\n return self.__trainers",
"def test_get_training_dataset_with_id(self):\n pass",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the number of active years for the trainer with ID in argument | def get(self):
trainer_id = request.args.get("trainerId")
if trainer_id is not None:
try:
return TrainerService.get_years_for_trainer(int(trainer_id))
except ValueError:
return INVALID_ID_ERROR, 400 # Bad Request
... | [
"def get_age_years(self) -> int:\n return self.__age_years",
"def available_years(self):\n years = [int(x) for x in self.client.nlst(self.root)]\n return years",
"def get_year_count(self):\r\n ward_group = self.current_table.groupby(['Year'])\r\n self.year_count = ward_group['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a cache HTTP adapter that is based on an HAR file. | def __init__(
self,
cache_path: Union[str, os.PathLike],
mode: str = 'r',
is_active: bool = True,
is_offline: bool = False,
is_passive: bool = True,
delete_after_hit: bool = False,
match_headers: bool = True,
mat... | [
"def generate_har(url):\n # TODO: Do validation checks on the URL.\n # TODO: Pass options: delay, screen size, user-agent override, etc.\n return fetch('http://localhost:3000/demo.har', data={url: url})",
"def create_cache(filename):\n cache = {}\n filePath = \"/u/fares/public_html/netflix-caches/\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads graph metadata GRAPH_DIR/FILENAME.GRAPH_EXT Draws a graph image IMG_DIR/FILENAME.IMG_EXT | def draw_graph(
filename: str,
graph_ext: str = DOT_EXT,
graph_dir: str = DOT_DIR,
img_dir: str = IMG_DIR,
img_ext: str = SVG_EXT
) -> None:
filepath = "{}/{}".format(graph_dir, filename)
graph = G(filepath)
graph.layout()
img_filename = filename.replace(g... | [
"def drawGraph(G, filename, detail):\n if (detail == True):\n pos = nx.spring_layout(G)\n nx.draw_networkx(G, pos)\n labels = nx.get_edge_attributes(G, 'weight')\n nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)\n plt.savefig(\"visualizations/\" + filename + \".jpg\")\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loops through a directory Draws graphs from all the graph metadata files | def loop_dir(dir_name: str, graph_ext: str) -> None:
directory = fsencode(dir_name)
for file in listdir(directory):
filename = fsdecode(file)
if filename.endswith(graph_ext):
draw_graph(filename) | [
"def graphs_directory():\n return os.path.join(output_directory(), \"graphs\")",
"def plot_all(motion,name_dir,save_fig,show,scatter,norm,extension):\n stg = motion + '.' + extension\n list_dir = os.listdir(name_dir)\n l = []\n for name in list_dir:\n if stg in name:\n l += [name]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To play the game, we first select the secret word for the player to guess and then play the game using that secret word. | def main():
secret_word = get_word()
print(secret_word)
play_game(secret_word) | [
"def main():\n secret_word = get_word()\n play_game(secret_word)",
"def play_turn(self):\n \n print('\\nOptions:')\n print('- You can save your game any time by typing \"save\" instead of a letter.')\n print('- You can quit any time by typing \"quit\" instead of a letter.\\n')\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all valid reset days | def get_reset_days(cashflows):
reset_dates = [cash_flow.Resets()[-1].Day()
for cash_flow in cashflows
if cash_flow.CashFlowType() == 'Float Rate']
return reset_dates | [
"def get_days(self):\n return list(self.iter_days())",
"def getAllDays(self):\n start = str(self.current[0:10])\n end = str(self.dueDate[0:10])\n daysRange = pd.date_range(start = start, end = end).tolist()\n daysRange = daysRange[1:len(daysRange)-1]\n days = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a brick path, split and return the components Returns a dict with the host component, the rest of the path, the zfs pool the ondisk storage format assumes that the dataset name is of the form // where ondisk_storage_format is either normal or compressed or deduplicated brick The brick path | def get_components(brick):
d = None
try:
if not brick:
raise Exception('Brick path not provided')
l = brick.split(':')
if not l or len(l) == 1:
raise Exception('Invalid brick path : %s' % brick)
d = {}
d["host"] = l[0]
d["path"] = l[1]
... | [
"def zfs_pool_name(self):\n return self.host.datasets.root.name.split(\"/\", maxsplit=1)[0]",
"def splitpath(self):\n \n pass",
"def _split(crumb_path: str) -> Tuple[str, str]:\n crumb_path = _get_path(crumb_path)\n\n if not has_crumbs(crumb_path):\n return crumb_path, ''\n\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the basic information about all the volumes except the integralview admin volume The return value is a list of dicts where each dict has all the info of one volume | def get_basic_volume_info_all():
vl = None
try:
d, err = xml_parse.run_gluster_command(
'/usr/sbin/gluster volume info all --xml')
if err:
raise Exception(err)
root = d["root"]
# Get the admin vol name so it can be excluded from the list
admin_vo... | [
"def volume_details(tenant_id, auth_token, volume_id):\n content = common_utils.do_request(\n tenant_id, auth_token, method=\"GET\",\n body='', service=\"volumes\",\n path=\"volumes/%s\" % (volume_id))\n return content",
"def show_asm_volumes(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the volume process status for a particular volume The return value is a dict which has a flag to say if all the processes are ok or not and for each brick, it has the appropriate process status vol_name The name of the volume for which the status details is required. vol_info_dict The dict returned from get_vol... | def get_volume_process_status(vol_name, vol_info_dict=None, vol_status_dict=None):
return_dict = {}
try:
if not vol_info_dict:
vol_info_dict, err = get_basic_volume_info(vol_name)
if err:
raise Exception(err)
if not vol_status_dict:
vol_statu... | [
"def get_complete_volume_info(vol_name, vol_info_dict=None):\n return_dict = {}\n try:\n if not vol_info_dict:\n vol_info_dict, err = get_basic_volume_info(vol_name)\n if err:\n raise Exception(err)\n\n return_dict = vol_info_dict\n\n vol_status_dict =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the volume quota information for a particular volume The return value is a dict which has the quota vol_name The name of the volume for which the status details is required. vol_info_dict The dict returned from get_volume_info for that volume we can get it if None | def get_volume_quota(vol_name, vol_info_dict=None):
return_dict = {}
try:
if not vol_info_dict:
vol_info_dict, err = get_basic_volume_info(vol_name)
if err:
raise Exception(err)
no_quotas_set = False
if "options" in vol_info_dict:
for o... | [
"def get_complete_volume_info(vol_name, vol_info_dict=None):\n return_dict = {}\n try:\n if not vol_info_dict:\n vol_info_dict, err = get_basic_volume_info(vol_name)\n if err:\n raise Exception(err)\n\n return_dict = vol_info_dict\n\n vol_status_dict =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all the information and status about a specific volume The return value is a dict which has all the info and status of the volume. This should be called carefully as it results in multiple underlying gluster calls. vol_name The name of the volume for which info is needed. vol_info_dict The basic volume info dic... | def get_complete_volume_info(vol_name, vol_info_dict=None):
return_dict = {}
try:
if not vol_info_dict:
vol_info_dict, err = get_basic_volume_info(vol_name)
if err:
raise Exception(err)
return_dict = vol_info_dict
vol_status_dict = {}
if ... | [
"def get_volume_process_status(vol_name, vol_info_dict=None, vol_status_dict=None):\n return_dict = {}\n try:\n\n if not vol_info_dict:\n vol_info_dict, err = get_basic_volume_info(vol_name)\n if err:\n raise Exception(err)\n\n if not vol_status_dict:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a volume info list and a volume name, determine if a volume of that name already exists. Returns True if it exists and False if not or if an error occurred vil A list of dicts of currently existing volumes if already generated. If None, then we generate the list here. vol_name The name of the volume that we need ... | def volume_exists(vil, vol_name):
exists = False
try:
if not vil:
vil, err = get_basic_volume_info_all()
if err:
raise Exception(err)
if vil:
for v in vil:
if v["name"] == vol_name:
exists = True
except ... | [
"def validate_storage_volume_existing_by_name(volume_name):\n FusionUIBase.navigate_to_section(SectionType.VOLUMES)\n if CommonOperationVolumes.verify_volume_exist(volume_name, timeout=5, fail_if_false=False):\n logger.info(\"Validating the Storage volume: '%s' is existing successfully.\" % volume_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a volume info dict, return all the hostnames on which the bricks reside. Returns a list of the hostnames on which the volume bricks reside. vol_info_dict The volume info dict of required volume. | def get_brick_hostname_list(vol_info_dict):
l = []
try:
if not vol_info_dict:
raise Exception('Required parameter not passed')
if 'bricks' in vol_info_dict:
for brick in vol_info_dict["bricks"]:
for ib in brick:
h, b = ib.split(':')
... | [
"def get_volumes_on_node(hostname, vil):\n # Returns a list of volume names on a node for display\n\n vol_list = []\n try:\n if not hostname:\n raise Exception('No GRIDCell name passed')\n\n if not vil:\n vil, err = get_basic_volume_info_all()\n if err:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of volume names on a node for display Returns a list of volume dicts of volumes that have a brick on that hostname. vil A list of vol_info_dicts of currently existing volumes if already generated. If None, then we generate the list here. hostname The hostname to check on.. | def get_volumes_on_node(hostname, vil):
# Returns a list of volume names on a node for display
vol_list = []
try:
if not hostname:
raise Exception('No GRIDCell name passed')
if not vil:
vil, err = get_basic_volume_info_all()
if err:
raise... | [
"def get_brick_hostname_list(vol_info_dict):\n\n l = []\n try:\n if not vol_info_dict:\n raise Exception('Required parameter not passed')\n if 'bricks' in vol_info_dict:\n for brick in vol_info_dict[\"bricks\"]:\n for ib in brick:\n h, b = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all the created snapshots for the specified volume name. Returns a list of all the snapshots if any. vol_name The name of the volume that we need to check on. | def get_snapshots(vol_name):
l = None
try:
cmd = 'gluster snapshot info volume %s --xml' % vol_name
d, err = xml_parse.run_gluster_command(cmd)
if err:
raise Exception(err)
if d:
if d["op_status"]["op_ret"] == 0:
l, err = xml_parse.get_sn... | [
"def get_volume_snapshots(self, volume):\n LOG.debug('get_volume_snapshot starts')\n pool_name = self.configuration.rbd_pool\n volume_name = 'volume-%s' % encodeutils.safe_encode(volume[\"id\"])\n snaps_on_vol = self._get_volume_snapshots(pool_name, volume_name)\n snapshots = list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a dict with the volume name and all the options that need to be set on that volume, this function will do the needful.. Returns a list of results from each option setting operation. cd A dict with the volume name and all the options that needs to be set. | def set_volume_options(cd):
try:
vol_name = cd["vol_name"]
auth_allow = cd["auth_allow"]
auth_reject = cd["auth_reject"]
if "nfs_disable" in cd:
nfs_disable = cd["nfs_disable"]
else:
nfs_disable = False
if "enable_worm" in cd:
enab... | [
"def test_volumes_complex(self):\n with open(\".scuba.yml\", \"w\") as f:\n f.write(\n r\"\"\"\n image: na\n volumes:\n /foo: /host/foo\n /bar:\n hostpath: /host/bar\n /snap:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a volume name, an option name and an option value, it will do the actual work of setting that option. Returns the gluster return codes after executing that operation. vol_name The name of the volume that we need to operate on. option The option that needs to be set. value The value for the selected option that ne... | def _set_volume_option(vol_name, option, value):
d = None
try:
cmd = 'gluster volume set %s %s %s --xml' % (vol_name, option, value)
d, err = xml_parse.run_gluster_command(cmd)
if err:
raise Exception(err)
except Exception, e:
return None, 'Error setting specific ... | [
"def setOption(self, name, value):\n petsc.optionsSetValue(name, value)\n return",
"def set_volume_options(cd):\n\n try:\n vol_name = cd[\"vol_name\"]\n auth_allow = cd[\"auth_allow\"]\n auth_reject = cd[\"auth_reject\"]\n if \"nfs_disable\" in cd:\n nfs_disable = c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine on which nodes and bricks the volume expansion/creation should happen onto and create the appropriate command to make it happen. Returns a dict with the command, the node list, the dataset list and a count that will be used by the caller to create the appropriate datasets, etc.. cmd The initial part of the co... | def build_create_or_expand_volume_command(cmd, si, anl, vol_type, ondisk_storage, repl_count, vol_name):
return_dict = {}
try:
node_list = []
if (not si) or (not vol_type) or (not ondisk_storage) or (not vol_name):
raise Exception('Required parameter not passed')
if (vol_t... | [
"def build_create_volume_command(vol_name, vol_type, ondisk_storage, repl_count, transport, si):\n\n return_dict = None\n try:\n # Now build the command based on parameters provided\n cmd = 'gluster volume create %s ' % vol_name\n if 'replicate' in vol_type.lower():\n cmd = cmd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine which nodes can be used to expand or create a volume based on the system state. Returns a dict with the the allowable node list vol_name If we are checking for an existing volume, then we need its name si The system info dict that has all the information about the current state of the grid. | def _get_allowable_node_list(si, vol_name=None):
anl = []
try:
for hostname in si.keys():
# Volumes can only be placed on nodes that are ok and are part of
# the storage pool
if si[hostname]["node_status"] != 0 or si[hostname]["in_cluster"] == False:
c... | [
"def get_volume_process_status(vol_name, vol_info_dict=None, vol_status_dict=None):\n return_dict = {}\n try:\n\n if not vol_info_dict:\n vol_info_dict, err = get_basic_volume_info(vol_name)\n if err:\n raise Exception(err)\n\n if not vol_status_dict:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a command to expand an existing volume based on its type and the current system state. Uses build_create_or_expand_volume_command to do most of the work. Returns a dict with the command, the node list, the dataset list and a count that will be used by the caller to create the appropriate datasets, etc.. vol_info_... | def build_expand_volume_command(vol_info_dict, si):
return_dict = None
try:
# First get all the node/disk combinations where the volume is not
# present
anl = []
num_nodes = 0
ondisk_storage = "normal"
if "compressed" in vol_info_dict['bricks'][0]:
o... | [
"def build_create_or_expand_volume_command(cmd, si, anl, vol_type, ondisk_storage, repl_count, vol_name):\n\n return_dict = {}\n try:\n node_list = []\n\n if (not si) or (not vol_type) or (not ondisk_storage) or (not vol_name):\n raise Exception('Required parameter not passed')\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |