query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Context manager for isolating `nodes` in `panel` | def _isolated_nodes(nodes, panel):
from maya import cmds
if nodes is not None:
cmds.isolateSelect(panel, state=True)
for obj in nodes:
cmds.isolateSelect(panel, addDagObject=obj)
yield | [
"def draw_nodes(self):\n pass",
"def folded(panel):",
"def draw_nodes(self, *args, **kwargs):\n return self.assembly_plotter.draw_nodes(*args, **kwargs)",
"def __panel__(self):\n return self._panel",
"def test_several_nodes(self):\n with Nodes()as n:\n n.nodes_discover... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies the image at path to the system's global clipboard. | def _image_to_clipboard(path):
import PySide.QtGui
image = PySide.QtGui.QImage(path)
clipboard = PySide.QtGui.QApplication.clipboard()
clipboard.setImage(image, mode=PySide.QtGui.QClipboard.Clipboard) | [
"def image_to_clipboard(path):\n\n image = QtGui.QImage(path)\n clipboard = QApplication.clipboard()\n clipboard.setImage(image, mode=QtGui.QClipboard.Clipboard)",
"def imageToClipboard(self, imagePath):\n subprocess.Popen([\"xclip\", \"-selection\", \"clipboard\", \"-t\", \"image/png\", \"-i\", i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return available screen size without space occupied by taskbar | def _get_screen_size():
import PySide.QtGui
rect = PySide.QtGui.QDesktopWidget().screenGeometry(-1)
return [rect.width(), rect.height()] | [
"def get_screen_resolution() -> tuple:\n root = tkinter.Tk()\n root.withdraw()\n return root.winfo_screenwidth(), root.winfo_screenheight()",
"def GetScreenSize(self):\n ...",
"def get_screen_size():\n from win32api import GetSystemMetrics\n scr_sz = np.array([GetSystemMetrics(0), GetSyste... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function checks for the channel id of the message and the channel id that we are currently set up with if they do not match, a different server is talking to us and we need to switch ids | def check_server_id(message):
global server_id
if server_id is 0: # the channel_id is not set up at all
server_id = message.channel.id # this is the current server that we're talking to
channel = client.get_channel(server_id) # this is the current channel in that server that we will... | [
"def _check_message_id(self, scm_i):\n log.debug(\" chk msgid(karma) w.: {}\".format(scm_i.get('id')))\n if scm_i.get('id').endswith('@ECsoftware.net'):\n scm_i.add_vote(self.filter_name, 1, 4, None, 'No Message-ID')\n ##print(\"MsgID: {}\".format(scm_i.get('id')))\n return sc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Si viene del form, eliminar los resources de favorite. | def delete(self, request, *args, **kwargs):
favorites = self.get_object()
favorites_list = favorites.anuncios.all()
if favorites_list:
for favorite in favorites_list:
favorites.anuncios.remove(favorite)
msg_success = 'Se han eliminado todos los anuncios de... | [
"def api_remove_favorite(self):\n raise NotImplementedError",
"def del_favorite(self, user, obj):\n content_type = ContentType.objects.get_for_model(type(obj))\n self.get_query_set().filter(user=user, content_type=content_type, object_id=obj.pk).delete()",
"def destroy(self, request, *args,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes data(losses and performance) into a dictionary for the sake of data plotting. | def verbose_data_dict(perf_data, epoch_losses, batch_losses):
data_dict = []
if epoch_losses is not None and len(epoch_losses['actor_mse']) > 0:
data_dict.append({'title': "Actor_MSE_Loss_vs_Epoch", 'data': epoch_losses['actor_mse'],
'y_label': 'Loss' + '( min: ' + str(min(epoc... | [
"def generate_dict(self):\n self._data_dict = {}\n self._data_dict['name'] = self._name\n self._data_dict['color'] = self._color\n self._data_dict['type'] = self.__repr__()\n self._data_dict['points'] = self._points.tolist()\n return self._data_dict",
"def generate_visual... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Left rotates array in place. | def left_rotate(arr):
return arr[1:] + [arr[0]] | [
"def rotate_left(arr, l, r):\n temp = arr[l]\n for i in range(l, r):\n arr[i] = arr[i+1]\n arr[r] = temp",
"def rotate_one_left(a):\n first = a[0]\n for i in range(1, len(a)):\n a[i-1] = a[i]\n a[len(a)-1] = first\n return a",
"def rotLeft(a, d):\n for i in range(d):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rotates array a left d times. | def rotLeft(a, d):
for i in range(d):
arr = left_rotate(arr)
return arr | [
"def left_rotate_s2(arr, d):\n n = len(arr)\n for i in range(d):\n for i in range(n-1):\n arr[i], arr[i + 1] = arr[i + 1], arr[i]",
"def rotLeft(a, d):\n return a[d:]+a[:d]",
"def rot_left_pythonic(a, d):\n n = len(a)\n if (n == d):\n return a\n result = []\n i = d%... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call regionInstances.bulkInsert to create instances | def create_instances_request(nodes, placement_groups=None, exclusive=False):
assert len(nodes) > 0
assert len(nodes) <= BULK_INSERT_LIMIT
# model here indicates any node that can be used to describe the rest
model = next(iter(nodes))
partition = lkp.node_partition(model)
template = lkp.node_temp... | [
"def create_instance_bulk(self, context, tenant_id, neutron_ports, vms,\n port_profiles, sync=False):",
"def call_post_bulk_create(cls, instances, using=None):\n post_bulk_create.send(cls, instances=instances, using=using)",
"def _bulk_insert(self):\n self.stdout.write(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
expand nodes in hostlist to hostnames | def expand_nodelist(nodelist):
if not nodelist:
return []
# TODO use a python library instead?
nodes = run(f"{lkp.scontrol} show hostnames {nodelist}").stdout.splitlines()
return nodes | [
"def _expand_hostlist(nodelist: str) -> List[str]:\n node_list = nodelist.split(\", \")\n\n result_hostlist = []\n for node in node_list:\n nodelist_match = r\"(\\w+-?)\\[((,?[0-9]+-?,?-?){0,})\\](.*)?\"\n if re.search(nodelist_match, node):\n match = re.sea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set nodes down with reason | def down_nodes(nodelist, reason):
if isinstance(nodelist, list):
nodelist = util.to_hostlist(nodelist)
run(f"{lkp.scontrol} update nodename={nodelist} state=down reason='{reason}'") | [
"def report_down(self,node):\n src = node.nodeid\n node.migarate_down()\n #for k,v in node.data_dict.iteritems():\n # dst = self.migarate_begin(src)\n # dst.migarate_node(k,v.size,src)",
"def changes_while_node_down_test(self):\n debug(\"changes_while_node_down_test... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hold job, set comment to reason | def hold_job(job_id, reason):
run(f"{lkp.scontrol} hold jobid={job_id}")
run(f"{lkp.scontrol} update jobid={job_id} comment='{reason}'") | [
"def _PostComment(self):\r\n lock = yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id)\r\n try:\r\n if not (yield self._Check()):\r\n return\r\n self._client.CheckDBNotModified()\r\n yield self._Update()\r\n yield self._Account()\r\n yield Operation.Trigger... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resume exclusive nodes in the node list | def prolog_resume_nodes(job_id, nodelist):
# called from PrologSlurmctld, these nodes are expected to be in the same
# partition and part of the same job
nodes = nodelist
if not isinstance(nodes, list):
nodes = expand_nodelist(nodes)
if len(nodes) == 0:
return
model = next(iter(... | [
"def deactivate_all():\r\n global active_nodes\r\n active_nodes = [False for i in range(n)]",
"def deactivate_all(self):\n\t self.active_nodes = [False for i in range(self.nodes)]",
"def __mark_active(self):\n for node in iterate_active_nodes(self):\n node.active = True",
"def check... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closure function for np.quantile | def quantile_func(q):
def f(x):
return np.quantile(x, q)
return f | [
"def compute_quantile(self, **kwargs):\n x = Dummy('x', integer=True)\n p = Dummy('p', real=True)\n left_bound = self.set.inf\n pdf = self.pdf(x)\n cdf = summation(pdf, (x, left_bound, x), **kwargs)\n set = ((x, p <= cdf), )\n return Lambda(p, Piecewise(*set))",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Observe a set of particles with dim=mc,d and compare the moments to self.truth_particles | def evaluate(self, particles, **kwargs):
truth = self.truth
metrics = self.metrics
moments = self.moments
results = []
# for key in truth:
th_hvi = np.concatenate([particles[key].reshape(particles[key].shape[0], -1) for key in truth], axis=1)
tr = np.concatenate([... | [
"def test_visualize():\n # Instantiate three particles for testing\n particles = [Particle(0.3, 0.5, 1), \n Particle(0.0, -0.5, -1), \n Particle(-0.1, -0.4, 3)]\n simulator = ParticleSimulator(particles)\n visualize(simulator)",
"def test_n_particles():\n for n_particl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the results to a .csv | def log_results(self, path):
pd.DataFrame(self.results).to_csv(path) | [
"def create_csv(self):\n self.csv_path = self.results_directory_path + \"/results.csv\"\n results_file = open(self.csv_path, \"wb\")\n results_writer = csv.writer(results_file)\n # Column headers\n results_writer.writerow(self.results_header)\n for groyne_cell in self.resul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The index_scores, will be used to plot results | def __init__(self, index_scores):
self.index_scores = index_scores | [
"def get_idx_scores_mapping(scores):\n return {i: score for i, score in enumerate(scores)}",
"def disc_index(self, index):\r\n \r\n h_list = []\r\n l_list = []\r\n \r\n q_resps = self.answers[:, index]\r\n q_answered = q_resps[q_resps>=0]\r\n \r\n #having... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Observe a set of scores with dim t,1 | def observe(self, scores, **fields):
[self._scores.append({'value': s, 'index': i, **fields}) for s, i in zip(scores, self.index_scores)]
for s in self.statistics:
v = self.statistics[s](scores)
self._results.append({'statistics': s, 'value': v, **fields}) | [
"def score_metrics(predicted_scores, scores):\n tf.summary.histogram('predicted_scores', predicted_scores)",
"def print_scores(X,y,model):",
"def assign_score(self, trajs):\n traj_scores = []\n for traj in trajs:\n obs = torch.stack(traj['states']).squeeze(dim=1) if isinstance(traj['st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a pandas with the results with tag methods in methods | def get_results(self, methods: list = None):
df = pd.DataFrame(self._results)
if (methods is not None) & ('method' in df.columns):
df = df.loc[[x in methods for x in df.method.values]]
return df | [
"def register_DataFrame_method(method):\n def inner(*args, **kwargs):\n\n\n class AccessorMethod(object):\n\n\n def __init__(self, pandas_obj):\n self._obj = pandas_obj\n\n @wraps(method)\n def __call__(self, *args, **kwargs):\n return method(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all the scores as a pandas object | def get_scores(self):
return pd.DataFrame(self._scores) | [
"def get_scores(self, save_path=None):\n summary_dict = {}\n summary_list = [[], []] # for csv\n header = []\n for k, result_list in self.multi_scores.items():\n mean = np.mean(result_list)\n std = np.std(result_list)\n summary_dict[k + '_mean'] = mean\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create row from node, style and extra prefix items. | def from_node(cls, node: NodeOrLeaf, style: "Style", extra=()):
if not extra:
return Row("", "", node)
items = [(style.vertical if cont else style.empty) for cont in extra]
indent = "".join(items[:-1])
branch = style.horizontal if extra[-1] else style.end
pre = indent... | [
"def iter_rows(node, style, extra=()):\n yield Row.from_node(node, style, extra)\n children = node.children\n if children:\n last_idx = len(children) - 1\n for idx, child in enumerate(children):\n yield from iter_rows(child, style, extra + (idx != last_idx,))",
"def _create_table... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create rows from children of given node. | def iter_rows(node, style, extra=()):
yield Row.from_node(node, style, extra)
children = node.children
if children:
last_idx = len(children) - 1
for idx, child in enumerate(children):
yield from iter_rows(child, style, extra + (idx != last_idx,)) | [
"def create_children(self, df, levels, depths):\n children = self.identify_children(df, levels, depths)\n\n for id_, row in children.iterrows():\n self.children.append(Tree(root=row,\n name_col=self.name_col,\n id_col... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Property for the initital velocity | def initial_velocity(self) -> float:
return self._initial_velocity | [
"def default_velocity(self) -> int:\r\n ...",
"def velocity(self):\n return self._velocity",
"def get_velocity(self):\r\n return self._v",
"def velocity(self):\n return self._velocity",
"def get_velocity(self):\n return self.velocity",
"def velocity(self):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Property for the last index that was calculated from previous data | def last_index(self) -> int:
return self._last_index | [
"def _last_index(self):\n return len(self.items) - 1",
"def get_last_index(self):\n return len(self.chain) - 1",
"def getLastPlotIndexKey(self):\n return self._lineIndex-1",
"def last_sequence_ind(self,):\n return self.last_sequence_ind_",
"def getLast(self):\r\n return se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Property for the constant error in accelerometer data | def acceleration_error_constant(self) -> float:
return self._acceleration_error_constant | [
"def ultrasonic_sensor_error(raw_sensor_value):\n\treturn raw_sensor_value * 1.1",
"def error_feature():\n return self.dataX @ (self.dataY - self.hypothesis(self.dataX))",
"def distmeter_err(self):\n from astropy import units\n return self.distmpc_err * units.Mpc.in_units(\"m\")",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an iterator for all of the values at each time step | def __iter__(self):
self.__getitem__(self._num_steps - 1)
return iter(self._previous_values[self.last_index:]) | [
"def __iter__(self):\n for time_point in self.time_points:\n yield time_point",
"def __iter__(self):\n for value in self.values:\n yield value",
"def __iter__(self):\n return self._timeseriesData.__iter__()",
"def iter_values(self):\n values = self.values\n if (v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an iterator for the internal velocity storage | def get_velocity_iter(self):
return iter(self._velocity_storage) | [
"def iterator(self):\n return _yarp.DVector_iterator(self)",
"def iterator(self):\n return _yarp.SVector_iterator(self)",
"def iterator(self):\n return _almathswig.vectorPosition2D_iterator(self)",
"def iterator(self):\n return _yarp.PidVector_iterator(self)",
"def iterator(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns two new lines representing min/max accelerometer error | def get_accelerometer_error(self) -> (Iterable[float], Iterable[float]):
acceleration_error = self.compute_accelerometer_error()
upper_error = [None] * self.num_steps
lower_error = [None] * self.num_steps
upper_error[0] = lower_error[0] = self.initial_value
upper_error[1] = lowe... | [
"def compute_accelerometer_error(self) -> float:\n number_iterations = min(self.past_n_steps, len(self.collected_data))\n if number_iterations <= 1:\n return self.acceleration_error_constant\n\n # Generate a best fitting line for the last few data points\n collected_data_itera... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the amount of error to propogate over the acceleration error lines | def compute_accelerometer_error(self) -> float:
number_iterations = min(self.past_n_steps, len(self.collected_data))
if number_iterations <= 1:
return self.acceleration_error_constant
# Generate a best fitting line for the last few data points
collected_data_iterator = rever... | [
"def acceleration_error_constant(self) -> float:\n return self._acceleration_error_constant",
"def error(line, data): #error function for a line\n \n #Metric: Sum of squared Y-axis differences, y2 - c0.x1 + c1\n err = np.sum((data[:,1] - line[0]*data[:, 0] + line[1])**2)\n return err",
"def _... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""AlexNet model architecture from the | def alexnet(**kwargs):
model = AlexNet(**kwargs)
# if pretrained:
# model.load_state_dict(model_zoo.load_url(model_urls['alexnet']))
return model | [
"def imagenet_alexnet(**kwargs):\r\n model = ImageNetAlexNet(**kwargs)\r\n return model",
"def define_model_architecture(\n net_params: dict,\n in_channels: int,\n out_classes: int):\n return instantiate(net_params, in_channels=in_channels, classes=out_classes)",
"def load_model(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Publish the given message in the given queue | def publish(self, queue, message):
# 1. Setup the channel to use to publish message
channel_handler = ChannelHandler(self._connection)
# 2. Open the channel before using it
channel_handler.open_channel()
# 3. Send the message via the channel
channel_handler.send_message... | [
"def publish(self, message, exchange, routing_key, **kwargs):\r\n mqueue.put(message)",
"def publish(self, queue, message, ttl=3600):\n\n # Get next message ID\n message_id = self.redis.incr(self._ns_nextid())\n\n # Push message to queue\n self.redis.setex(self._ns_message(queue... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reprocess the data for a specific handler, or if to_wrangle is None, then all of them | def rewrangle_data(self, to_wrangle=None):
if to_wrangle is None:
for hname, h in self.handlers.items():
h.run_all()
elif to_wrangle in self.handlers.keys():
self.handlers[to_wrangle].run_all()
else:
print("Cannot wrangle %s as the handler was ... | [
"def process(self, data=None):\n\n return super(RequestHandler, self).process(data=data or self.get_request_data())",
"def transform( request, data, finishing=False ):",
"def _prepare_handlers(self):\r\n timeout = None\r\n readable = []\r\n writable = []\r\n for handler in sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the latest build NVR for a package in the given tag, or None on failure | def get_latest_build(tag, package):
proc = Popen(["osg-koji", "-q", "list-tagged", "--latest", tag, package],
stdout=PIPE)
out = proc.communicate()[0] or b''
ret = proc.returncode
latest_build_line = out.decode("latin-1").strip()
if ret != 0 or not latest_build_line:
retu... | [
"def get_last_release_version():\n tags = run_command('git tag').split('\\n')\n tags = [tag for tag in tags if re.match(r'\\d+\\.\\d+\\.\\d+', tag) is not None]\n tags.sort(key=LooseVersion, reverse=True)\n\n return tags[0]",
"def latest_repo_release(url: str) -> str:\n\n resp = requests.get(ur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the line containing the build ID from `koji buildinfo` output | def get_build_line(latest_build):
proc = Popen(["osg-koji", "buildinfo", latest_build],
stdout=PIPE)
build_line = proc.stdout.readline().decode("latin-1").strip()
ret = proc.wait()
if ret != 0 or not build_line:
return
return build_line | [
"def get_build_id(build_line):\n match = re.search(r'\\[(\\d+)\\]', build_line)\n if match:\n return match.group(1)",
"def get_koji_build_info(build_id, remote, ctx):\n py_cmd = ('import koji; '\n 'hub = koji.ClientSession(\"{kojihub_url}\"); '\n 'print(hub.getBuild({buil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the build ID from the line containing it from `koji buildinfo` | def get_build_id(build_line):
match = re.search(r'\[(\d+)\]', build_line)
if match:
return match.group(1) | [
"def get_build_line(latest_build):\n proc = Popen([\"osg-koji\", \"buildinfo\", latest_build],\n stdout=PIPE)\n build_line = proc.stdout.readline().decode(\"latin-1\").strip()\n ret = proc.wait()\n if ret != 0 or not build_line:\n return\n return build_line",
"def get_build_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exports workspace dataframe to CSV | def workspace_df_to_csv(df, workspace_name):
file_name = workspace_name + '_questions.csv'
script_dir = os.path.dirname(__file__)
output_dir = os.path.join(script_dir, data_dir, 'workspace_training/')
output_path = os.path.join(output_dir, file_name)
df.to_csv(output_path, i... | [
"def export_csv(self, outpath):\n\n\t\tself.df.to_csv(outpath)",
"def write_csv(self):\n self.query_dataframe.to_csv(self.csv_filename, index=False)",
"def output_csv(df: pd.DataFrame, output_data_path: str):\n os.makedirs(os.path.dirname(output_data_path), exist_ok=True)\n df.to_csv(output_data_pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the reference function. | def reset(self):
self.ref_value = 0.0
self._average = 0.0
self.num_samples = 0 | [
"def reset(self, reset):\n\n self._reset = reset",
"def clearReference( r):\r\n if r.ObjType == 3:\r\n try:\r\n r.ClearRef() # from GME8 on\r\n except:\r\n cout( \"Exception while clearing reference: \" + r.Name + \"!\", 3)\r\n raise\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add two averaging objects. | def __iadd__(self, other):
if abs(self.T - other.T) > 1E-5:
msg = "The two objects being added needs to have the same "
msg += "temperature."
raise ValueError(msg)
if self.ref_value < other.ref_value:
diff = self.ref_value - other.ref_value
ot... | [
"def update_average(self, other):\n # Not sure I want this to be an assert, but we certainly want\n # something to check this.\n assert self.column_names == other.column_names\n # pylint: disable=no-member\n assert numpy.array_equal(self.time_grid, other.time_grid)\n total_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search word in brown corpus by input tags. return list | def searchbrown_word(tag):
brown_tagged_words = brown.tagged_words(categories='news')
hitwords = []
for i in range(len(brown_tagged_words)):
if tag == brown_tagged_words[i][1]:
hitwords.append(brown_tagged_words[i][0].lower())
return hitwords | [
"def searchbrown_phrase(tags):\n l = len(tags)\n brown_tagged_words = brown.tagged_words(categories='news')\n hitwords = []\n for i in range(len(brown_tagged_words)-l+1):\n searchtags = [tag for _,tag in brown_tagged_words[i:i+l]]\n if tags == searchtags:\n hitwords.append(tuple... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search phrase in brown corpus by input tags. return touple | def searchbrown_phrase(tags):
l = len(tags)
brown_tagged_words = brown.tagged_words(categories='news')
hitwords = []
for i in range(len(brown_tagged_words)-l+1):
searchtags = [tag for _,tag in brown_tagged_words[i:i+l]]
if tags == searchtags:
hitwords.append(tuple([w.lower()
... | [
"def searchbrown_word(tag):\n brown_tagged_words = brown.tagged_words(categories='news')\n hitwords = []\n for i in range(len(brown_tagged_words)):\n if tag == brown_tagged_words[i][1]:\n hitwords.append(brown_tagged_words[i][0].lower())\n return hitwords",
"def tagWords(words, tags)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Training a PG agent refers to updating its actor using the given observations/actions and the calculated qvals/advantages that come from the seen rewards. Recall that the expression for the policy gradient PG is PG = E_{tau} [sum_{t=0}^{T1} grad log pi(a_t|s_t) (Q_t b_t )] where tau=(s_0, a_0, s_1, a_1, s_2, a_2, ...) ... | def train(self, obs, acs, rews_list, next_obs, terminals):
# step 1: calculate q values of each (s_t, a_t) point,
# using rewards from that full rollout of length T: (r_0, ..., r_t, ..., r_{T-1})
q_values = self.calculate_q_vals(rews_list)
# step 2: calculate advantages that correspon... | [
"def compute_pg_vars(trajs, policy, baseline, discount, gae_lambda):\n for traj in trajs:\n # Include the last observation here, in case the trajectory is not finished\n baselines = baseline.predict(np.concatenate(\n [traj[\"observations\"], [traj[\"last_observation\"]]]))\n if tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes advantages by (possibly) subtracting a baseline from the estimated Q values | def estimate_advantage(self, obs, q_values):
# TODO: Estimate the advantage when nn_baseline is True
# HINT1: pass obs into the neural network that you're using to learn the baseline
# extra hint if you're stuck: see your actor's run_baseline_prediction
# HINT2: advantage should be [Q-b... | [
"def edp_reward(self) -> float:",
"def baseline(data):\n weights = weighting(data)\n return np.inner(weights,data['clicks'])/weights.sum()",
"def avgBaseline():\n return aBaseline",
"def _returns_advantages(self, rewards, dones, values, next_value):\n\t\treturns = np.append(np.zeros_like(rewards), ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parses a composer expression into a function | def parse_func(expr, whitelist, locals):
parsed = parse(expr, whitelist)
src = 'def func(input): return {}'.format(parsed)
exec(src, locals)
return locals.pop('func') | [
"def function_composer(*args):\n return functools.reduce(lambda f, g: lambda x: f(g(x)), args)",
"def build_pfunc(cls, representation):\n if ut.is_str(representation):\n try:\n func = eval(representation)\n except:\n bf = 'cls.build_pfunc('\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a list of items and yields pairs of items that are spread apart. >>> list(collocates(range(10), 3, False)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (4, 7), (5, 6), (5, 7), (5, 8), (6, 7), (6, 8), (6, 9), (7, 8), (7, 9), (8, 9)] | def collocates(items, spread=3, bidir=True):
maximum = len(items)
deltas = range(1, spread + 1)
for i, x in enumerate(items):
for d in deltas:
j = i + d
if j >= maximum:
break
y = items[j]
yield (x, y)
if bidir:
... | [
"def _gen_pairs(items):\n assert len(items) % 2 == 0\n items = iter(items)\n while True:\n try:\n yield next(items), next(items)\n except StopIteration:\n return",
"def pairs(lst):\r\n\tfor i in range(1, len(lst), 2):\r\n\t\tyield lst[i-1], lst[i]",
"def peers_for_cell(self, coords, include_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator to set custom name, tags and argument types to keywords. This decorator creates ``robot_name``, ``robot_tags`` and ``robot_types`` attributes on the decorated keyword method or function based on the provided arguments. Robot Framework checks them to determine the keyword's name, tags, and argument types, resp... | def keyword(name=None, tags=(), types=()):
if callable(name):
return keyword()(name)
def decorator(func):
func.robot_name = name
func.robot_tags = tags
func.robot_types = types
return func
return decorator | [
"def keyword_only(func):\n\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n if len(args) > 0:\n raise TypeError(\"Method %s forces keyword arguments.\" % func.__name__)\n self._input_kwargs = kwargs\n return func(self, **kwargs)\n\n return wrapper",
"def keyword_only... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shift the letter c forward by num, rotating to stay in the alphabet. | def rotate_letter(c, num):
return chr(((ord(c) - 97) + num) % 26 + 97) | [
"def caeser_shift(letter, n):\n if type(letter) != str:\n raise ValueError('Input should be a string')\n elif not (letter.isalpha() and len(letter) == 1):\n raise ValueError('Input should be a single letter')\n\n letter = str.upper(letter)\n shifted_letter = chr((or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Summarise the supplied data. | def summary(data, key=itemgetter(0), value=itemgetter(1)):
for k, group in groupby(data, key):
yield (k, sum(value(row) for row in group)) | [
"def summarize(self, data):\n\n return self.summary(data).flatten()",
"def _summary_stats(data):\n \n stats = {'min':[],'max':[], 'mean':[]}\n \n for scan in range(len(data)):\n stats['min'].append(\n (scan, min(data[scan][1]))\n )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine next setpoint velocities of motors. | def _get_next_velocity(self):
self._predict_state()
# curr = pos_quat_to_euler(self.curr_quat)
dest = pos_quat_to_euler(self.dest_quat_predict)
error = self.calc_error(self.dest_quat_predict)
# TODO error should be computed for phi, th axis individually
# TODO recommen... | [
"def next_config(self):\n\n delta = self.max_acc * self.step_time # denotes possible change in velocity\n right_vels = [self.right_vel + x * delta for x in [-1, 0, 1]]\n left_vels = [self.left_vel + x * delta for x in [-1, 0, 1]]\n best_possible = -math.inf\n best_l, best_r = 0, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Input geographical location, elevation, and timezone for solar model | def location_input():
# location for OPV greenhouse at UA CEAC in Tucson, AZ
latitude = 32.28 # OPV greenhouse latitude (deg)
longitude = -110.94 # OPV greenhouse longitude (deg)
timezone = -7 # Tucson, AZ timezone (UTC)
elevation = 718 # OPV greenhouse elevation (m)
return latitu... | [
"def solar_param((y,mo,d,h,mi),latitude,longitude, UTC_diff=0, groundalbedo=0.18):\n time_shift = datetime.timedelta(hours=UTC_diff) #SGT is UTC+8 \n thistime = pd.DatetimeIndex([pd.Timestamp(np.datetime64(datetime.datetime(y,mo,d,h,mi) + time_shift), tz='UTC')]) \n thisloc = pvlib.location.Location(la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Input orientation of OPV greenhouse | def greenhouse_orientation():
# NEED TO CHECK THIS WITH COMPASS (OR IPHONE)
orientation_angle = 90 # angle between east-west line and the length of the greenhouse (0-90 degree)
orientation_angle = float(orientation_angle) | [
"def get_orientation(self, visited):\n #print(visited)\n if visited:\n rot = mathutils.Quaternion(self.helical_axisParam, self.get_angle(2))\n a = self.positions[2]\n b = self.positions[3]\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fit roof measurements to curve with curve fit function | def curve_fit():
x_west, z_west, x_east, z_east = roof_measurements()
# find best curve fit for west roof section
param_west, param_cov_west = optimize.curve_fit(test_func, x_west, z_west)
print(param_west)
# z = 7.29944696 + (1.27415518*x) + (-0.0680139854*x**2) + (0.00152035861*x**3)
... | [
"def fit_curve(x,y,p0,func):\n ifixx = np.zeros(np.array(x).shape)\n data = sodr.Data(x,y)\n model = sodr.Model(func)\n worker = sodr.ODR(data,model,p0,ifixx=ifixx,maxit=500)\n out = worker.run()\n out = worker.restart()\n return out",
"def use_curvefit(x_values, x_values_extra, y_values, y_v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate incidence angle for every slope agle on greenhouse roof | def calc_incidence_angle():
Delta_r, lat_r, Omega_r, Zenith_r, Azimuth_r, Elev_angle = solar_model()
# Beta is equal to angle of tilted surface to horizontal (in radians)
roof_slopes_west = section_coordinates()
Beta_r = np.arctan(roof_slopes_west)
incidence_angles_west = np.zeros(101)
... | [
"def steps_to_angle():\n pass",
"def _angle_of_attack(self, rel_wind, blade_chord):\n # blade_chord_vector - (relative_wind + pi)\n # rel_oposite = rel_wind.rotated(math.pi)\n aoa_rad = rel_wind.theta - blade_chord.theta\n aoa_rad = vec.normalize_angle(aoa_rad)\n aoa_360 = ao... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Install log handler on Flask application. | def install_handler(self, app):
# Check if directory exists.
basedir = dirname(app.config["LOGGING_FS_LOGFILE"])
if not exists(basedir):
raise ValueError("Log directory {0} does not exist.".format(basedir))
handler = RotatingFileHandler(
app.config["LOGGING_FS_LO... | [
"def configure_logger(app: Flask):\n path = Path(app.config['LOG_PATH'])\n if not path.exists():\n path.mkdir(parents=True)\n log_name = Path(path, 'market_{time}.log')\n\n logger.add(\n log_name,\n encoding='utf-8',\n level=app.config['LOG_LEVEL'],\n backtrace=app.con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
u""" Returns the type of a bankcard based on its number. | def bankcard_type(number):
number = str(number)
if len(number) == 13:
if number[0] == "4":
return VISA
elif len(number) == 14:
if number[:2] == "36":
return MASTERCARD
elif len(number) == 15:
if number[:2] in ("34", "37"):
return AMEX
elif ... | [
"def get_card_type(number):\n number = str(number)\n #group checking by ascending length of number\n if len(number) == 13:\n if number[0] == \"4\":\n return \"VISA\"\n elif len(number) == 15:\n if number[:2] in (\"34\", \"37\"):\n return \"AMEX\"\n elif len(number)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a Bankcard object for use in payment processing. | def get_bankcard_obj(self):
kwargs = {
'card_number': self.cleaned_data['number'],
'expiry_date': self.cleaned_data['expiry_month'].strftime("%m/%y"),
'ccv': self.cleaned_data['ccv_number'],
}
if self.cleaned_data['start_month']:
kwargs['start_date... | [
"def get_bankcard_obj(self):\n kwargs = {\n 'name': self.cleaned_data['EWAY_CARDNAME'],\n 'card_number': self.cleaned_data['EWAY_CARDNUMBER'],\n 'expiry_date': \"%s/%s\" % (\n self.cleaned_data['EWAY_CARDEXPIRYMONTH'],\n self.cleaned_data['EWAY_C... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates which DOT reports have been added. | def update_reports():
return os.listdir('./reports') | [
"def editReport(self, finalReport):\n report = self.mergeReport()\n for f in report.getAllFiles():\n f['outputModule'] = self.moduleName\n f['module_label'] = self.moduleName\n f['inputpfns'] = []\n f['inputs'] = self.inputFiles()\n finalReport.ad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates which csv have been added. | def update_csv():
return os.listdir('./data') | [
"def reload_csv(self):\n self.load_csv()\n self.tableView.insert_data(self.database)\n self.update()",
"def __compare_csv(self):\n # Convert dates to datetime\n self.court_df['date'] = pd.to_datetime(self.court_df['date'], dayfirst=True)\n \n # Load the full datase... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts all the pdf links from beautified soup of DOT website | def get_all_pdf(soup):
list_to_update = []
report = soup.find_all('div', class_='mb-4 clearfix')
for a in report[0].find_all('a', href=True):
sub_link = a['href']
if 'individual' in sub_link:
if not (sub_link.startswith('http') or sub_link.startswith('www')):
... | [
"def get_urls(base_url):\n res = requests.get(base_url, headers=HEADERS)\n res = BeautifulSoup(res.text, 'html.parser')\n res = res.find_all(href=re.compile('pdf'))\n return res",
"def extract_link_pdf(entry):\n return [doc[\"href\"] for doc in e[\"links\"] if doc[\"type\"] == \"application/pdf\"][... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds page numbers for operating metrics. | def find_operating_page_numbers(filename):
with pdfplumber.open(filename) as pdf:
page = pdf.pages[1] # page 41 is missing baggage information
text = page.extract_text()
op_re_exp = r'(Operating Carrier (\(Monthly\)|\(Quarterly\)) \s*\d{1,})|(Reporting Carrier(\s*|\s\(Quarterly\)\s*)\d{1,})'
... | [
"def get_num_of_pages(self):",
"def get_num_page(abs_path):\n\n prev_p, curr_p = None, None\n \n try:\n for cmd in (('/usr/local/bin/pdfinfo', abs_path),\n ('grep', 'Pages'),\n ('awk', '{print $2}')):\n curr_p = subprocess.Popen(cmd, stdout=subproce... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts monthly values out of pdf file. | def get_table_values_monthly(filename, page_num):
with pdfplumber.open(filename) as pdf:
page = pdf.pages[page_num - 1]
text = page.extract_text()
# Regex
re_month = re.compile(r'^[A-Za-z]*.\d{2,}') # Finds the month/year
re_new_rank = re.compile(r'^\d{1,}\s*[A-Z].*') # finds indices
... | [
"def mo_parse_pdf(self, filepath):\n\n text = textract.process(filepath, encoding='utf-8')\n text = text.decode('utf-8')\n\n if 'PRESSURE CALIBRATION DATA' in text:\n self.mo_parse_p(filepath)\n\n elif 'TEMPERATURE CALIBRATION DATA' or 'CONDUCTIVITY CALIBRATION DATA' in text:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts quarterly values out of pdf file. | def get_table_values_quarterly(filename, page_num):
with pdfplumber.open(filename) as pdf:
page = pdf.pages[page_num - 1]
text = page.extract_text()
# Regex
re_month = re.compile(r'^[A-Za-z]*.-.[A-Za-z]*.\d{2,}') # Finds the month/year
re_new_rank = re.compile(r'^\d{1,}\s*[A-Z].*') # f... | [
"def get_table_values_monthly(filename, page_num):\n with pdfplumber.open(filename) as pdf:\n page = pdf.pages[page_num - 1] \n text = page.extract_text()\n\n # Regex\n re_month = re.compile(r'^[A-Za-z]*.\\d{2,}') # Finds the month/year\n re_new_rank = re.compile(r'^\\d{1,}\\s*[A-Z].*') # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle ACME "challenge" phase. | def acme_challenge(self, domain):
return self.network.send_and_receive_expected(
messages.ChallengeRequest(identifier=domain),
messages.Challenge) | [
"async def complete_challenge(\n self,\n key: josepy.jwk.JWK,\n identifier: acme.messages.Identifier,\n challenge: acme.messages.ChallengeBody,\n ):\n pass",
"def on_challenge(challenge):\n print(printHeader('FFBOLab Client') + 'Initiating authentication.')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves the certificate received from the ACME server. | def save_certificate(self, certificate_msg, cert_path, chain_path):
# pylint: disable=no-self-use
cert_chain_abspath = None
cert_fd, cert_file = le_util.unique_file(cert_path, 0o644)
cert_fd.write(certificate_msg.certificate.as_pem())
cert_fd.close()
logging.info(
... | [
"def save_ca():\n cert_file = os.environ.get('HOME') + '/.cat_installer/ca.pem'\n debug(\"saving cert\")\n with open(cert_file, 'w') as cert:\n cert.write(Config.CA + \"\\n\")",
"def save_certificate(self, stdout):\n # save the file\n with open(self.certificate_path, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Redirect all traffic from HTTP to HTTPS | def redirect_to_ssl(self, domains):
for dom in domains:
try:
self.installer.enhance(dom, "redirect")
except errors.LetsEncryptConfiguratorError:
logging.warn("Unable to perform redirect for %s", dom)
self.installer.save("Add Redirects")
se... | [
"def ssl_redirect():\n if request.get_header('X-Forwarded-Proto', 'http') != 'https':\n redirect(request.url.replace('http://', 'https://', 1), code=301)",
"def rewrite_https():\n\n if request.path.startswith(\"/_healthz\"):\n # Health blueprint must be accessible via HTTP\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate Key and CSR files. Verifies that the client key and csr arguments are valid and correspond to one another. This does not currently check the names in the CSR due to the inability to read SANs from CSRs in python crypto libraries. If csr is left as None, only the key will be validated. | def validate_key_csr(privkey, csr=None):
# TODO: Handle all of these problems appropriately
# The client can eventually do things like prompt the user
# and allow the user to take more appropriate actions
# Key must be readable and valid.
if privkey.pem and not crypto_util.valid_privkey(privkey.pem... | [
"def test_validate_ksr_with_ecdsa_key(self):\n xml = self._make_request()\n request = request_from_xml(xml)\n self.assertTrue(validate_request(request, self.policy))",
"def check_valid_request_ca(self):\n\n self.check_valid_request_common()\n\n alg = self.get_POW().getSignatureA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a CSR with the given private key. | def init_csr(privkey, names, cert_dir):
csr_pem, csr_der = crypto_util.make_csr(privkey.pem, names)
# Save CSR
le_util.make_or_verify_dir(cert_dir, 0o755)
csr_f, csr_filename = le_util.unique_file(
os.path.join(cert_dir, "csr-letsencrypt.pem"), 0o644)
csr_f.write(csr_pem)
csr_f.close()
... | [
"def __init__(self, private_key):\n if private_key:\n if isinstance(private_key, str): # base58 encoded string\n self.private_key = PrivateKey.from_b58check(private_key)\n else:\n self.private_key = private_key\n self.public_key = self.private_k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a prettyprinted list of authenticators. This is used to provide helpful feedback in the case where a user specifies an invalid authenticator on the command line. | def list_available_authenticators(avail_auths):
output_lines = ["Available authenticators:"]
for auth_name, auth in avail_auths.iteritems():
output_lines.append(" - %s : %s" % (auth_name, auth.description))
return '\n'.join(output_lines) | [
"def active_authenticators(self, email, username, password):\n try:\n for authenticator in self.authenticators:\n filter_template = authenticator.filter_template\n if filter_template:\n filter_str = filter_template.format(email=email, username=usern... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a valid installer if one exists. | def determine_installer(config):
installer = configurator.ApacheConfigurator(config)
try:
installer.prepare()
return installer
except errors.LetsEncryptNoInstallationError:
logging.info("Unable to find a way to install the certificate.")
return
except errors.LetsEncryptMi... | [
"def installer_exists(self, platform):\n \n validations.validate_platform(platform)\n \n installer_filename = os.path.join(\n settings.CUSTOM_INSTALLER_ROOT,\n self.build_id,\n constants.PLATFORM_BUNDLES[platform]\n )\n\n if os.path.isfile(installer_filename):\n return True\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View checkpoints and associated configuration changes. | def view_config_changes(config):
rev = reverter.Reverter(config)
rev.recovery_routine()
rev.view_config_changes() | [
"def view_config_changes(self):\n logger.warning(\"view_config_changes not implemented\")\n raise errors.NotSupportedError(\"N/A\")",
"def checkpoint():",
"def get_checkpoints(self):\n # recompute checkpoints\n return self._checkpoints",
"def checkpoint(self):\r\n return self._c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtains the default parameters of a given function | def get_default_args(func):
signature = inspect.signature(func)
return {
k: v.default
for k, v in signature.parameters.items()
if v.default is not inspect.Parameter.empty
} | [
"def parameter_defaults(func: Callable) -> dict[str, Any]:\n signature = inspect.signature(func)\n return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}",
"def get_default_args(func):\n\tsignature = inspect.signature(func)\n\treturn {k: v.default\n\t\tfor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds all intervals whose intersection with interval is not empty; also includes the two intervals the the most left and right if their bounds are directly adjacent to the interval. For example, if intervals | def _intersect_continuous(self, interval):
first = self.intervals.bisect_left(interval)
last = first
while first > 0 and \
self.intervals[first - 1].upper >= interval.lower:
first -= 1
while last < len(self.intervals) and \
self.intervals[last].low... | [
"def overlap_of_all_intervals(interval_edges): #this may be (very?) inefficient...this actually isn't the way manin calculated overlap\n totaloverlap = 0\n trimmed_interval_edges = copy.deepcopy(interval_edges)\n for index, first_interval in enumerate(interval_edges):\n #sys.stderr.write('Interval {... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the interval that contains the given value. | def find(self, value):
index = self.intervals.bisect_left(value)
if index < len(self.intervals) and self.intervals[index].lower == value:
return self.intervals[index]
if index > 0 and self.intervals[index - 1].contains(value):
return self.intervals[index - 1]
retu... | [
"def intervalContaining(self, point):\n for interval in self.intervals:\n if interval.contains(point):\n return interval\n return None",
"def _find_interval_containing_new_value(x, new_value):\n new_value_shape = shape_utils.combined_static_and_dynamic_shape(new_value)[0]\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the list of intervals has a nonempty intersection with the given interval. | def contains(self, interval):
first, last = self._intersect(interval)
return first != last | [
"def __contains__(self, interval: GenomeInterval) -> bool:\n contig = interval.contig\n if contig not in self.interlaps:\n return False\n return interval in self.interlaps[contig]",
"def nonempty_intersection(list1, list2):\n return len(list(set(list1) & set(list2))) > 0",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a function which has an image as first parameter and additional parameters. It will build a user interface consisting of sliders for numeric parameters and parameters that are called "footprint" or "selem". | def interact(func,
image = None,
*args,
continuous_update: bool = True,
context:dict = None,
zoom_factor:float = 1.0,
zoom_spline_order:int = 0,
colormap:str = None,
display_min:float = None,
display_max... | [
"def interact(func, image, *args, **kwargs):\n import inspect\n import ipywidgets\n\n exposable_parameters = []\n footprint_parameters = []\n\n sig = inspect.signature(func)\n for key in sig.parameters.keys():\n exposable = False\n default_value = 0\n if isinstance(sig.paramet... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy contents of INPUT to OUTPUT. | def inout(input_, output_):
while True:
chunk = input_.read(1024)
if not chunk:
break
output_.write(chunk) | [
"def copy(self, input, output):\n in_log = open(input, 'r')\n for line in in_log:\n output.write(line)\n in_log.close()",
"def _copy_output(src: Graph, dst: Graph):\n for n_src, n_dst in zip(src.nodes, dst.nodes):\n if n_src.op == 'output':\n n_dst.meta = n_src... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return WeightCategory.light if weight is below 100 | def get_weight_category(self) -> WeightCategory:
return WeightCategory.light if self.weight < 100 else WeightCategory.heavy | [
"def determine_category(weight):\n if weight < 52:\n return Category.FLY\n elif 52 <= weight < 57:\n return Category.FEATHER\n elif 57 <= weight < 63:\n return Category.LIGHT\n elif 63 <= weight < 69:\n return Category.WELTER\n elif 69 <= weight < 75:\n return Categ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the current pipeline filename string | def save(self, filename):
pass | [
"def save_pipeline(*, pipeline_to_persist) -> None:\n\n # Prepare versioned save file name\n save_file_name = f\"{config.app_config.pipeline_save_file}{_version}.pkl\"\n save_path = TRAINED_MODEL_DIR / save_file_name\n # Remove old pipeline\n remove_old_pipelines(files_to_keep=[save_file_name])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates the request URL from the current configuration | def _create_request_url():
url = 'http'
if _config['save']:
url += 's'
url += '://{}:{}/move'.format(_config['ip'], _config['port'])
return url | [
"def configuration_url(self):",
"def generate_url(self):\n self.ensure_one()\n base_url = self.env['ir.config_parameter'].get_param('web.base.url')\n if base_url and base_url[-1:] != '/':\n base_url += '/'\n db = self._cr.dbname\n return \"{}web?db={}#id={}&view_type=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clamps a given value between 0 and 100. | def _clamp_percent(value):
if value < 0:
print("Less than 0 percent specified for extension. Clamping to 0")
value = 0
elif value > 100:
print("More than 100 percent specified for extension. Clamping to 100")
value = 100
return value | [
"def clamp(value, floor=-100, ceil=100):\n return max(min(value, ceil), floor)",
"def clamp(min_value: float, max_value: float, value: float):\n\t\tvalue = min(value, max_value)\n\t\tvalue = max(value, min_value)\n\t\treturn value",
"def clamp(min_value, max_value, value):\n return max(min_value, min(valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves only finger 3 | def move_finger3(percent):
percent = _clamp_percent(percent)
_send_request(f3=percent) | [
"def touch_moved(self, touch):\n\t\tpass",
"def swipe_up(self):\n self.swipe_sub(SWIPE_MATRIX[0])",
"def swipe_left(self):\n self.swipe_sub(SWIPE_MATRIX[2])",
"def swipe_down(self):\n self.swipe_sub(SWIPE_MATRIX[1])",
"def swipe_right(self):\n self.swipe_sub(SWIPE_MATRIX[3])",
"def move3(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves only finger 4 | def move_finger4(percent):
percent = _clamp_percent(percent)
_send_request(f4=percent) | [
"def swipe_down(self):\n self.swipe_sub(SWIPE_MATRIX[1])",
"def swipe_up(self):\n self.swipe_sub(SWIPE_MATRIX[0])",
"def swipe_left(self):\n self.swipe_sub(SWIPE_MATRIX[2])",
"def swipe_right(self):\n self.swipe_sub(SWIPE_MATRIX[3])",
"def touch_moved(self, touch):\n\t\tpass",
"def swipe_custo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves only finger 5 | def move_finger5(percent):
percent = _clamp_percent(percent)
_send_request(f5=percent) | [
"def swipe_up(self):\n self.swipe_sub(SWIPE_MATRIX[0])",
"def swipe_down(self):\n self.swipe_sub(SWIPE_MATRIX[1])",
"def touch_moved(self, touch):\n\t\tpass",
"def swipe_left(self):\n self.swipe_sub(SWIPE_MATRIX[2])",
"def fingersUp(self):\n if self.results.multi_hand_landmarks:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves all fingers specified. Unspecified fingers are not moved | def move_fingers(f1=None, f2=None, f3=None, f4=None, f5=None):
_send_request(f1=f1, f2=f2, f3=f3, f4=f4, f5=f5) | [
"def fix_all_fingers(self):\n for next in range(self.m):\n self.finger_table[next] = self.find_successor(self.key.id + 2**self.next)",
"def fingersUp(self):\n if self.results.multi_hand_landmarks:\n myHandType = self.handType()\n fingers = []\n # Thumb\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the extra property by deserializing json. | def extra_dejson(self):
obj = {}
if self.extra:
try:
obj = json.loads(self.extra)
except Exception as e:
self.log.exception(e)
self.log.error("Failed parsing the json for conn_id %s", self.conn_id)
return obj | [
"def json_property(self, json_name: str):\n try:\n #\n # Looking for specific attribute\n #\n prev = self._raw_values\n for attr in json_name.split(\".\"):\n prev = prev[attr]\n\n return prev\n except KeyError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs asynchronous video annotation. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `AnnotateVideoProgress` (progress). `Operation.response` contains `AnnotateVideoResponse` (results). | def AnnotateVideo(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | [
"def AnnotateVideo(self, request, timeout, metadata=None, with_call=False, protocol_options=None):\n raise NotImplementedError()",
"def annotate_video(input_file, output_file):\n\tvideo = VideoFileClip(input_file)\n\tannotated_video = video.fl_image(annotate_image_array2)\n\tannotated_video.write_videofile(o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs asynchronous video annotation. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `AnnotateVideoProgress` (progress). `Operation.response` contains `AnnotateVideoResponse` (results). | def AnnotateVideo(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
raise NotImplementedError() | [
"def AnnotateVideo(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def annotate_video(input_file, output_file):\n\tvideo = VideoFileClip(input_file)\n\tannotated_vid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return current position in the playlist. | def current_position(self):
# It is an error to call playlist_current_pos when there are
# no entries in the playlist.
r = self.x.playlist_current_pos()
r.wait()
if r.iserror():
print r.get_error()
return None
else:
return r.get_dict()... | [
"def get_pos(self):\n if self.player is not None and self.state == \"play\":\n return self.player.get_position() * self._length\n return 0",
"def media_position(self):\n if self._media_playback_trackable():\n self._media_position_updated_at = utcnow()\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format the playlist. First we try to get imformation from id3v2, if it fails, then try id3, else we just display the file name. | def playlist(self):
def iconv(s):
encoding = self.options["id3_encoding"]
try:
if encoding:
return s.encode('latin1').decode(encoding).encode('utf-8')
else:
return s.encode('latin1')
except UnicodeEncodeE... | [
"def find_artist_playlist(data):\n\n return data['artist'].lower() + '.m3u'",
"def playlist_name(self) -> str:\n # Assumption: Line with playlist name begins with \"name:\"\n line = self.line_starts_with(\"name:\")\n if not line:\n return self.filename\n colon_index = lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the path enterd by the user, and expand it to full path. Or return None if user haven't enter anything. | def _get_path(self, prompt):
# When input from vim, vim escapes some special characters,
# so we have to expand them first.
cwd = vim.eval('expand(getcwd())')
path = vim.eval('expand(input("%s", "", "file"))' % prompt)
if path == None or path == "":
return None
... | [
"def expandpath(path):\n return os.path.abspath(os.path.expanduser(path))",
"def ExpandPath(path):\n return os.path.realpath(os.path.expanduser(path))",
"def _expand_user(pathname):\n if pathname is None:\n return None\n return os.path.expanduser(pathname)",
"def expandpath(path, force_absolu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all lines in the window. | def _clear_window(self):
self.buf[:] = [] | [
"def delete_all_lines(self, *args):\n self.lines.clear()",
"def clear():\n # TODO: this should actually create a stack of output so I can test each screen\n lines.clear()",
"def clearwin(window, startx, starty):\n\n y,x = window.getmaxyx()\n\n for i in range(startx, x-1):\n for j in ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refresh the play window. | def refresh_window(self):
self.buf[:] = self.player.playlist()
if self.prev_song != None:
self.refresh_mark() | [
"def refresh_window(self):",
"def refresh(self):\n self.screen.refresh()\n self.title_bar.refresh()\n self.main_output.refresh()\n self.main_input.refresh()",
"def refresh(self):\n\t\tfor window in self.refresh_queue:\t# Make sure to go through in sequential order, as the windows\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Force the use of the Python implementation of the kernels | def usePython():
global kernels_imp
from .import _kernels_py
kernels_imp = _kernels_py | [
"def useCython():\n global kernels_imp\n if HAS_CYTHON:\n import _kernels\n kernels_imp = _kernels",
"def disable_custom_kernel():\n global _TF_ADDONS_PY_OPS\n _TF_ADDONS_PY_OPS = True",
"def enable_custom_kernel():\n global _TF_ADDONS_PY_OPS\n _TF_ADDONS_PY_OPS = False",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Force the use of the Cython implementation of the kernels, if available | def useCython():
global kernels_imp
if HAS_CYTHON:
import _kernels
kernels_imp = _kernels | [
"def usePython():\n global kernels_imp\n from .import _kernels_py\n kernels_imp = _kernels_py",
"def enable_custom_kernel():\n global _TF_ADDONS_PY_OPS\n _TF_ADDONS_PY_OPS = False",
"def disable_custom_kernel():\n global _TF_ADDONS_PY_OPS\n _TF_ADDONS_PY_OPS = True",
"def run_cython(args)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns some functionalities of a module that is declared in a MARA_XXX variable or function `module.MARA_XXX` can be a function that returns a list or dict a list a dict | def module_functionalities(module: types.ModuleType, MARA_XXX: str, type) -> []:
if MARA_XXX in dir(module):
functionalities = getattr(module, MARA_XXX)
if isinstance(functionalities, typing.Callable):
functionalities = functionalities()
if isinstance(functionalities, typing.Dict... | [
"def get_functions(module_name, as_string=False):\n if module_name == \"all\":\n funcs = []\n funcs_in_dict = func_dict()\n for key in funcs_in_dict:\n for func in funcs_in_dict[key]:\n funcs.append(func)\n else:\n funcs = func_dict()[module_name]\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches for all declared click commands and adds them to the app, grouped by package | def register_commands(self):
for module in copy.copy(sys.modules).values():
for command in module_functionalities(module, 'MARA_CLICK_COMMANDS', click.Command):
if 'callback' in command.__dict__ and command.__dict__['callback']:
package = command.__dict__['callbac... | [
"def add_commands(names=()):\n\n for name in names:\n for entry_point in iter_entry_points(name):\n try:\n func = entry_point.load()\n flowtool_main_group.add_command(func, name=entry_point.name)\n except DistributionNotFound:\n style.debu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a global layout with navigation etc. to pages | def register_page_layout(self):
def after_request(r: flask.Response):
if isinstance(r, response.Response):
r.set_data(layout.layout(r))
return r
self.after_request(after_request) | [
"def create_mainlayout(self):\n self.main_layout.addLayout(self.create_view_area_layout())\n self.main_layout.addLayout(self.create_information_layout())",
"def add_navigation(self):\n placeholder = self.page.placeholders.get(slot='content')\n add_plugin(placeholder, 'LocalNavigationPl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable caching for dynamic content (not static files). | def disable_caching(self):
def after_request(r: flask.Response):
if 'Cache-Control' not in r.headers:
r.headers['Cache-Control'] = 'no-store'
return r
self.after_request(after_request) | [
"def disable_caches(self):",
"def disable_cache():\n global _CACHING\n _CACHING = False",
"def never_cache_preview(response):\n response.cache_control.max_age = 0\n response.cache_control.no_cache = True\n response.cache_control.must_revalidate = True\n response.cache_control.no_store = True\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets up error pages for all http exceptions | def register_error_handlers(self):
def error_handler(error):
if not isinstance(error, exceptions.HTTPException):
error = exceptions.InternalServerError()
return response.Response(bootstrap.card(body=_.span[_.p(style='color:#888')[error.description or ''],
... | [
"def register_errorhandlers(app):\n\n def render_error(e):\n return render_template('errors/%s.html' % e.code), e.code\n\n for e in [\n requests.codes.INTERNAL_SERVER_ERROR,\n requests.codes.NOT_FOUND,\n requests.codes.UNAUTHORIZED,\n ]:\n app.errorhandler(e)(render_error... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Caches calls to flask.url_for because it's kind of slow | def patch_flask_url_for(self):
original_url_for = flask.url_for
flask.url_for = functools.lru_cache(maxsize=None)(original_url_for) | [
"def _install_url_for_wrappers(self):\n\n # python code is unaffected by Frozen-Flask unless\n # it explicitly uses relative_url_for(), so check:\n\n if self.freezing and self.app.config['FREEZER_RELATIVE_URLS']:\n current_url_for = relative_url_for\n else:\n curren... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a new command to a mara flask app. Args | def register_command(app: MaraApp, command: click.Command, package: str):
if isinstance(command, click.MultiCommand):
app.cli.add_command(command)
else:
command.name = package + '.' + command.name
app.cli.add_command(command) | [
"def register_commands(app: Flask):\n\n app.cli.add_command(db_cli)\n\n @app.cli.command(\n \"pip-compile\",\n context_settings=dict(\n ignore_unknown_options=True,\n allow_extra_args=True,\n help_option_names=[],\n ),\n )\n @click.pass_context\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |