query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Fetch from url or from file if it has been cached previously | def fetch_maybe(cls, url, path, save=False):
if os.path.isfile(path):
# print("Found %s" % os.path.basename(path))
with open(path, "rb") as file:
return file.read(), True
if save:
return cls.fetch_and_save(url, path), False
return cls.fetch_wit... | [
"def _resolve_cache(self, url):\n data = self.cache.get(url)\n if not data:\n return None\n if self.debug:\n log.debug('GET {} got result from cache.'.format(url))\n return data",
"def FetchUrlContent(url):\n content = memcache.get(url)\n if content:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch file and save to disk | def fetch_and_save(cls, url, path):
content = cls.fetch_with_retry(url)
if not content:
return False
# print("Saving {}".format(os.path.basename(path)))
with open(path, "wb") as file:
file.write(content)
return content | [
"def fetch_save(url):\n\n name = url.split(\"/\")[-1]\n response = requests.get(url, stream=True)\n if response.status_code == 200:\n with open(f\"{DATA_PATH}/{name}\", \"wb\") as f:\n f.write(response.raw.read())\n else:\n logging.info(f\"Failed {url} download\")",
"def _do_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementatin of sim(n1, n2) from Collins and Duffy (2001). Parsing with a Single Neuron. Given two (dependency parse) graphs and a node from each one, returns the set of common dependency targets. Each target consists of a (target node ID, target node ID) tuple, where the first target is from the first graph and the s... | def common_dependency_targets(graph1, graph2, n1, n2, node_attrib='label',
edge_attrib='label'):
n1_children = dependency_children(graph1, n1, edge_attrib=edge_attrib)
n2_children = dependency_children(graph2, n2, edge_attrib=edge_attrib)
n1_rels, n2_rels = defaultdict(list), d... | [
"def node_diff(self):\n if self.input1 is None or self.input2 is None:\n raise Exception(\"Missing input: please run the populate() method first\")\n if self.node_dict1 is None or self.node_dict2 is None:\n self.make_node_dict()\n # Initialize dictonaries to keep track of ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Counts the number of common (dependency parse) subgraphs rooted at n1 and n2. This is an implementation of Cm(n1, n2) for dependency structures from Collins and Duffy (2001). Parsing with a Single Neuron. | def count_common_subgraphs(graph1, graph2, n1, n2,
node_attrib='label', edge_attrib='label'):
for graph in (graph1, graph2):
assert nx.is_directed_acyclic_graph(graph)
if graph1.node[n1][node_attrib] != graph2.node[n2][node_attrib]:
return 0
n1_children = dependenc... | [
"def getNumberOfCommonLabels(variant1=[], variant2=[]):\n\n return len(commonLabels(variant1,variant2))",
"def CN(G,nodeij):\n node_i=nodeij[0]\n node_j=nodeij[1]\n neigh_i=set(G.neighbors(node_i))\n neigh_j=set(G.neighbors(node_j))\n neigh_ij=neigh_i.intersection(neigh_j)\n num_cn=len(neigh_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a graph, returns a set of its dependency rules. If root_node is given, returns only those rules from the subgraph rooted at that node. A dependency rules is represented by a (source node label, edge/relation label, target node label) triple, e.g. ('woman', 'dt', 'the'). Returns | def get_dependency_rules(graph, root_node=None,
node_attrib='label', edge_attrib='label'):
rules = set()
if not root_node:
# root node is the first element in a topological sort of the graph
root_node = nx.topological_sort(graph)[0]
for source, target in nx.dfs_edg... | [
"def get_dependencies(graph: Graph, node: Node):\n dependencies: Set[Node] = set()\n def traverse_nodes(nodes):\n for candidate in nodes:\n if candidate not in dependencies:\n dependencies.add(candidate)\n traverse_nodes(graph[candidate])\n traverse_nodes(gra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns True, iff a graph contains all dependency rules of the given subgraph candidate. | def includes_all_subgraph_rules(graph, subgraph_candidate,
subgraph_root_node=None,
node_attrib='label', edge_attrib='label'):
graph_rules = get_dependency_rules(graph, node_attrib=node_attrib,
edge_attrib=edge_at... | [
"def is_dependency_subgraph(graph, subgraph_candidate,\n node_attrib='label', edge_attrib='label'):\n if len(subgraph_candidate) > 1:\n if nx.is_weakly_connected(subgraph_candidate):\n if includes_all_subgraph_rules(graph, subgraph_candidate,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns True, if the graph contains all of the subgraph candidate's dependency rules. The subgraph must also be (weakly) connected and contain at least two nodes. | def is_dependency_subgraph(graph, subgraph_candidate,
node_attrib='label', edge_attrib='label'):
if len(subgraph_candidate) > 1:
if nx.is_weakly_connected(subgraph_candidate):
if includes_all_subgraph_rules(graph, subgraph_candidate,
... | [
"def includes_all_subgraph_rules(graph, subgraph_candidate,\n subgraph_root_node=None,\n node_attrib='label', edge_attrib='label'):\n graph_rules = get_dependency_rules(graph, node_attrib=node_attrib,\n edge_attri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
naively generate all (dependency parse) subgraphs of a given graph by iterating through all possible node combinations. HIGHLY INEFFICIENT. | def get_dependency_subgraphs(graph, node_attrib='label', edge_attrib='label'):
assert nx.is_directed_acyclic_graph(graph)
for n in xrange(graph.number_of_nodes()):
for subnodes in itertools.combinations(graph.nodes(), n+1):
subgraph_candidate = graph.subgraph(subnodes)
if is_depe... | [
"def strongly_connected_component_subgraphs(G):\n cc=strongly_connected_components(G)\n graph_list=[]\n for c in cc:\n graph_list.append(G.subgraph(c))\n return graph_list",
"def run_generations(init_len):\n num_graphs = 0\n current_gen = [nx.path_graph(init_len)]\n complete_graph_list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dp[i][j] represent the length of longest palindrome subseq from s[i] to s[j] so the answer is dp[0][n 1] | def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [[1] * n for _ in range(n)]
for length in range(1, n + 1):
for i in range(n - length + 1):
j = i + length - 1
print(i, j)
if length == 1:
dp[i][j] = 1... | [
"def longestPalindrome_np2(self, s: str) -> str:\n jen = 1\n start = 0\n end = 0\n k = len(s)\n dp = [[0 for i in range(k)] for i in range(k)]\n \n for i in range(k): #i表示回文子串的尾部索引\n for j in range(i+1):#j表示回文子串的头部索引\n if i - j <= 1: #相邻的情况\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets GoogleMediaItem object attributes to values given in dictionary | def from_dict(self, dictionary):
required_keys = ['filename', 'id', 'baseUrl']
assert all(key in list(dictionary.keys()) for key in required_keys), \
'Dictionary missing required key. GoogleMediaItem.from_dict() ' \
'requires keys: {}'.format(required_keys)
self.name = ... | [
"def set_attrs(source, item):\n for attr in source.attrs:\n item.attrs[attr] = source.attrs[attr]",
"def _set_attrs(ds, **attrs_map):\n for key in attrs_map:\n val = attrs_map[key] # Use Python 2/3 agnostic style\n ds.attrs[key] = val",
"def set_attr(self, asset_key, attr, value=True)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name of stages to initialize as string or list (not tuple!) or None to skip. Skip single axes with "" or None as item in the list. | def stages(self, stages):
if stages is None:
self._stages = None
else:
self._stages = stages if isinstance(stages, list) else [stages] * len(self.pidevice.allaxes)
debug('ControllerStartup.stages = %s', itemstostr(self._stages)) | [
"def stage_names(cls, stage_count, is_curtis):\r\n\t\tif is_curtis:\r\n\t\t\treturn [\r\n\t\t\t\t'Stage %s' % cls._curtis_label(i) \r\n\t\t\t\tfor i in range(1, stage_count + 1)\r\n\t\t\t]\r\n\t\telse:\r\n\t\t\treturn ['Stage %s' % i for i in range(1, stage_count + 1)]",
"def optional_input_names(self) -> List[Un... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name of axes as list of strings or None. | def axesnames(self):
return self._axesnames | [
"def axesNames(self, data, info):\n return []",
"def allAxes( mv ):\n if mv is None: return None\n return mv.getAxisList()",
"def _getaxes(self):\n try:\n return [getattr(self.nxgroup,name) for name in _readaxes(self.axes)]\n except KeyError:\n return None",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call INI command if available. | def callini(self):
debug('ControllerStartup.callini()')
if not self.pidevice.HasINI() or self.prop['skipini']:
return
self.pidevice.INI() | [
"def ini(*args):\n return _VMpy.ini(*args)",
"def run_if_interactive(self):\n pass",
"def load_anki():\r\n try:\r\n Config.load_config()\r\n except Exception as e:\r\n print(\"Error when loading config:\", e)\r\n print(\"Please open Anki before running script again.\")\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait until device is ready. | def waitonready(self):
debug('ControllerStartup.waitonready()')
waitonready(self.pidevice, **self._kwargs) | [
"def _wait(self):\n t0 = time()\n while not self.is_ready():\n if time() - t0 > self.READY_TIMEOUT_SEC:\n raise DeviceIsNotReady()",
"async def wait_until_ready(self):\r\n await self._is_ready.wait()",
"async def wait_until_ready(self):\n await self._ready.w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset servo if it has been changed during referencing. | def resetservo(self):
debug('ControllerStartup.resetservo()')
if self.servostates is not None:
setservo(self.pidevice, self.servostates)
elif self._databuf['servobuf']:
setservo(self.pidevice, self._databuf['servobuf']) | [
"def servo_off(self):\n self.logger.info('Setting servo OFF')\n self.electronics.move_servo(0)\n self.config['servo']['status'] = 0",
"def _set_servo(self):\n self.servo.set_mode(0)\n if \"h\" in DEBUG:\n progress(\"%s.set_mode('Servo')\" % (self.servo.name))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reference unreferenced axes if according option has been provided and wait on completion. | def referencewait(self):
debug('ControllerStartup.referencewait()')
if not self.refmodes or self.prop['skipref']:
return
self._databuf['servobuf'] = getservo(self.pidevice, self.pidevice.axes)
toreference = {} # {cmd: [axes]}
for i, refmode in enumerate(self._refmode... | [
"def _ref_with_refcmd(self, axes, refmode):\n debug('ControllerStartup._ref_with_refcmd(axes=%s, refmode=%s)', axes, refmode)\n for axis in axes:\n if self.pidevice.HasRON():\n try:\n self.pidevice.RON(axis, True)\n except GCSError as exc:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if 'axis' has already been referenced with 'refmode'. | def _isreferenced(self, refmode, axis):
if self.prop['forceref']:
return False
if refmode in ('POS',):
return False
if refmode == 'ATZ':
return self.pidevice.qATZ(axis)[axis]
if refmode == 'REF':
return self.pidevice.qREF(axis)[axis]
... | [
"def is_ref_known(self):\r\n \r\n if \"N\" in self.ref:\r\n return False\r\n else:\r\n return True",
"def checkRefs(self, export_refs):\r\n return True",
"def is_ref(self, node):\n return node in self.ref_nodes and node not in self.main_nodes"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enable RON, change servo state if appropriate and reference 'axes' with the 'refmode' command. | def _ref_with_refcmd(self, axes, refmode):
debug('ControllerStartup._ref_with_refcmd(axes=%s, refmode=%s)', axes, refmode)
for axis in axes:
if self.pidevice.HasRON():
try:
self.pidevice.RON(axis, True)
except GCSError as exc:
... | [
"def servo_on(self):\n self.logger.info('Setting servo ON')\n self.electronics.move_servo(1)\n self.config['servo']['status'] = 1",
"def _set_motor(self):\n self.servo.set_mode(1)\n if \"h\" in DEBUG:\n progress(\"%s.set_mode('Motor')\" % (self.servo.name))\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Autozero 'axes' and move them to position "0.0". | def _autozero(self, axes):
debug('ControllerStartup._autozero(axes=%s)', axes)
self.pidevice.ATZ(axes, ['NaN'] * len(axes))
waitonautozero(self.pidevice, axes, **self._kwargs)
setservo(self.pidevice, axes, [True] * len(axes), **self._kwargs)
moveandwait(self.pidevice, axes, [0.0]... | [
"def moveToZero(self):\n\t\tself.grp.a.t.v = [0,0,0]\n\t\tself.grp.a.r.v = [0,0,0]",
"def clean_axes(ax):\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')",
"def reset(self):\n self.xvie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set RON accordingly and reference 'axes' with the POS command to position "0.0". | def _ref_with_pos(self, axes):
debug('ControllerStartup._ref_with_pos(axes=%s)', axes)
assert self.pidevice.HasPOS(), 'controller does not support the POS command'
self.pidevice.RON(axes, [False] * len(axes))
self.pidevice.POS(axes, [0.0] * len(axes))
waitonready(self.pidevice, *... | [
"def set_axes(num_axes):\n Path.NUM_AXES = num_axes\n Path.max_speeds = np.ones(num_axes)\n Path.home_speed = np.ones(num_axes)\n Path.home_backoff_speed = np.ones(num_axes)\n Path.home_backoff_offset = np.zeros(num_axes)\n Path.steps_pr_meter = np.ones(num_axes)\n P... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enable all connected axes if appropriate. | def enableaxes(self):
debug('ControllerStartup.enableaxes()')
if not self.pidevice.HasEAX() or self.prop['skipeax']:
return
for axis in self.pidevice.axes:
try:
self.pidevice.EAX(axis, True)
except GCSError as exc:
if exc != gcs... | [
"def _enable_channels(self) -> None:\n for ch in self.active_channels:\n path = f\"qachannels_{ch}_\"\n self.set(path + \"input_on\", 1)\n self.set(path + \"output_on\", 1)",
"def setAxisAllColor(idx=-1, axes='XYZ'):\n dislin.axclrs(idx, 'ALL', axes)",
"def set(self, *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write 'wavepoints' for 'wavetable' in bunches of 'bunchsize'. The 'bunchsize' is device specific. Please refer to the controller manual. | def writewavepoints(pidevice, wavetable, wavepoints, bunchsize=None):
if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):
raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__)
wavepoints = wavepoints if isinstance(wavepoints, (list, set, tuple)) else [wavepoi... | [
"def _make_waves(self):\n wf = []\n wf.append(pigpio.pulse(1<<self.gpio, 0, self.t0))\n wf.append(pigpio.pulse(0, 1<<self.gpio, self.gap))\n self.pi.wave_add_generic(wf)\n self._amble = self.pi.wave_create()\n\n wf = []\n wf.append(pigpio.pulse(1<<self.gpio, 0, self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return dictionary of servo states or "False" if the qSVO command is not supported. | def getservo(pidevice, axes):
if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):
raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__)
axes = getaxeslist(pidevice, axes)
if not axes:
return {}
if pidevice.HasqSVO():
return pidevice.qS... | [
"def setservo(pidevice, axes, states=None, toignore=None, **kwargs):\n if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):\n raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__)\n\n if not pidevice.HasSVO():\n return False\n if not axes:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return dictionary of on target states for open or closedloop 'axes'. If qOSN is not supported open loop axes will return True. | def ontarget(pidevice, axes):
if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):
raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__)
axes = getaxeslist(pidevice, axes)
if not axes:
return {}
servo = getservo(pidevice, axes)
closedloopax... | [
"def axes_active(self) -> np.ndarray: # array[Axes]\n return self.axes.flat[:self.n_plots]",
"def q_states(self):\n return self._q_states",
"def _get_observable_state(self):\n observable_state = {}\n for var_name in self.observable_state_vars:\n if var_name == 'population_graph':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait until referencing of 'axes' is finished or timeout. | def waitonreferencing(pidevice, axes=None, timeout=300, predelay=0, postdelay=0, polldelay=0.1):
if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):
raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__)
axes = getaxeslist(pidevice, axes)
if not axes:
... | [
"def plot_finalize():\n global figure\n global axes\n\n plot_refresh()\n plt.ioff()\n plt.show()\n\n figure, axes = None, None",
"def check_on_redraw():\n # if not jobqueue.is_on_queue(REDRAW_QUEUE):\n # raise Exception(\"Illegal thread access (on queue %s).\" % jobqueue.get_curr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set servo of 'axes' to 'states'. Calls RNP for openloop axes and waits for servo operation to finish if appropriate. EAX is enabled for closedloop axes. | def setservo(pidevice, axes, states=None, toignore=None, **kwargs):
if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):
raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__)
if not pidevice.HasSVO():
return False
if not axes:
return True
... | [
"def enableaxes(self):\n debug('ControllerStartup.enableaxes()')\n if not self.pidevice.HasEAX() or self.prop['skipeax']:\n return\n for axis in self.pidevice.axes:\n try:\n self.pidevice.EAX(axis, True)\n except GCSError as exc:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait until all 'axes' are on phase. | def waitonphase(pidevice, axes=None, timeout=300, predelay=0, postdelay=0, polldelay=0.1):
if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):
raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__)
axes = getaxeslist(pidevice, axes)
if not axes:
re... | [
"def check_if_transforms_active(self):\n all_active = workflow.wait_for_transforms()\n\n if all_active:\n self.status_text.append(\"Found expected transforms\")\n workflow.setup_plus_remote(self.connector)\n workflow.prepare_probe_pivot_cal()\n\n self.ctk_pi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait until all macros are finished, then query and raise macro error. | def waitonmacro(pidevice, timeout=300, predelay=0, polldelay=0.1):
if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):
raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__)
maxtime = time() + timeout
waitonready(pidevice, timeout=timeout, predelay=predela... | [
"def wait_until_ready() -> None:\n no_data_counter = 0\n retry_pattern_pos = 0\n while True:\n status = self.connection.get_query_status(sfqid)\n if not self.connection.is_still_running(status):\n break\n if status == Q... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call MOV with 'axes' and 'values' and wait for motion to finish. | def moveandwait(pidevice, axes, values=None, timeout=300):
if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice):
raise TypeError('Type %s is not supported!' % type(pidevice).__name__)
if not axes:
return
pidevice.MOV(axes, values)
if isinstance(axes, dict):
axes = l... | [
"def move(self, axis, dist):\n t = self.moveTime\n N = self.moveSamples\n # read initial position for all channels\n texts = [getattr(self, ax + \"Label\").text()\n for ax in self.activeChannels]\n initPos = [re.findall(r\"[-+]?\\d*\\.\\d+|[-+]?\\d+\", t)[0] for t ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test ability to generate csv with simple input data. | def test_csv_simple_input(self):
# Mix of integer and string data. Ensure that commas and
# quotes are escaped properly.
data = [
{
'name': 'Normal string',
'item_num': 1,
},
{
'name': 'String, with, commas',
... | [
"def test_add_csv(self):\n pass",
"def test_list_csv(self):\n pass",
"def test_write_data_in_csv(self):\n expected = [[\"uno\", \"dos\", \"tres\"], [\"cuatro\", \"cinco\", \"seis\"]]\n CsvOperations.write_data(\"test.csv\", expected)\n self.assertEqual(CsvOperations.read_data(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that unicode cell values are converted correctly to csv. | def test_csv_with_unicode(self):
data = [
{
'name': 'Normal string',
'item_num': 1,
},
{
'name': u'String with ' + unichr(0x16c) + ' char',
'item_num': 2,
},
]
table = TableReportFor... | [
"def test_unicode_with_csv():\n data = [['观音', '1'], ['Ποσειδῶν', '456']]\n headers = ['letters', 'number']\n output = delimited_output_adapter.adapter(data, headers)\n assert \"\\n\".join(output) == dedent('''\\\n letters,number\\n\\\n 观音,1\\n\\\n Ποσειδῶν,456''')",
"def test_to_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure that excludesomecolumnsfromreport works. | def test_exclude_from_report(self):
data = [
{
'name': 'page 1',
'item_num': 1,
},
{
'name': 'page 2',
'item_num': 2,
},
]
class TableWithExclude(TableReportForTesting):
c... | [
"def test_exclude_cols(self):\n filepath = op.join(op.abspath(op.dirname(__file__)), \"testdata\",\n \"iris.csv\")\n df = pd.read_csv(filepath)\n specs = {\"data\": {'exclude_columns': ['Species']}}\n with DummyProjectFactory(specs, df) as project:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test ability to generate excel output with simple input data. | def test_excel_simple_input(self, extension='xls'):
excel_support = getattr(settings, 'EXCEL_SUPPORT', django_tables2_reports.utils.get_excel_support())
response = self.table.treatement_to_response(
self.table.as_csv(HttpRequest()),
report_format='xls')
self.assertEqual(r... | [
"def test_generate_sample_sheet(self):\n pass",
"def generate_excel_report(dashes):\r\n pass",
"def test_export_spreadsheet(self):\r\n client = self.getClient()\r\n if client:\r\n exp = [['#SampleID', 'DOB'],\r\n ['#Example mapping file for the QIIME analysis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a list of vertices and corresponding weights and returns the list of vertices resulting from the weighted average | def averageCurve(vertices, weights,a):
weightedCurve = [[PVector.mult(j,i[0]) for j in i[1]]
for i in zip(weights,vertices)]
average = [averageVertices(i,weights,a) for i in zip(*weightedCurve)]
return average | [
"def _weightedAverage(list_):\n\n\t\taccum = [0, 0]\n\n\t\tfor point, weight in list_:\n\n\t\t\taccum[0] += point[0] * weight\n\t\t\taccum[1] += point[1] * weight\n\n\t\ttotalWeight = sum([weight for point, weight in list_])\n\n\n\t\tif totalWeight == 0:\n\t\t\t\n\t\t\treturn (0, 0)\n\n\n\t\taccum[0] /= float(total... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads knowledge base to memory | def load_knowledge_base():
knowledge_base = {}
with open('knowledge_base.json') as f:
knowledge_base = json.load(f)
return knowledge_base | [
"def load_knowledge(self):\n MemoryManager.load_memory(self.knowledge_file)",
"def load_knowledge(self):\n try:\n file_name = dirname(__file__) + \"/model/data.ab\"\n self.EventsDatabase = load(open(file_name, 'rb'))\n #tmp = load(open(file_name, 'rb'))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get recording's size in seconds | def get_recording_size(file_name):
recording_size = check_output(
["mp3info", "-p", "%m:%s\n", "{}".format(file_name)]).decode("utf-8")
print("Recording size:", str(recording_size))
minutes_seconds = (int(recording_size.split(":")[0]) * 60)
seconds = int(recording_size.split(":")[1].replace("\n... | [
"def audio_recording_size_bytes(self):\n return self._audio_recording_size_bytes",
"def audio_recording_duration_seconds(self):\n return self._audio_recording_duration_seconds",
"def record_duration(self):\n return self.config.get('record_duration', 5)",
"def get_length(self):\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that webhook returns 500 for unkown action | def test_webhook_unkown_action(self):
event = {
"body": json.dumps({
"queryResult": {
"action": "1manage_bmi"
}})
}
context = {}
resp = webhook(event, context)
self.assertEqual(resp["statusCode"], 500)
self.a... | [
"def test_unsupported_action(self):\r\n self.xmodule.verify_oauth_body_sign = Mock()\r\n request = Request(self.environ)\r\n request.body = self.get_request_body({'action': 'wrongAction'})\r\n response = self.xmodule.grade_handler(request, '')\r\n real_response = self.get_response... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that webhook return 500 for empty body/action in event | def test_webhook_empty_event(self):
event = {
'body': json.dumps({})
}
context = {}
resp = webhook(event, context)
self.assertEqual(resp["statusCode"], 500)
self.assertEqual(resp["body"], json.dumps({})) | [
"def test_webhook_unkown_action(self):\n event = {\n \"body\": json.dumps({\n \"queryResult\": {\n \"action\": \"1manage_bmi\"\n }})\n }\n context = {}\n resp = webhook(event, context)\n self.assertEqual(resp[\"statusCode... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates surface area of square | def square_surface_area(a):
return (a*a) | [
"def compute_surface_area(self):\n return np.sum(self._find_triangle_areas())",
"def surface_area(self) -> FLOAT:\n\t\td = (self.pMax - self.pMin).view(Vector)\n\t\treturn 2. * (d.x * d.y + d.x * d.z + d.y * d.z)",
"def calc_inner_surface_area(self):\n return pi * self.inner_dia * self.length",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates total circumferences of a rectangle | def rectangle_circumference(a,b):
return (2*(a+b)) | [
"def circumference(self):\n return self.width + self.height",
"def circumference(self):\n # Define doctests for circumference method:\n # Define circumference functionality:\n return round((2 * math.pi * self.radius),2)",
"def circumference(r):\r\n return 2 * math.pi * r",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculates surface area of a rectangle | def rectangle_surface_area(a,b):
return (a*b) | [
"def total_surface_area(length, width, height):\n front_back = area_of_rectangle(length, width) * 2\n sides = area_of_rectangle(width, height) * 2\n top_bottom = area_of_rectangle(length, height) * 2\n return front_back + sides + top_bottom",
"def surface_area(self) -> FLOAT:\n\t\td = (self.pMax - sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calcualtes surface area of a circle | def circle_surface_area(a):
return (a*a*math.pi) | [
"def surface_area(self) -> float:\n return 4 * np.pi * self.radius**2",
"def circle_area(circle):\n return pi * circle.radius * circle.radius",
"def circle_area(radius):\n return pi*radius*radius",
"def area_of_circle(radius):\n return math.pi * radius ** 2",
"def area_of_circle(radius):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If there are X company families currently running plan b, AND config throttles to Y company families, AND X is less than Y, then we should find Y X company families to run. | def test_get_company_families_in_need_of_plan_b_positive(self):
self.mock.max_simultaneous_plan_bs = 5
self.mock.currently_running_companies = [[1, "run_id"], [2, "run_id"], [3, "run_id"]]
needs_plan_b_companies = [[4, None], [5, None], [6, None]]
expected_number_of_tasks_to_create = 4
... | [
"def test_get_company_families_in_need_of_plan_b_negative(self):\n self.mock.max_simultaneous_plan_bs = 5\n self.mock.currently_running_companies = [[1, \"run_id1\"], [2, \"run_id2\"], [3, \"run_id3\"], [4, \"run_id4\"], [5, \"run_id5\"]]\n self.mock.company_families_in_need_of_plan_b = None\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If there are X company families currently running plan b, AND config throttles to Y company families, AND Y is less than or equal Y, then we should find exactly 0 company families to run. | def test_get_company_families_in_need_of_plan_b_negative(self):
self.mock.max_simultaneous_plan_bs = 5
self.mock.currently_running_companies = [[1, "run_id1"], [2, "run_id2"], [3, "run_id3"], [4, "run_id4"], [5, "run_id5"]]
self.mock.company_families_in_need_of_plan_b = None
self.mox.Re... | [
"def test_get_company_families_in_need_of_plan_b_positive(self):\n self.mock.max_simultaneous_plan_bs = 5\n self.mock.currently_running_companies = [[1, \"run_id\"], [2, \"run_id\"], [3, \"run_id\"]]\n needs_plan_b_companies = [[4, None], [5, None], [6, None]]\n expected_number_of_tasks_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets alignment alphabet for codon alignment. Only nucleotide alphabet is accepted. Raise an error when the type of alphabet is incompatible. | def get_codon_alphabet(alphabet, gap="-", stop="*"):
from Bio.Alphabet import NucleotideAlphabet
if isinstance(alphabet, NucleotideAlphabet):
alpha = alphabet
if gap:
alpha = Gapped(alpha, gap_char=gap)
if stop:
alpha = HasStopCodon(alpha, stop_symbol=stop)
el... | [
"def alphabet(self):\n return SequenceAlphabets.get(self.type)",
"def _guess_consensus_alphabet(self, ambiguous):\n # Start with the (un-gapped version of) the alignment alphabet\n a = Alphabet._get_base_alphabet(self.alignment._alphabet)\n\n # Now check its compatible with all the res... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Choose which generator and discriminator architecture to use by uncommenting one of these lines. | def GeneratorAndDiscriminator():
# Baseline (G: DCGAN, D: DCGAN)
return ResnetGenerator, DCGANDiscriminator
# No BN and constant number of filts in G
# return WGANPaper_CrippledDCGANGenerator, DCGANDiscriminator
# 512-dim 4-layer ReLU MLP G
# return FCGenerator, DCGANDiscriminator
# No n... | [
"def GeneratorAndDiscriminator():\n\n # ResNet Generator and Discriminator\n if FLAGS.architecture == \"ResNet\":\n return ResNetGenerator, ResNetDiscriminator\n\n else:\n raise Exception('You must choose an architecture!')",
"def GeneratorAndDiscriminator():\n\n # Fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for add_relation_type | def test_add_relation_type(self):
pass | [
"def test_add_relation_types(self):\n pass",
"def test_change_relation_type(self):\n pass",
"def test_change_relation_types(self):\n pass",
"def test_get_relation_type(self):\n pass",
"def test_resource_relation_resource_add_relation_post(self):\n pass",
"def test_find_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for add_relation_types | def test_add_relation_types(self):
pass | [
"def test_add_relation_type(self):\n pass",
"def test_change_relation_types(self):\n pass",
"def test_find_relation_types(self):\n pass",
"def test_change_relation_type(self):\n pass",
"def test_get_relation_type(self):\n pass",
"def test_remove_relation_types(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for change_relation_type | def test_change_relation_type(self):
pass | [
"def test_change_relation_types(self):\n pass",
"def test_add_relation_type(self):\n pass",
"def test_get_relation_type(self):\n pass",
"def test_add_relation_types(self):\n pass",
"def test_remove_relation_type(self):\n pass",
"def test_remove_relation_types(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for change_relation_types | def test_change_relation_types(self):
pass | [
"def test_change_relation_type(self):\n pass",
"def test_add_relation_types(self):\n pass",
"def test_add_relation_type(self):\n pass",
"def test_remove_relation_types(self):\n pass",
"def test_get_relation_type(self):\n pass",
"def test_find_relation_types(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for find_relation_types | def test_find_relation_types(self):
pass | [
"def test_get_relation_type(self):\n pass",
"def test_add_relation_types(self):\n pass",
"def test_add_relation_type(self):\n pass",
"def test_change_relation_types(self):\n pass",
"def test_change_relation_type(self):\n pass",
"def test_remove_relation_types(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for get_relation_type | def test_get_relation_type(self):
pass | [
"def test_find_relation_types(self):\n pass",
"def test_change_relation_type(self):\n pass",
"def test_add_relation_type(self):\n pass",
"def test_change_relation_types(self):\n pass",
"def test_add_relation_types(self):\n pass",
"def getRelationType( self ):\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for remove_relation_type | def test_remove_relation_type(self):
pass | [
"def test_remove_relation_types(self):\n pass",
"def test_resource_relation_resource_remove_relation_delete(self):\n pass",
"def test_resource_relation_resource_remove_relation_delete_0(self):\n pass",
"def test_change_relation_type(self):\n pass",
"def test_change_relation_types... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for remove_relation_types | def test_remove_relation_types(self):
pass | [
"def test_remove_relation_type(self):\n pass",
"def test_change_relation_types(self):\n pass",
"def test_change_relation_type(self):\n pass",
"def test_add_relation_types(self):\n pass",
"def test_resource_relation_resource_remove_relation_delete_0(self):\n pass",
"def t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
After the applications have been sent to Ahjo, the handlers should not be able to modify the applications. If the batch is returned without decision (as might theoretically happen), then the handlers may need to make changes again. | def applications_can_be_modified(self):
return self.status in [
ApplicationBatchStatus.DRAFT,
ApplicationBatchStatus.RETURNED,
] | [
"def test_bogus_applications_parameter_handled(self):\n # Check status quo ante.\n self.assertEqual(Application.objects.count(), 2)\n self.assertEqual(\n Application.objects.filter(status=Application.APPROVED).count(), 2\n )\n\n # Post a completely invalid app pk.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the template_name of this UpdateSmtpTemplate. | def template_name(self, template_name):
self._template_name = template_name | [
"def template_name(self, template_name):\n self._template_name = template_name",
"def tpl_name(self, tpl_name):\n self._tpl_name = tpl_name",
"def workflow_template_name(self, workflow_template_name):\n\n self._workflow_template_name = workflow_template_name",
"def template_group_name(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the html_content of this UpdateSmtpTemplate. | def html_content(self, html_content):
self._html_content = html_content | [
"def set_html(self, in_html):\n try:\n payload = self.msg.get_payload()\n payload[1] = MIMEText(in_html, 'html')\n self.msg.set_payload(payload)\n except TypeError:\n print(\"ERROR: \"\n \"Payload is not a list. Specify an HTML message with ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the html_url of this UpdateSmtpTemplate. | def html_url(self, html_url):
self._html_url = html_url | [
"def html(self, html):\n\n self._html = html",
"def html_url(self):\n return self._html_url",
"def set_html(self, in_html):\n try:\n payload = self.msg.get_payload()\n payload[1] = MIMEText(in_html, 'html')\n self.msg.set_payload(payload)\n except Typ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the reply_to of this UpdateSmtpTemplate. | def reply_to(self, reply_to):
self._reply_to = reply_to | [
"def set_reply_to(self, address):\n if not self.validate_email_address(address):\n raise Exception(\"Invalid email address '%s'\" % address)\n self._reply_to = address",
"def reply_to_email_address(self, val: EmailAddress):\n self._reply_to = val",
"def reply_to_email_address(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the attachment_url of this UpdateSmtpTemplate. | def attachment_url(self, attachment_url):
self._attachment_url = attachment_url | [
"def attachments_uri(self, attachments_uri):\n\n self._attachments_uri = attachments_uri",
"def attachment_id(self, attachment_id):\n\n self._attachment_id = attachment_id",
"def avatar_url(self, avatar_url):\n\n self._avatar_url = avatar_url",
"def attachment_file_name(self, attachment_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the is_active of this UpdateSmtpTemplate. | def is_active(self, is_active):
self._is_active = is_active | [
"def is_active(self, is_active):\n \n self._is_active = is_active",
"def active(self, active):\n\n self._active = active",
"def is_active(self, value):\n self.__is_active = value",
"def _set_active(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load an OpenVINO model for inference from directory. | def _load(path, device=None, cache_dir=None, shapes=None):
status = KerasOpenVINOModel._load_status(path)
if status.get('xml_path', None):
xml_path = Path(status['xml_path'])
invalidInputError(xml_path.suffix == '.xml',
"Path of openvino model must b... | [
"def _load(path):\n status = KerasOpenVINOModel._load_status(path)\n if status.get('xml_path', None):\n xml_path = Path(status['xml_path'])\n invalidInputError(xml_path.suffix == '.xml',\n \"Path of openvino model must be with '.xml' suffix.\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A VIEW token contract. | def token(chain: BaseChain) -> Contract:
return deploy_contract(chain, 'DSToken', args=['VIEW']) | [
"def view(self) -> 'outputs.ViewDefinitionResponse':\n return pulumi.get(self, \"view\")",
"def UserToken(self) -> object:",
"def odb_token():\n return genToken()",
"def oov_token(self):\n return None",
"def __require_permission_view(self):\n permission = codechecker_api_shared.ttype... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A blank ViewlySeedSale contract. | def sale(chain: BaseChain, token: Contract, beneficiary) -> Contract:
args = [token.address, beneficiary]
seed_sale = deploy_contract(chain, 'ViewlySeedSale', args=args)
token.transact().setOwner(seed_sale.address)
return seed_sale | [
"def test_deposit_stellar_no_trustline(acc1_usd_deposit_transaction_factory):\n deposit = acc1_usd_deposit_transaction_factory()\n deposit.status = Transaction.STATUS.pending_anchor\n deposit.save()\n assert not create_stellar_deposit(deposit.id)\n assert (\n Transaction.objects.get(id=deposit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A running ViewlySeedSale contract. | def running_sale(chain: BaseChain, token: Contract, sale) -> Contract:
sale.transact().startSale(DURATION, BLOCK_OFFSET)
chain.wait.for_block(sale.call().startBlock())
return sale | [
"def sale(chain: BaseChain, token: Contract, beneficiary) -> Contract:\n args = [token.address, beneficiary]\n seed_sale = deploy_contract(chain, 'ViewlySeedSale', args=args)\n token.transact().setOwner(seed_sale.address)\n return seed_sale",
"def test_scaffold():\n MyScaffoldContract(\"config\")",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a new ocpnplugins.xml. | def generate(sourcedir, destfile, version, date):
tree = ET.Element('plugins')
version_elem = ET.SubElement(tree, "version")
version_elem.text = version
date_elem = ET.SubElement(tree, "date")
date_elem.text = \
date if date else datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
for pat... | [
"def __generate_plugin_file(self):\n __root = ET.Element(\"plugin\", {\n \"id\": \"org.dita.specialization.\" + self.plugin_name\n })\n if self.plugin_version != None:\n ET.SubElement(__root, \"feature\", {\n \"extension\": 'package.version',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove automations for a Tasmota device. | async def async_remove_automations(hass, device_id):
await device_trigger.async_remove_triggers(hass, device_id) | [
"def clear_all_devices():\n adapter = get_adapter()\n for key in devices_by_adr.keys():\n device = get_device(key)\n try:\n adapter.RemoveDevice(device) \n except DBusException:\n print(\"could not remove\", device)",
"def remove_test_devices():\n for device in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle the removal of a device. | async def async_device_removed(event):
if event.data["action"] != "remove":
return
await async_remove_automations(hass, event.data["device_id"]) | [
"def device_removed(self, device):\n for device_entity in self._device_registry[device.ieee]:\n self._hass.async_create_task(device_entity.async_remove())\n if device.ieee in self._events:\n self._events.pop(device.ieee)",
"def remove(self, device_id):\n raise NotImpleme... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Discover and add a Tasmota device automation. | async def async_discover(tasmota_automation, discovery_hash):
if tasmota_automation.automation_type == AUTOMATION_TYPE_TRIGGER:
await device_trigger.async_setup_trigger(
hass, tasmota_automation, config_entry, discovery_hash
) | [
"def test_add_device(self):\n\n pass",
"def flash_tasmota(self, flash_mode, serial_port):\n # Make sure device is tasmota\n if self.software != 'tasmota':\n print('{f_name} is {software}, not tasmota'.format(**self))\n return(False)\n if current_tasmota_version !=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns average color distance between pixels in originalPixels list and newPixels list | def checkQualityOfSection(originalPixels, newPixels):
totalDistance = 0
numPixels = 0
for r in range(originalPixels.shape[0]):
for c in range(originalPixels.shape[1]):
if r == 0 or r == originalPixels.shape[0] - 1 or c == 0 or c == originalPixels.shape[1] - 1:
continue
... | [
"def distance(rgb1, rgb2):\n diffs = np.array(rgb1) - np.array(rgb2)\n return math.sqrt(np.sum(diffs**2))",
"def image_rms_diff(src, dest):\n total = 0\n width, height = src.size\n for x in range(width):\n for y in range(height):\n s_r, s_g, s_b, s_a = src.getpixel((x, y))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the price of this membership as a string of pounds and pence. | def price_pounds(self):
price = '{0:03d}'.format(self.price)
return price[:-2] + '.' + price[-2:] | [
"def formatted_price(self) -> str:\n return fmt_money(self.price)",
"def get_price(self):\n return self.price",
"def display_price(self):\n return '$ '+str(self.price)",
"def price(self):\n if self.on_sale():\n return self.sale_price\n elif self.has_price():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reports API calls in highest to lowest usage order. | def stats():
# Log all API requests
exception = log_api()
if exception:
return jsonify({'error': exception}), HTTPStatus.INTERNAL_SERVER_ERROR
try:
data = redis.zrevrangebyscore(
REDIS_LOG_KEY_NAME,
REDIS_INT64_MAX,
0,
withscores=True)
... | [
"def test_api_usage(self) -> None:\n api_usage: ApiUsage = connections[sf_alias].connection.api_usage\n self.assertGreater(api_usage.api_usage, 0)\n self.assertGreater(api_usage.api_limit, 5000)",
"def get_api_status():\n\tlstatus = api.rate_limit_status()['resources']\n for r in lstat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log the API request in redis. | def log_api():
try:
redis.zincrby(REDIS_LOG_KEY_NAME, 1, request.path)
except RedisError as exc:
return exc | [
"def on_request_log_redis_stats(event):\n redis = get_redis(event.request)\n log_redis_statistics(redis)",
"def _log(self):\r\n self.application.log_request(self)",
"def log_to_api(self):\n if self.entries:\n try:\n headers = {'Content-Type': 'application/json'}\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The decorator avoid print statements to print messages on console. | def disable_print_statements_on_console(func):
@wraps(func)
def wrap(*args, **kw):
suppress_text = io.StringIO()
sys.stdout = suppress_text
result = func(*args, **kw)
sys.stdout = sys.__stdout__
return result
return wrap | [
"def suppress() -> None:\n def _printnull(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False) -> None:\n pass\n\n builtins.print = _printnull",
"def disable():\n builtins.print = print_orig",
"def silence_print(is_master):\n import builtins as __builtin__\n\n builtin_print = __buil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is a helper to create `PipelineML` object directly from two Kedro `Pipelines` (one of training and one of inference) . | def pipeline_ml_factory(
training: Pipeline,
inference: Pipeline,
input_name: str = None,
conda_env: Optional[Union[str, Path, Dict[str, Any]]] = None,
model_name: Optional[str] = "model",
model_signature: Union[ModelSignature, str, None] = "auto",
**kwargs
) -> PipelineML:
pipeline = P... | [
"def create_pipelines(seed, verbose=1):\n\n models = [\n ('LR', LogisticRegression()),\n ('LDA', LinearDiscriminantAnalysis()),\n ('KNN', KNeighborsClassifier()),\n ('CART', DecisionTreeClassifier(random_state=seed)),\n ('NB', GaussianNB()),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure disabled_options values are part of the list of options | def _validate_disabled_options(self, proposal) -> List[str]:
if proposal.value is None or not proposal.value:
return []
proposal_diff = set(proposal.value).difference_update(set(self._options_labels))
assert (
not proposal_diff
), f"Invalid passed options for 'dis... | [
"def valid_options(self) -> list:\n raise NotImplementedError()",
"def validate_options(self) -> None:\r\n pass",
"def allow_options(self, model, field, options):\n options = COMMON_OPTIONS + options\n\n for (k, v) in field.get(\"options\", {}).items():\n allowed = False\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Put options into desired grouping, updating `options` | def _set_grouping(self, change) -> None:
grouping = self._grouping_full
self.options = self._flat_groupings(grouping)
self.set_trait(
"_grouping_labels",
tuple(
[
(header, tuple([_[0] for _ in options]))
for header, ... | [
"def modify_option_group(OptionGroupName=None, OptionsToInclude=None, OptionsToRemove=None, ApplyImmediately=None):\n pass",
"def condition_group_options(self):\n if \"no-groups\" in self.options and self.options[\"no-groups\"]:\n self.options[\"groups\"] = []\n if \"exclude-groups... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get group headers from self._grouping_labels | def _group_headers(self) -> List[str]:
return [_[0] for _ in self._grouping_labels] | [
"def get_group_names(self):\r\n return self.groups.keys()",
"def get_group_names(self):\n return list(self._groups.keys())",
"def get_group_names(self):\n return [group.lg_name for group in self.groups]",
"def getGroups(self):\n side1Groups = self.side1Groups = {}\n side2Gro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return label,valuepair of grouping index. The index is expected to match `_flat_groupings`, i.e., the actual dropdown. | def _get_grouping_label_value(
self,
index: int,
grouping: Tuple[Tuple[str, Tuple[Tuple[str, Any]]]] = None,
) -> Tuple[str, Any]:
grouping = grouping if grouping is not None else self._grouping_full
res = self._flat_groupings(grouping)[index]
if not isinstance(res, ... | [
"def get_group_index(self, index):\n\n g_index = None\n for group in self.groups:\n if group[0] == index:\n g_index = group[1]\n break\n return g_index",
"def _get_group_index(self, index):\n\n g_index = 0\n for group in self.groups:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
mirror triples from endpoints according to resource paths specified in res_paths. Each resource path is a tuple consisting of a list of start resources and a list of patterns describing which edges to follow. A very simple example of a resource path may consist of just a start resource, e.g. | def mirror (self, res_paths):
self.start_time = time.time()
self.todo = []
self.done = set()
for res_path in res_paths:
resolved_paths = map(
lambda p:
map(
lambda p: (s... | [
"async def paths_from_src(\n src: str = Query(..., description=\"starting article\"),\n dsts: list[str] = Query(..., description=\"destination articles\"),\n db: Session = Depends(database.get_db),\n):\n paths: dict[str, Optional[ArticlePath]] = {}\n ppd = multi_target_bfs(db, src)\n for dst in ds... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new endpoint mirror helper with P2E (propert to entity mapping) support Like LDFMirror but fetches property entities as well. graph target RDFLib graph endpoints dict mapping host names to LDF endpoints, e.g. { | def __init__ (self, graph, endpoints, aliases, prefixes, p2e_mapper ):
self.p2e_mapper = p2e_mapper
super (LDFMirrorP2E, self).__init__(graph, endpoints, aliases, prefixes) | [
"def generate_proxy(classname, endpoints):\n # Replace path vars like (?<schemaname>.*) with {schemaname} for Retrofit's annotation\n var_pattern = re.compile(r\"\\{(\\w+)\\}\")\n\n helper_class = []\n found_key_array_parameter = False\n\n yield \"/*\"\n yield \" * This file is auto-generated by h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method fetches the latest .dmg from Jenkins. First, it checks the id of the latest build. Next, it fetches the artifacts from that build and saves the .dmg to the workspace. | def fetch_executable_from_jenkins():
base_job_url = os.environ.get('JENKINS_JOB_URL')
if not base_job_url:
error('Jenkins job URL for the builder is not specified.')
build_json = json.loads(requests.get('%s/api/json'
% base_job_url).text)
last_build = b... | [
"def fetch_exe_from_jenkins():\n base_job_url = os.environ.get(\"JENKINS_JOB_URL\")\n if not base_job_url:\n print \"Jenkins job URL for the builder is not specified.\"\n sys.exit(-1)\n\n build_json = json.loads(requests.get(\"%s/api/json\" % base_job_url).text)\n last_build = build_json['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a username and iterates over all of the animes, adding them to the csv file. | def profile(username):
link = "https://myanimelist.net/animelist/{}".format(username)
mal_soup = get_soup(link)
table = json.loads(mal_soup.find('table').get('data-items'))
print("\nRunning...\n")
for dic in table:
link = "https://myanimelist.net{}"
res = mal_get_all_info(link.format... | [
"def write_csv(user_data: dict, user_name: str, watch_type: str) -> None:\n with open(user_name + '_' + watch_type + '.csv') as user_csv:\n writer = csv.writer(user_csv, delimiter=',')\n for anime in user_data:\n writer.writerow([anime, user_data[anime]])",
"def append_to_csv(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the logger. The verbose_level should be in [0, 1, 2]. This won't return anything but will reconfigure the root logger. | def set_logger(verbose_level):
if verbose_level >= 2:
logging_level = logging.DEBUG
elif verbose_level == 1:
logging_level = logging.INFO
else:
logging_level = logging.ERROR
logging.basicConfig(level=logging_level,
stream=sys.stdout,
... | [
"def set_logger(verbose):\n\n level = 0\n if verbose == 1:\n level = logging.INFO\n elif verbose == 2:\n level = logging.DEBUG\n elif verbose == 3:\n level = logging.WARNING\n elif verbose == 4:\n level = logging.ERROR\n elif verbose == 5:\n level = logging.CRITI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert distributions to openTURNS. The list of distribution is converted to openTURNS objects. | def dists_to_ot(dists):
try:
dists = [eval('ot.' + dist, {'__builtins__': None},
{'ot': __import__('openturns')})
for dist in dists]
except (TypeError, AttributeError):
raise AttributeError('OpenTURNS distribution unknown.')
return dists | [
"def _convertToDistr(self, ws):\n alg = self.createChildAlgorithm('ConvertToDistribution')\n alg.setProperty('Workspace', ws)\n alg.execute()",
"def __convert_to_probabilities__(self, _list):\n # convert to probabilities\n _max = max(_list)\n _min = min(_list)\n pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert kernel to openTURNS. The kernel is converted to openTURNS objects. | def kernel_to_ot(kernel):
try:
kernel = eval('ot.' + kernel, {'__builtins__': None},
{'ot': __import__('openturns')})
except (TypeError, AttributeError):
raise AttributeError('OpenTURNS kernel unknown.')
return kernel | [
"def convert(context, cm_node, inputs, outputs):\n kernel_enum = {'linearKernel': 'LINEAR', 'polyKernel': 'POLY',\n 'rbfKernel': 'RBF', 'sigmoidKernel': 'SIGMOID', 'precomputedKernel': 'PRECOMPUTED'}\n kernel = cm_node.supportVectorClassifier.kernel\n kernel_val = kernel.W... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert kernel to scikitlearn. The kernel is converted to scikitlearn objects. | def kernel_to_skl(kernel):
try:
kernel = eval('kernels.' + kernel, {'__builtins__': None},
{'kernels': __import__('sklearn.gaussian_process.kernels',
fromlist=['kernels'])})
except (TypeError, AttributeError):
raise AttributeErro... | [
"def cast(obj: 'itkLightObject') -> \"itkLabelStatisticsImageFilterIF2ISS2 *\":\n return _itkLabelStatisticsImageFilterPython.itkLabelStatisticsImageFilterIF2ISS2_cast(obj)",
"def itkLabelStatisticsImageFilterISS2ISS2_cast(obj: 'itkLightObject') -> \"itkLabelStatisticsImageFilterISS2ISS2 *\":\n return _... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regresa las recomendaciones para "user", basándose en la información de MovieLens guardada en prefs | def userRec(user):
return recommendations.getRecommendations(prefs, user)[0:20] | [
"def getPreferencesForUser(self, modName: str, user: 'User'):\n # logger.debug('Self prefs: %s', self._prefs)\n prefs = {}\n for up in user.preferences.filter(module=modName): # type: ignore\n prefs[up.name] = up.value\n for p in self._prefs[modName]['prefs']:\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Проверяет упорядоченность массива A по возрастанию, если ascending=True или по убыванию, если ascending=False Алгоритм проверяет за O(len(A)) | def check_sorted(A, ascend=True):
flag = True
s = 2*int(ascend) - 1 # == 1 если ascend=True или -1 если ascend=False
for i in range(0, len(A)-1):
if s*A[i] > s*A[i+1]: # s разворачивает знак при сортировке по убыванию
flag = False
break
return flag | [
"def is_sorted(a):\n\tfor i in range(1,len(a)):\n\t\tif _less(a[i], a[i-1]):\n\t\t\treturn False\n\treturn True",
"def is_sorted(A: list) -> bool:\r\n\r\n # If it's None, return None\r\n if A is None:\r\n return None\r\n\r\n # If the length is 0 or 1, then\r\n # it's sorted\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs Friedman's test. G array of arrays(groups). First group is G[0] each group mus have the same number of elements! | def friedman(G, alpha = 0.05, ignoreties = False, onetailed = True, verbose = True):
nclasses = len(G) # number of groups
nblocks = len(G[0])
Rank = [0]* nclasses # ranks array.
for j in range(nblocks):
# get the rows.
row = []
for i in r... | [
"def test_ford_fulkerson_algo() -> np.ndarray:\r\n res = ford_fulkerson_algorithm(np.array(ex_sample_graph), 0, 10)\r\n print(\"Result: \")\r\n print(res)\r\n return res",
"def test_fg():\n\n # Note: doesn't assert fg itself, as it return false when group_results are empty\n # This is due to th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes old file from filesystem when corresponding `ProductImage` object is updated with new file. | def auto_delete_file_on_change(sender, instance, **kwargs):
if not instance.pk:
return False
try:
old_image = ProductImage.objects.get(pk=instance.pk).image
except ProductImage.DoesNotExist:
return False
new_image = instance.image
if not old_image == new_image:
... | [
"def delete_product_image(self):\n self.product.image.delete()",
"def auto_delete_file_on_change(sender, instance, **kwargs):\n if not instance.pk:\n return False\n\n try:\n old_file = Variant.objects.get(pk=instance.pk).image\n except Variant.DoesNotExist:\n return False\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initiates a scan request to the scanning thread calculates the scan position based on self.num_points_done | def send_request(self):
x_pos = self.x_pos_list[self.num_points_done % self.x_num]
y_pos = self.y_pos_list[self.num_points_done // self.x_num]
# zigzag scanning to minimize backlash
if np.where(self.y_pos_list == y_pos)[0][0] % 2 == 1: # for even-numbered rows
... | [
"def scan_points(self, offsets, home_point):",
"def scan(self):\n for angle in range(self.MIDPOINT-400, self.MIDPOINT+401, 100):\n self.servo(angle)\n self.scan_data[angle] = self.read_distance()\n #sort the scan data for easier analysis\n self.scan_data = OrderedDict(so... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper for netstring_read and netstring_readfd. | def _netstring_read(read_func, max_length):
length_str = read_length(read_func)
length = int(length_str)
if max_length and length > max_length:
raise ValueError("Payload is too large: %s" % length)
payload = read_func(length)
tag_byte = read_func(1)
# dump_line can emit a newline.
if tag_byte != ',' ... | [
"def netstring_readfd(fd, max_length=0):\n read_func = lambda length: os.read(fd, length)\n return _netstring_read(read_func, max_length)",
"def ReadNetstring(sock):\n\t# First attempt to read the length.\n\tsize = ''\n\twhile True:\n\t\ttry:\n\t\t\tc = sock.recv(1)\n\t\texcept socket.error, e:\n\t\t\tif e[0] =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a byte string from a file descriptor. | def netstring_readfd(fd, max_length=0):
read_func = lambda length: os.read(fd, length)
return _netstring_read(read_func, max_length) | [
"def read_c_string(fd: BinaryIO) -> bytes:\n string = bytearray()\n while True:\n byte = fd.read(1)\n if not byte or byte == b'\\0':\n return bytes(string)\n string += byte",
"def bread(fd # type: Union[bytes, str, pathlib.Path, pathlib.PurePath, TextIO, BinaryIO]\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CCG = ColumnandConstraint Generation ColumnandConstraint Generation algorithm. Iteration between the MP and SP until convergence criteria is reached. | def ccg_algo(dir:str, tol: float, gamma: int, pv_min: np.array, pv_max: np.array, engagement: np.array, solver_param: dict, day:str, log:bool=False, printconsole:bool=False, warm_start:bool=False, M_neg:float=None):
# Compute the maximal deviation between the max and min PV uncertainty set bounds
max_dev = pv_... | [
"def CBF_GEN_conic(dim,mc,*args:(float,float,float,{float, np.array})):\n\n def vec_u(u):\n if(type(u)==int):\n res = np.zeros((dim,1))\n res[u] = 1\n return res\n assert(len(u)==dim)\n return np.array(u).reshape((-1,1))\n args = [(a,b,c,vec_u(u)) for (a,b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this method creates a jobprocess instance and all its tasks, however if the job its created as finished it will not create any task, example the time has come for start a job but a previous instance is still running and the process its configured for not overlap the new instance will be created as finished | def create(cls, process, *args, **kwargs):
job = cls(process=process, *args, **kwargs)
job.save()
ret_tasks = []
if job.status != 'finished':
tasks = Task.objects.filter(is_active=True, process=process)
ret_tasks = [JobTask.create(job, t) for t in tasks]
... | [
"def new_process(self, job_info):\n if int(job_info['mem_required']) > self.memory.mem_size:\n self.memory_full = True\n else:\n self.job_scheduling_queue.add(Process(**job_info))\n self.system_status_list.job_scheduling_queue_list.add(Process(**job_info))",
"def cre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform random distortions on an image. | def distort_image(image):
# Randomly flip horizontally.
with tf.name_scope("flip_horizontal", values=[image]):
image = tf.image.random_flip_left_right(image)
# Randomly distort the colors based on thread id.
with tf.name_scope("distort_color", values=[image]):
image = tf.image.random_brightness(image, ... | [
"def distort_image(self, image):\n image_size = 32\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n print(\"Apply random cropping\")\n image = tf.image.resize_image_with_crop_or_pad(image, image_size + 4, image_size + 4)\n image = tf.random_crop(image, [image_size... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a nonfunctioning pipe. | def __init__(self):
self._read_pipe_name = ''
self._write_pipe_name = ''
self._thread: Optional[Thread] = None | [
"def __init__(self, pipes, args):\n super(Karma, self).__init__(pipes)",
"def _setup_pipe(self):\r\n self.test_id_read_fd, self.test_id_write_fd = os.pipe()\r\n\r\n fcntl.fcntl(self.test_id_read_fd, fcntl.F_SETFL, os.O_NONBLOCK)\r\n self.epoll = select.epoll()\r\n self.epoll.reg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A static method used to create a pipe between two processes. On POSIX systems, it creates a named pipe using `os.mkfifo`. On Windows platforms, it starts a backgroud thread that transfars data from the writer to the reader process it is connected to. | def create_ipc_pipe(temp_dir: str, suffix: str = '') -> 'Pipe':
unique_name = str(uuid.uuid4()) + suffix
pipe = Pipe()
if sys.platform == 'win32':
import win32pipe # type: ignore
pipe_name = '-nt-shaka-' + unique_name
# The read pipe is connected to a writer process.
pipe._read_pip... | [
"def _make_fifo(self):\n if os.path.exists(self.fifo_path):\n os.remove(self.fifo_path)\n os.mkfifo(self.fifo_path)",
"def PipeConnection(incoming, outgoing):\r\n return Connection(Channel(PipeStream(incoming, outgoing)))",
"def pipe(logger=None):\n with plock:\n (p1,p2)=os... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a Pipe object whose read or write end is a path to a file. | def create_file_pipe(path: str, mode: str) -> 'Pipe':
pipe = Pipe()
# A process will write on the read pipe(file).
if mode == 'w':
pipe._read_pipe_name = path
# A process will read from the write pipe(file).
elif mode == 'r':
pipe._write_pipe_name = path
else:
raise RuntimeErr... | [
"def io_pipe():\n r_fd, w_fd = os.pipe()\n with io.open(r_fd, 'rb', 0) as r, \\\n \t io.open(w_fd, 'wb', 0) as w:\n \tyield r, w",
"def pipe(required=True, mode='r'):\n def validate(ctx, param, value):\n if value is not None:\n return click.open_file(value, mode=mode, lazy=True), ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |