query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Called when a configuration is added to the collector | def added(self, configuration): | [
"def _config_changes_handler(self, tracker_changed_event):\n tracker = self._trackers_api.get_trackers(\n tracker_id=tracker_changed_event.tracker_id)[0]\n tracker.set_storage(self.storage)\n self.scheduler.add_tracker(tracker)",
"def configurable(self, configur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when a configuration is updated in collector | def updated(self, newConfiguration): | [
"def configuration_changed(self, config_changes):\n # TODO: implement",
"def _on_config_changes(self, **kwargs) -> None:\n self._needs_recalc = True\n self._gen_sync.mark_updated()",
"def _config_changes_handler(self, tracker_changed_event):\n tracker = self._trackers_api.get_trackers(\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a new statistic to the service. Throws an exception if the statistic already exists. | def addStatistic(self, name, type): | [
"def add_statistic_value(sim_info: SimInfo, statistic_id: Union[int, CommonStatisticId], value: float, add_dynamic: bool=True, add: bool=True) -> bool:\n if sim_info is None:\n return False\n if CommonSimStatisticUtils.is_statistic_locked(sim_info, statistic_id):\n return False\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the statistic object for the given name. | def getStatistic(self, name): | [
"def get(cls, service, name=\"\", option_=\"\") :\n\t\ttry :\n\t\t\tobj = systembw_stats()\n\t\t\tif not name :\n\t\t\t\tresponse = obj.stat_resources(service, option_)\n\t\t\treturn response\n\t\texcept Exception as e:\n\t\t\traise e",
"def get(self, name):\n metric = MetricModel.find_by_name(name)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set up a worker type | def setWorkerClass(self, iCollectorWorker): | [
"def set_worker_count(self, count: int) -> \"TFClusterConfig.Builder\":\n self.add_node_type(\"worker\", count)\n return self",
"def createGuiWorker() -> ghidra.util.worker.Worker:\n ...",
"def on_worker_starts(self):\n pass",
"def set_msg_worker_fabric(self, msg):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disconnect from target device | def disconnect(self, device): | [
"def disconnect(self):\n\n c.cso_logger.info('[{0}][{1}]: Disconnect from device'.format(self.target['name'], 'Disconnect'))\n message = {'action': 'update_task_status', 'task': 'Disconnect', 'uuid': self.target['uuid'],\n 'status': 'Disconnecting...'}\n self.emit_message(mess... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function to get a filter function to filter the devices for which to generate configs. The returned filter function must be suitable for use with the 'filter' builtin. 'options' is a dictionary of potential control options for the filter. | def getFilter(options): | [
"def perfsonar_client_filters(options):\n\n start, end = get_start_and_end_times(options)\n\n filters = ApiFilters()\n filters.source = options.src\n filters.destination = options.dest\n filters.measurement_agent = options.agent\n filters.event_type = options.type\n filters.time_start = calenda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the modelnet path from a routefile from pair[0] to pair[1] We use grep because routefiles are insanely large, and loading the entire thing for a lookup will kill memory. | def lookup_mn_route(route_file,pair):
call = []
call.append('/bin/grep')
call.append('int_vndst=\"%d\" int_vnsrc=\"%d\"'% (pair[1][0],pair[0][0]))
call.append(route_file)
try:
result = subprocess.check_output(call)
except subprocess.CalledProcessError as e:
sys.stderr.write("E... | [
"def router_resolve(file_full_path):\n\ttry:\n\t\tf = open(file_full_path,'r')\n\texcept:\n\t\tprint('No Found File:%s',file_full_path)\n\titems = []\n\tfor line in f.readlines():\n\t\tif line.strip():\n\t\t\tm1 = re.findall('^(.*)',line.strip());\n\t\t\tif m1:\n\t\t\t\titem = m1[0].split(' ')\n\t\t\t\tfor ip in it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the shortest path for all nodes, using the attribute named wt_attr as the weighting function. | def allpairs(graph_file=None,wt_attr=None):
if graph_file is None and wt_attr is None:
parser = argparse.ArgumentParser()
parser.add_argument("-w", help="Attribute to use for shortest path weight",
metavar="<weight attribute>")
parser.add_argument("graph_file... | [
"def printAllPaths(self, startN):\r\n nodes = self.calcLeastCostPaths(startN)\r\n for n in nodes:\r\n if n.name == startN:\r\n continue\r\n path = self.getPathStr(nodes, n)\r\n print(\"least-cost path to node {!s}: {!s}\".format(n.name, path)\r\n + \"and the cost is {:.1f}\".f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a modelnet route, return the sequence of nodes it passes through (using the internal representation idx as a node id) This effectively translates modelnet vertex ID's to igraph IDs. | def __route2idxlist(igraph,pair,route):
idxlist = []
edges = igraph.es.select(int_idx_in=route)
srcnode = igraph.vs.select(vn_eq=pair[0][0])[0].index
idxlist.append(srcnode)
while len(route) > 0:
hop = route.pop(0)
edge = edges.select(idx=hop)[0]
if edge.source == idxlist[... | [
"def node_ids(self):\n return [self.ni_id, self.nj_id, self.nk_id, self.nl_id]",
"def node_link_ids(shape):\n (in_vert, in_horiz) = _node_in_link_ids(shape)\n (out_vert, out_horiz) = _node_out_link_ids(shape)\n node_link_ids = np.vstack((in_vert.flat, in_horiz.flat, out_vert.flat, out_horiz.flat))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select sample_size pairs of 'tor_relay' virtnodes from model_file and return them as a list of pairs | def select_sample(model_file,sample_size):
with open(model_file) as f:
tree= etree.parse(f)
virtnodes = [(int(x.get('int_vn')),x.get('vip'))
for x in tree.xpath("//virtnode[@nodetype='tor_relay']")]
if len(virtnodes) == 0:
sys.stderr.write("Warning, found no virtual node... | [
"def read_pairs(mode, config):\n # if mode == 'train' / 'test'\n with open('data/processed/{}/{}.txt'.format(config['dataset'], mode), 'r') as f:\n dataset = f.readlines()\n\n pairs = []\n for s in dataset:\n s = s.strip()\n phrase, label = s.split('\\t')\n phrase = ' '.join(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads a custom path to the device. This function reads the path from file path.csv in the local directory. This file can be generated using the Custom Path Generator.xlsm workbook. | def uploadCustomPath() :
print(">pcc")
comm.Write("pcc")
# read the moves out of the file
packets = []
with open("path.csv", "r") as fin :
for line in fin :
r = re.compile("[ \t\n\r,]+")
data = r.split(line)
if len(data) < 3 :
brea... | [
"def _upload_csv(self, output_path, now_utc, csv_name):\n output_filename = self._get_output_filename(now_utc)\n\n # If output path was specified, copy the csv temp file either to\n # a local file or upload it to Google Cloud Storage.\n full_output_path = os.path.join(output_path, output... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a RawHID binary file dump into csv format. This is NOT the same as converting a binary dump from the old overserial ADS stream because it does not use separator characters. | def convertBinaryDump(fname_in, fname_out) :
with open(fname_in, "rb") as fin, open(fname_out, "w") as fout :
# print out the header
fout.write("Time (*10us), Position (tics), Position Error Derivative (tics), Cmd Vel (tics/min), Target Pos (tics), Target Vel (tics), Motor Position (tics), Flags\n")... | [
"def pcap2csv(pcap_file_path, csv_file_path):\n cmd = []\n cmd.append(\"tshark\")\n cmd += ['-2','-R','tcp'] #all tcp packets\n cmd.append(\"-n\") # dont resolve ip addresses\n cmd += \"-T fields -e frame.time_epoch -e ip.src -e tcp.srcport -e ip.dst -e tcp.dstport -e tcp.len -e ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots the data generated using readCtrlHistory and/or streaming and stored in the class's data arrays | def plotData(self) :
# plot the data!
if len(self.figwindows) == 0 :
self.figwindows.append(plotgui.PlotWindow())
self.figwindows[0].move(0,0)
self.figwindows.append(plotgui.PlotWindow())
self.figwindows[1].move(400, 0)
self.figwindows... | [
"def plot_data(self):\n #TODO: implement time axis scale\n plt.title(\"Event #{} voltage\".format(self._event_number))\n plt.xlabel(\"time [ns]\")\n plt.ylabel(\"voltage [V]\")\n plt.plot(self._raw_data)\n plt.show()",
"def plot_data(self, frame_ordering):\n\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts streaming collection of data from the device, saved to a timestamped .bin file in the streams directory using the RawHID USB mode. This works better than the old plotter.startStreamPlot mode, which used the serial console. | def startStreaming(self) :
# tell the rawhid interface program to start saving out data streams
self.streaming = True
fbase = "streams/" + timeStamped(comm.port)
self.stream_fname = fbase + "stream.bin"
comm.DataStreamStartSave(DS_STREAM_HIST, self.stream_fname)
... | [
"def start_streaming(self):\n if (not self.is_connected()):\n self.message_string = 'Board is not connected.'\n return\n\n if (not (self.is_streaming)):\n self.message_string = 'Started streaming'\n self.port.reset_input_buffer()\n self.port.write... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stops streaming collection of data from the device being saved to the .bin file, converts the .bin to .csv, and shows the results. | def stopStreaming(self) :
# disable streaming
comm.Write("ss 0")
# tell the rawhid proxy to stop saving the data stream
comm.DataStreamStopSave(DS_STREAM_HIST)
self.streaming = False
# convert the .bin to .csv
newname = self.stream_fname... | [
"def stop_streaming_and_logging(self):\n self.write_char_array([self.COM_STOP_STREAMANDLOGGING])",
"def stop_streaming(self):\n self.message_string = 'Stopped streaming data'\n self.is_streaming = False\n self.port.write(STOP_STREAMING_CMD.encode('utf-8'))",
"def stop_recording(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initiate an OAuth login. Call the MediaWiki server to get request secrets and then redirect the user to the MediaWiki server to sign the request. | def login():
consumer_token = mwoauth.ConsumerToken(
app.config['CONSUMER_KEY'], app.config['CONSUMER_SECRET'])
try:
redirect, request_token = mwoauth.initiate(
app.config['OAUTH_MWURI'], consumer_token)
except Exception:
app.logger.exception('mwoauth.initiate failed')
... | [
"def auth():\n\n return redirect(f'https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=g37b9kh93q0fiihc931e29gwihf2q9&redirect_uri={REDIRECT_URI}&scope=user_read')",
"def login_oauth1(self):\n sess = dbsession.DropboxSession(self.app_key, self.app_secret,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if the get_media_manger function returns sensible things | def test_get_media_manager(self):
response, request = self.do_post({'title': u'Balanced Goblin'},
*REQUEST_CONTEXT, do_follow=True,
**self.upload_data(GOOD_JPG))
media = self.check_media(request, {'title': u'Balanced Gobli... | [
"def test_get_current_tan_media(self):\n pass",
"def get_media(self) -> bool:\n is_image = len(self._soup.find_all(\"img\")) > 0\n is_video = len(self._soup.find_all(\"video\")) > 0\n return is_image or is_video",
"def test_parse_media_association(self):\n self.assertEqual(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a trie of keywords, then sets fail transitions | def init_trie(genes):
AdjList.append({'value':'', 'next_states':{},'fail_state':0,'health_index':[]})
add_keywords(genes)
set_fail_transitions() | [
"def build_trie(self):\n\t\ttry:\n\t\t\twith open(self.corpus_filename, 'r+') as f:\n\t\t\t\tphrases = f.read().splitlines()\n\t\texcept FileNotFoundError:\n\t\t\traise\n\t\tfor phrase in phrases:\n\t\t\tself.trie.insert(phrase)",
"def build_trie(patterns):\n tree = dict()\n tree[0] = {}\n idx = 1\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a gtk menu, including submenu's | def build_menu(tree, accelgroup=None, root=True):
if root:
menu = gtk.MenuBar()
else:
menu = gtk.Menu()
for element in tree:
item = gtk.MenuItem(element['name'])
if element.has_key('icon'):
pass
if element.has_key('submenu'):
item.set_submenu... | [
"def _build_menus(self):\n debug('Timeline._build_menus')\n self.menu=tk.Menu(self.root, tearoff=0)\n #self.menu.add_command(label=\"Status\", command=self._set_status_text_for_item)\n #self.menu.add_separator()\n #self.menu.add_command(label=\"Rename\", command=self._open_item_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called to submit transaction traces. The transaction traces should be an iterable of individual traces. NOTE Although multiple traces could be supplied, the agent is currently only reporting on the slowest transaction in the most recent period being reported on. | def send_transaction_traces(self, transaction_traces):
if not transaction_traces:
return
payload = (self.agent_run_id, transaction_traces)
return self._protocol.send("transaction_sample_data", payload) | [
"def execute_on_traces(self, traces):\n self.ensure_one()\n new_traces = self.env['marketing.trace']\n\n if self.validity_duration:\n duration = relativedelta(**{self.validity_duration_type: self.validity_duration_number})\n invalid_traces = traces.filtered(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called to submit sample set for span events. | def send_span_events(self, sampling_info, span_event_data):
payload = (self.agent_run_id, sampling_info, span_event_data)
return self._protocol.send("span_event_data", payload) | [
"def test_submit_captured_events(self):\r\n # This method utilises the POST request method and will make changes to the Canvas instance. This needs consideration.\r\n pass",
"def run(self):\n self.burst_events()",
"def save_spans_data(self):\n\n self.spans_list = [entry.selection for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called to submit metric data for specified period of time. Time values are seconds since UNIX epoch as returned by the time.time() function. The metric data should be iterable of specific metrics. | def send_metric_data(self, start_time, end_time, metric_data):
payload = (self.agent_run_id, start_time, end_time, metric_data)
return self._protocol.send("metric_data", payload) | [
"def metric_api_call(self, time_start, action):\n time_end = time.time()\n diff = time_diff_ms(time_start, time_end)\n point = \"api latency: {} took {} ms\".format(action, diff)\n self._queue.put(point)",
"def thingspeak_post(metrics_time_utc, humidity, temperature, logger=None, thing... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receive agent commands from the data collector. | def get_agent_commands(self):
payload = (self.agent_run_id,)
return self._protocol.send("get_agent_commands", payload) | [
"def fetch_commands(self):\r\n continue_working = True\r\n while continue_working:\r\n cmd_tuple = self.connection_manager.read_command(self)\r\n if cmd_tuple is None:\r\n break\r\n\r\n cmd_type, cmd_args = cmd_tuple\r\n continue_working = sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called to submit errors. The errors should be an iterable of individual error details. NOTE Although the details for each error carries a timestamp, the data collector appears to ignore it and overrides it with the timestamp that the data is received by the data collector. | def send_errors(self, errors):
payload = (self.agent_run_id, errors)
return self._protocol.send("error_data", payload) | [
"def error_details(self):\n\n # TODO There is no attempt so far to eliminate duplicates.\n # Duplicates could be eliminated based on exception type\n # and message or exception type and file name/line number\n # presuming the latter are available. Right now the file\n # name and l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called to sub SQL traces. The SQL traces should be an iterable of individual SQL details. NOTE The agent currently only reports on the 10 slowest SQL queries in the most recent period being reported on. | def send_sql_traces(self, sql_traces):
payload = (sql_traces,)
return self._protocol.send("sql_trace_data", payload) | [
"def dbtrace(off=bool, keyword=\"string\", verbose=bool, mark=bool, info=bool, title=\"string\", output=\"string\", timed=bool, filter=\"string\"):\n pass",
"def _step1(cs, sql, run_log):\n q_time_start = time.time()\n cs.execute(sql)\n q_time_end = time.time()\n q_time_elapsed = q_time_end - q_tim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a MFRC522 module. spi_dev should be an object representing a SPI interface to which | def __init__(self, spi_dev):
self.spi = spi_dev
self.reset()
# Set TAuto - timer starts automatically after the enf of transmission
# TPrescaler_Hi - set to 0x0D
self.write_register(Registers.TModeReg, 0x8D)
# Set TPrescaler_Lo - set to 0x3E.
# Togethe... | [
"def __init__(self, spi_rack, module, frequency=100e6):\n #def __init__(self, module, frequency=100e6):\n self.spi_rack = spi_rack\n self.module = module\n\n self.rf_frequency = frequency\n self.stepsize = 1e6\n self.ref_frequency = 10e6\n self.use_external = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads all images in the folder and returns them as a list. If shuffle True, shuffles the ordering of all image files. | def reader(path, shuffle=True):
files = []
for img_file in os.scandir(path):
if img_file.name.lower().endswith('.jpg', ) and img_file.is_file():
files.append(img_file.path)
if shuffle:
# Shuffle the ordering of all image files in order to guarantee
# random ordering of ... | [
"def data_reader(input_dir, shuffle=True):\r\n file_paths = []\r\n\r\n for img_file in scandir(input_dir):\r\n if img_file.name.endswith('.jpg') and img_file.is_file():\r\n file_paths.append(img_file.path)\r\n\r\n if shuffle:\r\n # Shuffle the ordering of all image files in order to guarantee\r\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check sampling if finished. | def is_completed(self):
return self.sample_count > self.max_sample | [
"def nested_sampling_done(self):\n if self.ln_evidence is not None:\n return True\n return False",
"def wait_for_samples(self, output_sampler: OutputSampler, expected_num: int):\n now = time.time()\n end = now + 30\n\n while now < end:\n time.sleep(0.1)\n now = time.tim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the max number of samples. | def max_samples(self):
return self.max_sample | [
"def getMaxSamples(self):\n return self.getOrDefault(self.maxSamples)",
"def max_samples(self) -> Optional[pulumi.Input[int]]:\n return pulumi.get(self, \"max_samples\")",
"def max_sample_value(self):\n return self._max_sample_value",
"def getMaxFeatures(self):\n return self.getOrD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
grant readable acl for username or global if username is empty | def _grant_read_access(self, node_id, username=None):
headers = self._get_admin_header()
if username: # grand readable acl for user
end_point = os.path.join(self.shock_url, 'node', node_id, 'acl/read?users={}'.format(username))
resp = _requests.put(end_point, headers=headers)
... | [
"def add_read_acl(self, node_id, username=None):\n\n headers = self._get_admin_header()\n\n end_point = os.path.join(self.shock_url, 'node', node_id, 'acl/?verbosity=full')\n resp = _requests.get(end_point, headers=headers)\n\n if resp.status_code != 200:\n raise ValueError('G... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check current acl and then grant readable acl to user or public | def add_read_acl(self, node_id, username=None):
headers = self._get_admin_header()
end_point = os.path.join(self.shock_url, 'node', node_id, 'acl/?verbosity=full')
resp = _requests.get(end_point, headers=headers)
if resp.status_code != 200:
raise ValueError('Grant readable... | [
"def _grant_read_access(self, node_id, username=None):\n headers = self._get_admin_header()\n\n if username: # grand readable acl for user\n end_point = os.path.join(self.shock_url, 'node', node_id, 'acl/read?users={}'.format(username))\n resp = _requests.put(end_point, headers=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provided a controller and a desired state for the system, return the optimal park signal sequence that forces the system into the desired state des_transition tuple/list with desired transition between two states in the system. des_transition[0] start des_transition[1] end | def find_sequence(ctrl, des_transition, T):
to_visit_first = set()
to_visit_second = set()
for edge in ctrl.edges_iter(data=True):
next_ctrl_state = edge[1] # end state of transition in controller
sys_state = edge[2]['loc'] # controller steers into this system state
#print("sys_stat... | [
"def qp_controller(current_state, desired_state, dt, dim=2):\n\n # torque PD controller values\n wheel_kp = 50.0\n wheel_kd = 10.0\n max_torque = 20.0\n\n # cost on obtaining next state and velocity\n kp = 0.0\n kd = 1.0\n\n # half state length\n hl = len(current_state) / 2\n\n mp = Ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all valid pairs of tape given a list of OpenCV contours | def get_pairs(contours):
rect_pairs = []
for index, cnt in enumerate(contours):
# Rotated rect - ( center (x,y), (width, height), angle of rotation )
rect = cv2.minAreaRect(cnt)
center_x, center_y = rect[0]
rect_angle = -round(rect[2], 2)
cv2.putText(img, str(rect_angle... | [
"def __filter_contours(input_contours, min_area, min_perimeter, min_width, max_width,\n min_height, max_height, solidity, max_vertex_count, min_vertex_count,\n min_ratio, max_ratio):\n output = []\n for contour in input_contours:\n x,y,w,h = cv2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
assert x is not None | def ll_assert_not_none(x):
assert x is not None, "ll_assert_not_none(%r)" % (x,)
return x | [
"def assert_true(a: Any) -> None: \n assert a is True",
"def is_not_none(x) -> bool:\n return x is not None",
"def test_one_and_none(self):\n assert bu.one_and_none(None, \"snek\")",
"def Should_Not_Be_Type_None(var):\n if var is None:\n raise AssertionError(\"the variable passed was ty... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a StopTimeHash from the first ttable entry of a model.Train | def first_of_train(cls: Type[T], train: model.Train) -> T:
first_tt_entry = train.timetable[0]
return cls(
train.calendar,
last_part(first_tt_entry.station),
";".join(last_part(i) for i in train.destinations),
first_tt_entry.arrival
) | [
"def last_of_train(cls: Type[T], train: model.Train) -> T:\n last_tt_entry = train.timetable[-1]\n if last_tt_entry.departure < 0:\n last_tt_entry = train.timetable[-2]\n return cls(\n train.calendar,\n last_part(last_tt_entry.station),\n \";\".join(l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a StopTimeHash from the last ttable entry of a model.Train | def last_of_train(cls: Type[T], train: model.Train) -> T:
last_tt_entry = train.timetable[-1]
if last_tt_entry.departure < 0:
last_tt_entry = train.timetable[-2]
return cls(
train.calendar,
last_part(last_tt_entry.station),
";".join(last_part(i) fo... | [
"def observation_time_stop(self):\n return self.time_ref + u.Quantity(self.table.meta[\"TSTOP\"], \"second\")",
"def get_timetable(stop):\n\n timetable = {}\n\n ops = requests.get(\n \"https://luasforecasts.rpa.ie/xml/get.ashx?action=forecast&stop=\"\n + stop\n + \"&encrypt=false... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively finds all blocks up to and including this node | def blocks_up_to(self) -> List[List["BlockNode"]]:
if not self.prev:
# Base case - no previous trains
blocks = [[]]
else:
# Recursive case - find all previous trains
blocks = []
for prev_train in self.prev:
blocks.extend(prev_tr... | [
"def search_blocks(model):\n blocks = []\n for name, node in model.named_nodes():\n if is_connection_node(node):\n blocks.append(search_blocks_items(node))\n return blocks",
"def iterblocks(self):\n def traverse(b, depth):\n if type(b) is not tuple:\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a train from storage, used after its blocks were assigned | def drop_train(self, train: TrainShort) -> None:
del self.trains_by_id[train.id]
if len(self.trains_by_first_sta[train.first_sta]) == 1:
del self.trains_by_first_sta[train.first_sta]
else:
try:
self.trains_by_first_sta[train.first_sta].remove(train.id)
... | [
"def rm_trainer(self):\n self.trainers[-1].exit_flag.value = 1\n self.trainers[-1].join()\n self.trainers.pop()",
"def delete(self, desc):\n if not desc:\n return\n self.alloc.free(StoreBlock.from_desc(desc))",
"def remove_brain(self, brain):\n del self.brain... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solve blocks of a particular train, and afterwards remove it (and others with throughservice) from the BlockSolver. | def solve_train(self, train: TrainShort) -> None:
visited: dict[model.TrainID, BlockNode] = {}
root_node = BlockNode(train)
# Expand the node
self.expand_previous(root_node, visited)
self.expand_next(root_node, visited)
# No through service - don't do anything
i... | [
"def replace_blocks(self, blocks: Iterable[QuantumCircuit]) -> \"ControlFlowOp\":\n pass",
"def remove(self, smoothed, valley_mask=None):\r\n\r\n # Erode blocks based on the height map\r\n mx, mz, my = self.__local_ids.shape\r\n removed = numpy.zeros((mx, mz), bool)\r\n material... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a node and recursively expands its previous trains. `node.prev` should either be empty, or contain a single train (done when recursively expanding in the opposite direction), whose ID should be provided in the `ignore_train` to avoid infinite recursion. | def expand_previous(self, node: BlockNode, visited: Dict[model.TrainID, BlockNode],
ignore_train: model.TrainID = "") -> None:
visited[node.train.id] = node
prev_trains = self.previous_trains(node.train)
# Nothing to do, rewind up
if not prev_trains:
... | [
"def expand_next(self, node: BlockNode, visited: Dict[model.TrainID, BlockNode],\n ignore_train: model.TrainID = \"\") -> None:\n visited[node.train.id] = node\n next_trains = self.next_trains(node.train)\n\n # Nothing to do, rewind up\n if not next_trains:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a node and recursively expands its next trains. `node.next` should either be empty, or contain a single train (done when recursively expanding in the opposite direction), whose ID should be provided in the `ignore_train` to avoid infinite recursion. | def expand_next(self, node: BlockNode, visited: Dict[model.TrainID, BlockNode],
ignore_train: model.TrainID = "") -> None:
visited[node.train.id] = node
next_trains = self.next_trains(node.train)
# Nothing to do, rewind up
if not next_trains:
return
... | [
"def expand_previous(self, node: BlockNode, visited: Dict[model.TrainID, BlockNode],\n ignore_train: model.TrainID = \"\") -> None:\n visited[node.train.id] = node\n prev_trains = self.previous_trains(node.train)\n\n # Nothing to do, rewind up\n if not prev_trains:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to find all immediately preceding trains for given train. | def previous_trains(self, train: TrainShort) -> List[model.TrainID]:
if train.is_first:
return []
matches: List[model.TrainID] = []
hashes = self.trains_by_last_sta.get(train.first_sta)
if train.prev is not None:
# Train had nicely defined previousTrainTimetable... | [
"def next_trains(self, train: TrainShort) -> List[model.TrainID]:\n if train.is_last:\n return []\n\n matches: List[model.TrainID] = []\n hashes = self.trains_by_first_sta.get(train.last_sta)\n\n if train.next is not None:\n # Train had nicely defined previousTrainT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to find all immediately following trains for given train. | def next_trains(self, train: TrainShort) -> List[model.TrainID]:
if train.is_last:
return []
matches: List[model.TrainID] = []
hashes = self.trains_by_first_sta.get(train.last_sta)
if train.next is not None:
# Train had nicely defined previousTrainTimetable fiel... | [
"def previous_trains(self, train: TrainShort) -> List[model.TrainID]:\n if train.is_first:\n return []\n\n matches: List[model.TrainID] = []\n hashes = self.trains_by_last_sta.get(train.first_sta)\n\n if train.prev is not None:\n # Train had nicely defined previousT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basic queue complete doesn't use the envelopewe always just lpop | def complete(self, envelope, worker_id, pipeline):
pipeline.lpop(self._working_queue_key(worker_id)) | [
"def _dequeue(self):\n func, args = self.queue.poplet()\n func(*args)",
"def __dequeue(self):\n return self.__queue.pop()",
"def wipeQueue():\n\tq.clear()",
"def test_empty_dequeue(empty_q):\n assert empty_q.dequeue() is False",
"def _deq(self):\n if(len(self.q)>0):\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if job is done. If done, send results expects teh full job dict from the frontend currently (frontend sends as json) job_id job id of the job to check dict with status, and if done then job results | def check_job_status(job_id):
# what we're returning to requester
payload = {}
if OSPARC_TEST_MODE or job_id == "fake-job-for-testing":
# this is test mode, send back sucessful and mock data
payload = {
"download_path": "fake-path",
"outputs": ["fake-output1", "f... | [
"def check_status(domain, org_key, job_id, headers):\n url = f\"{domain}/api/investigate/v1/orgs/{org_key}/processes/search_jobs/{job_id}\"\n contacted = \"\"\n completed = \"1\"\n print(\"Checking to see if query has completed...\")\n while contacted != completed:\n response = requests.get(ur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the drug given the organism, gene, and position of point mutation. | def get_drug(self, organism, gene, position):
table = self._data
drug = table[(table['Organism'] == organism) & (table['Gene'] == gene) & (
table['Codon Pos.'] == position)]['Drug']
if (drug.empty):
logger.warning("No drug found for organism=%s, gene=%s, position=%s"... | [
"def inter_grapple_point(self):\r\n # new\r\n grapple_point = self.problem_spec.grapple_points[1]\r\n return grapple_point",
"def gun_point(self):\n return self.position\n # x, y = self.position\n # _, _, w, h = self.bounding_rect\n # half_w, half_h = round(w / 2),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Customer Details form, first page of Enquiry | def customer_details(request):
# Set initial response code for testing purposes
response_code = 200
if request.method == "POST":
form = CustomerDetailsForm(request.POST, use_required_attribute=False)
if form.is_valid():
# Save to the session to be retreived later
r... | [
"def showCustomerDetails(var,custid):\n _gotoCustomer(var,custid,CUSTSHOWONLY)",
"def property_details(request):\n\n # Set initial response code for testing purposes\n response_code = 400\n\n # Session check to verify journey integrity\n if not \"customer_details\" in request.session:\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Property Details form, second page of Enquiry | def property_details(request):
# Set initial response code for testing purposes
response_code = 400
# Session check to verify journey integrity
if not "customer_details" in request.session:
return redirect("customer_details")
if request.method =="POST":
form = PropertyDetailsForm(... | [
"def display(self):\r\n print(\"PROPERTY DETAILS\")\r\n print(\"=\"*15)\r\n print(\"square footage: {}\".format(self.square_feet))\r\n print(\"bedrooms: {}\".format(self.num_bedrooms))\r\n print(\"bathrooms: {}\".format(self.num_baths))\r\n print()",
"def execute(self, co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function checks if number multiples of the divisors. | def check_natural_divisible(number, divisors):
for divired in divisors:
if number % divired == 0:
return True | [
"def divisible(number, divisor):\n try:\n number = int(number)\n divisor = int(divisor)\n return number % divisor == 0\n except:\n return False",
"def multiples(n):\n if n % 3 == 0 or n % 5 == 0:\n return True\n return False",
"def find_proper_divisors(number):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generation a natural number multiples of the divisors. Numbers are generated up to the limit. | def generate_natural_divisibles(limit, *divisors):
if limit < 0:
return
for number in range(1, limit):
if check_natural_divisible(number, divisors):
yield number | [
"def get_divisors(num):\n yield 1\n\n for i in range(2, num / 2 + 1):\n if not num % i:\n yield i",
"def divisors(n):\r\n for i in range(1, round(n ** 0.5) + 1):\r\n if n % i == 0:\r\n yield i\r\n j = n // i\r\n if i != j:\r\n yield... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The internal counter, formatted as a 16 byte block suitable for consumption by the cipher | def _counter_block(self):
return self._counter.to_bytes(16, byteorder='little') | [
"def encodeCounter64(integer):\n return _encodeUnsigned('Counter64', integer)",
"def encodeCounter32(integer):\n return _encodeUnsigned('Counter32', integer)",
"def chacha20_block(key: bytes, nonce: bytes, counter: int) -> int:\n assert type(key) is bytes, 'key is no instance of bytes'\n assert len(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw hough lines without any extrapolation | def draw_hough_line(img, lines, color=[255,0,0], thickness=2):
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(line_img, (x1,y1), (x2,y2),[255, 0, 0],2)
return line_img | [
"def houghp(self):\n img = cv2.imread(self.pageImage)\n #print self.pdfImage\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n h,w,channel = img.shape\n gray = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,11,7)\n kernel = np.zeros((5,5),np.u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a UPATrial object corresponding to a complete graph with num_nodes nodes Note the initial list of node numbers has num_nodes copies of each node number | def __init__(self, num_nodes):
self._num_nodes = num_nodes
self._node_numbers = [node for node in range(num_nodes) for dummy_idx in range(num_nodes)] | [
"def make_graph_UPA(num_nodes, num_edges_per_node):\n \n # Test num_nodes and num_edges_per_node to determine whether\n # the algoritnm can be used\n _num_nodes = int(num_nodes)\n _num_edges_per_node = int(num_edges_per_node)\n if _num_nodes < _num_edges_per_node:\n print \"###> Error: _num... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implements visited bfs algorithm Return set of visited nodes | def bfs_visited(ugraph, start_node):
if ugraph.get(start_node,0) == 0:
return set([])
bfs_que = Queue()
bfs_que.enqueue(start_node)
visited = set([start_node])
while len(bfs_que) > 0:
node = bfs_que.dequeue()
for neigh in ugraph[node]:
if neigh not in ... | [
"def bfs(self, start=None):\n visited = set()\n stack = [start]\n while stack:\n vertex = stack.pop(0)\n yield vertex\n if vertex not in visited:\n visited.add(vertex)\n stack.extend(self.get_adj(vertex) - visited)\n return",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns features as property. | def features(self):
return self.__features | [
"def feature_list(self):\n return self.features.features()",
"def vocation_features(self):\n return self.vocation.features",
"def builtin_features(self) -> Dict:\n return self._builtin_features",
"def GetFeatures(self):\n return json.dumps(FEATURES)",
"def get_feature_names(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return is entrance as property. | def is_entrance(self):
return self.__is_entrance | [
"def get_an_event_property(self):\n return self.__an_event_property",
"def is_assigned(self):\n return bool(self.current_property())",
"def isInherent(self):\n return self.objtype == s_INHERENT",
"def is_entrance(self, toggle: bool):\n self.__is_entrance = toggle",
"def isPropert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets flag to indicate whether room is an entrance. | def is_entrance(self, toggle: bool):
self.__is_entrance = toggle | [
"def is_entrance(self):\n return self.__is_entrance",
"def setEssential(self,flag):\n self.essential=flag",
"def enterRoom(self):\n # put tile if there isn't one\n if not self.hasTile():\n self.putTile()\n # get this rooms mob depending on certain circumstances\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns is exit as property. | def is_exit(self):
return self.__is_exit | [
"def terminating(self) -> bool:\n return typing.cast(\n bool,\n self._properties.get(\"terminating\"),\n )",
"def is_exit(self, toggle: bool):\n self.__is_exit = toggle",
"def is_assigned(self):\n return bool(self.current_property())",
"def getOnExit(self) -> ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets flag to indicate whether room is an exit. | def is_exit(self, toggle: bool):
self.__is_exit = toggle | [
"def set_exiting(state=EXITING):\n global exiting\n\n logger.debug('Waiting for exiting state lock')\n with _lock:\n if exiting != state:\n logger.debug('Setting exiting flag to {}'.format(state))\n exiting = state",
"def set_flag(flag = 'exit'):\n FLAG[flag] = True",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets right room link. | def right(self, room):
if room and not isinstance(room, Room):
raise TypeError('Type must be Room instance or None.')
self.__right = room | [
"def link_room(self, room_to_link, direction):\n self.linked_rooms[direction] = room_to_link\n #print( self.name + \" linked rooms :\" + repr(self.linked_rooms) )",
"def setRoom(self, room):\n self.info['roomRef'] = room",
"def setroom(self, room):\n pass",
"def setRoomRef(self, newRoom):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets down room link. | def down(self, room):
if room and not isinstance(room, Room):
raise TypeError('Type must be Room instance or None.')
self.__down = room | [
"def set_port_link_down(self, port_no, dp_id=None):\n self.set_port_state(port_no, False, dp_id=dp_id)",
"async def down(self):\n await self.set(self.Direction.DOWN)",
"def offlink(self, offlink):\n\n self._offlink = offlink",
"def link_room(self, room_to_link, direction):\n self.l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns visited as property. | def visited(self):
return self.__visited | [
"def getVisit(self):\n\n return self.visit",
"def visited_urls(self) -> Set:\n return self._visited_urls",
"def is_visited(self) -> bool:\n return self.colour == RED",
"def visited_urls(self):\r\n return list(set(self._visited_urls) | set(self.paths.keys()))",
"def mark_visited(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns blocked as property. | def blocked(self):
return self.__blocked | [
"def stealth_mode_blocked(self):\n if \"stealthModeBlocked\" in self._prop_dict:\n return self._prop_dict[\"stealthModeBlocked\"]\n else:\n return None",
"def inbound_notifications_blocked(self):\n if \"inboundNotificationsBlocked\" in self._prop_dict:\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a feature from a room's feature list. | def remove_feature(self, feature):
if not isinstance(feature, Feature):
raise TypeError('Type must be Feature instance')
self.__features.remove(feature) | [
"async def remove(message: discord.Message, plugin: plugin_in_req, req_id: get_req_id):\n # Test and reply if feature by requested id doesn't exist\n assert feature_exists(plugin, req_id), \"There is no such feature.\"\n\n # Remove the feature\n del feature_reqs.data[plugin][req_id]\n feature_reqs.sa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test against output of SPM_MDP_VB_X.m 1A one hidden state factor, one observation modality, backwards horizon = 3, policy_len = 1, policyconditional prior | def test_active_inference_SPM_1a(self):
array_path = os.path.join(os.getcwd(), DATA_PATH + "vbx_test_1a.mat")
mat_contents = loadmat(file_name=array_path)
A = mat_contents["A"][0]
B = mat_contents["B"][0]
C = to_arr_of_arr(mat_contents["C"][0][0][:,0])
obs_matlab = mat_c... | [
"def policy_improvement():\n policy_stable = True\n for s in STATES:\n current_v = sum([P[s, POLICY[s], s1] * (R[s, POLICY[s], s1] + GAMMA*V[s1]) for s1 in STATES])\n # Taking best action with respect to current value function V:\n for a in ACTIONS:\n temp = sum([P[s, a, s1] * ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Workflow function changes order state to spare_cancel. | def spare_cancel(self,cr,uid,ids,context=None):
exchange = self.pool.get('exchange.order')
wf_service = netsvc.LocalService("workflow")
for rec in self.browse(cr , uid ,ids):
exchange_ref = rec.ir_ref
exchange_id = exchange.search(cr , uid , [('name' , '=' , exchange_ref... | [
"def cancel_all_open_order(self):",
"def cancel_open_order(self, pair):",
"def save(self):\n order = self.context['order']\n order.cancel_order()",
"def save(self):\n order = self.context['order']\n\n order.cancel_order()",
"def action_cancel(self):\n # TDE DUMB: why is ca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check That there is one quote Approved | def check_spare_invoice(self, cr ,uid ,ids , context=None):
for rec in self.browse(cr , uid ,ids):
approved=False
for quote in rec.q_ids:
if quote.state == 'done':
approved=True
if not approved:
raise osv.exc... | [
"def quote_approved(self, cr, uid, ids,context=None):\n wf_service = netsvc.LocalService(\"workflow\")\n internal_obj = self.pool.get('ireq.m')\n internal_products = self.pool.get('ireq.products')\n quote_obj = self.pool.get('pur.quote')\n \n for quote in self.browse(cr, u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check That all quote in confirmed or cancel state | def check_invoice_complete(self, cr ,uid ,ids , context=None):
for rec in self.browse(cr , uid ,ids) :
if not rec.q_ids:
raise osv.except_osv( _('No Invoice!'), _('There is no Invoices.'))
return False
confirm=False
for quote i... | [
"def confirmed(self, cr, uid, ids):\n # This method is workflow function it checks many field then change the states\n for quote in self.browse(cr, uid, ids):\n if not quote.quote_no: #Check if there is a number \n raise osv.except_osv(('No Quotation Number !'), ('Please .. F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates purchase order or stock picking from quotation which is in done state and then change the workflow state to purchase_officer. | def create_spare_purchase_order(self,cr, uid, ids, context=None):
print"================================================"
picking_obj = self.pool.get('stock.picking')
stock_move = self.pool.get('stock.move')
purchase_obj = self.pool.get('purchase.order')
rec=self.browse(cr, uid, ... | [
"def handleNewOrder( order, event ):\n \n if event.destination != icore.workflow_states.order.finance.CHARGEABLE:\n return\n\n if not event.source in ( icore.workflow_states.order.finance.REVIEWING, ):\n return \n\n if icore.IShippableOrder.providedBy( order ):\n order.shipments = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Workflow function changes quotation state to done, cancel all other quotations of the requisition and change the requisition state to wait_confirmed. | def quote_approved(self, cr, uid, ids,context=None):
wf_service = netsvc.LocalService("workflow")
internal_obj = self.pool.get('ireq.m')
internal_products = self.pool.get('ireq.products')
quote_obj = self.pool.get('pur.quote')
for quote in self.browse(cr, uid, ids):
... | [
"def action_cancel_draft(self, cr, uid, ids, context=None):\n #for trans in self.browse(cr, uid, ids):\n #if trans.transportation_id.state not in ['trans_manager']:\n #raise osv.except_osv(_('Wrong action !'), _('You can not cancel the quotaion in this state ..')) \n if not le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the tuple (Z, A, suffix, ZA) for an gnd isotope name (e.g., gnd name = 'Am242_m1' returns ( 95, 242, 'm1', 95242 ). | def getZ_A_suffix_andZAFromName( name ) :
if( name == 'n' ) : return( 0, 1, '', 1 )
if( name == 'gamma' ) : return( 0, 0, '', 0 )
if( name[:18] == 'FissionProductENDL' ) :
ZA = int( name[18:] )
Z = ZA / 1000
A = 1000 * Z - ZA
return( Z, A, '', ZA )
if( '__' in name ) : r... | [
"def split_name_ucsb(name):\n sans_prefix = name[::-1][:name[::-1].index('ScanImage_'[::-1])][::-1]\n sans_suffix = sans_prefix[:sans_prefix.index('_Ablation')]\n spot_name = sans_suffix[::-1][:sans_suffix[::-1].index('-')][::-1]\n sample_name = sans_suffix[::-1][sans_suffix[::-1].index('-')+1:][::-1]\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does this PDF contain enough pages? | def check_nb_pages(self, data):
try:
s_io = StringIO(data)
reader = pypdf.PdfReader(s_io)
num_pages = reader.getNumPages()
print(("num pages: %d" % num_pages))
return num_pages > 2
except PyPdfError as e:
return False | [
"def test_len_pages(self):\n self.assertEqual(len(self.pdf.pages), 2)",
"def ifPageExists(total_pages, page_no):\n if page_no <= total_pages:\n return False\n return True",
"def check_pages(soup):\n review_count = int(soup.find(itemprop='reviewCount').text.strip('()'))\n pages = 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function checks the payment gateway id and returns the respective navigators by calling respective get_navigators functions | def get_pg_navigators(request):
try:
input_json = request
# checking if pg provider is PayTM
if input_json['gateway_details']['pg_provider_id'] == 4:
pg_navigator_vars = get_pg_navigators_paytm(input_json)
match = re.findall(r"'Status': 'Failure'", str(pg_navigator_va... | [
"def navigate_to():\n \n return Navi.navigate_to(\"Mobile Payment Configuration\")",
"def get_current_user_gateway(vir_sys):\n logging.debug(\"In get_current_user_gateway\")\n api_resp_user_gateway = connect_gp.call_api(\"XPATH_GET_GATEWAY\", vir_sys)\n # result should be a APIResponse\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find a satisfying assignment for a given CNF formula.a Returns that assignment if one exists, or None otherwise. >>> satisfying_assignment([]) {} >>> sa = satisfying_assignment([[('a', True), ('b', False), ('c', True)]]) >>> ('a' in sa and sa['a']) or ('b' in sa and not sa['b']) or ('c' in sa and sa['c']) True >>> sati... | def satisfying_assignment(formula):
#print('new_recursion:')
#print(formula)
if len(formula)==0: #Base case: empty formula returns empty assignments
return {}
assignments = {}
ind = 0 #Which literal are we looking at?
boolVal = True #What value does the variable in our current literal ... | [
"def satisfying_assignment(formula):\n assignment = {}\n# for clause in formula:\n# for literal in clause: d \n# if literal[0] not in assignment:\n# assignment[literal[0]] = None\n# else:\n# continue \n if formula == []:\n# print('empty')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function should create constraints that ensure that each actor has one and only one manager. | def make_one_manager_constraints(vars):
#We want one clause of all literals, and all other clauses of each
constraints = []
for actor in vars:
managers = vars[actor]
at_least_one_clause = [] #This clause will contain the literals ("A_1",True),...,("A_i",True) for given actor A and K=i, ensur... | [
"def make_different_constraint(vars,acted_with):\n constraints = []\n #(not A_i) or (not B_i) for connected actors A and B and manager i --> either one of two connected actors can have a given manager, or neither, but not both.\n #possible issue: repetition of each pair (should be okay, since cnf value doe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function should create constraints that ensure that each actor has a different manager from other actors in the same movie. | def make_different_constraint(vars,acted_with):
constraints = []
#(not A_i) or (not B_i) for connected actors A and B and manager i --> either one of two connected actors can have a given manager, or neither, but not both.
#possible issue: repetition of each pair (should be okay, since cnf value doesnt chan... | [
"def make_one_manager_constraints(vars):\n #We want one clause of all literals, and all other clauses of each\n constraints = []\n for actor in vars:\n managers = vars[actor]\n at_least_one_clause = [] #This clause will contain the literals (\"A_1\",True),...,(\"A_i\",True) for given actor A ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that a request contains JSON with specific fields | def validate_json_contains(api_method, request, fields, code=400):
json = request.get_json()
# If the required fields are not in the json, return none and error payload
for field in fields:
if not field in json:
return None, api_message(api_method, API_REQUIRES_FIELDS.format(fields), co... | [
"def validate_request_json(json_data: Dict[str, Any], required_fields: List[str]) -> Dict[str, str]:\n # Create a default success message\n response = {\"status\": \"success\"}\n for required_field in required_fields:\n if required_field not in json_data:\n # Set the error fields\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds links key to object (first argument) based on links dictionary and value | def wrap_with_links(obj, links, val, root_path, many=False):
if many:
for item in obj:
item['links'] = {}
for key in links:
item['links'][key] = root_path + links[key].format(item[val])
else:
obj['links'] = {}
for key in links:
obj['lin... | [
"def add_new_link(self, text, link, source, info):\n print(\"Adding new link\")\n for word in self.keywords:\n word = self.keywords[word]\n word.check_link(text, link, source, info)\n word.transform_to_dict()",
"def delayedLoadLinksComp(objectDict, linkData):\n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function just writes the pcap_path as a comment into the arff file. It's done for debugging purposes as well as to keep track of where the written area is | def write_pcap_path(self, pcap_path):
with open(self.output_path, 'a+') as file:
file.write(ArffWriter.NEW_LINE)
file.write("% "+pcap_path)
file.write(ArffWriter.NEW_LINE) | [
"def _write_comment(self, comment):\n\n # Write the comment into the log\n self._file.write(comment + \"\\n\")\n\n # If appropriate, print the comment into the screen\n if not self._silent:\n print(comment)\n\n # Flush the file\n self._file.flush()",
"def write... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a rule which ensures that x is accessible to the actor in the action. | def require_xobj_accessible(actionsystem, action) :
@actionsystem.verify(action)
@docstring("Ensures the object x in "+repr(action)+" is accessible to the actor. Added by require_xobj_accessible.")
def _verify_xobj_accessible(actor, x, ctxt, **kwargs) :
if not ctxt.world[AccessibleTo(x, actor)] :
... | [
"def user_has_rule_action_permission(user_db, action_ref):\n raise NotImplementedError()",
"def require_xobj_visible(actionsystem, action) :\n @actionsystem.verify(action)\n @docstring(\"Ensures the object x in \"+repr(action)+\" is visible to the actor. Added by require_xobj_visible.\")\n def _v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a rule which ensures that x is visible to the actor in the action. | def require_xobj_visible(actionsystem, action) :
@actionsystem.verify(action)
@docstring("Ensures the object x in "+repr(action)+" is visible to the actor. Added by require_xobj_visible.")
def _verify_xobj_visible(actor, x, ctxt, **kwargs) :
if not ctxt.world[VisibleTo(x, actor)] :
retu... | [
"def require_xobj_accessible(actionsystem, action) :\n @actionsystem.verify(action)\n @docstring(\"Ensures the object x in \"+repr(action)+\" is accessible to the actor. Added by require_xobj_accessible.\")\n def _verify_xobj_accessible(actor, x, ctxt, **kwargs) :\n if not ctxt.world[AccessibleTo(x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds rules which check if the object x is held by the actor in the action, and if only_hint is not true, then if the thing is not already held, an attempt is made to take it. The transitive flag refers to allowing the actor be the owner of the object, and not necessarily holding onto it directly. | def require_xobj_held(actionsystem, action, only_hint=False, transitive=True) :
def __is_held(actor, x, ctxt) :
if transitive :
return actor == ctxt.world[Owner(x)] and ctxt.world[AccessibleTo(x, actor)]
else :
return ctxt.world.query_relation(Has(actor, x))
@actionsystem... | [
"def hint_xobj_notheld(actionsystem, action) :\n @actionsystem.verify(action)\n @docstring(\"Makes \"+repr(action)+\" more logical if object x is not held by the actor. Added by hint_xobj_notheld.\")\n def _verify_xobj_notheld(actor, x, ctxt, **kwargs) :\n if not ctxt.world.query_relation(Has(actor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a rule which makes the action more logical if x is not held by the actor of the action. | def hint_xobj_notheld(actionsystem, action) :
@actionsystem.verify(action)
@docstring("Makes "+repr(action)+" more logical if object x is not held by the actor. Added by hint_xobj_notheld.")
def _verify_xobj_notheld(actor, x, ctxt, **kwargs) :
if not ctxt.world.query_relation(Has(actor, x)) :
... | [
"def _constraint(self, action):\n return float(self.vehicle.crashed) + float(self.vehicle.lane_index[2] == 0)/15",
"def require_xobj_held(actionsystem, action, only_hint=False, transitive=True) :\n def __is_held(actor, x, ctxt) :\n if transitive :\n return actor == ctxt.world[Owner(x)]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One cannot take what is fixed in place. | def before_taking_check_fixedinplace(actor, x, ctxt) :
if ctxt.world[FixedInPlace(x)] :
raise AbortAction(ctxt.world[NoTakeMessage(x)], actor=actor) | [
"def reset_fixed_varied_parameters(self):\n self.varied_params = [param for param in self.parameters\n if param.is_varied()]\n self.fixed_params = [param for param in self.parameters\n if param.is_fixed()]",
"def set_fixed(self, num):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One cannot take what one is inside or on. Assumes there is a room at the top of the heirarchy of containment and support. | def before_taking_check_not_inside(actor, x, ctxt) :
loc = ctxt.world[Location(actor)]
while not ctxt.world[IsA(loc, "room")] :
if loc == x :
if ctxt.world[IsA(x, "container")] :
raise AbortAction(str_with_objs("{Bob|cap}'d have to get out of [the $x] first.", x=x), actor=act... | [
"def get_notable_objects_no_for_scenery(actor, x, ctxt) :\n if ctxt.world[Scenery(x)] and ctxt.world[IsA(x, \"container\")] :\n raise ActionHandled([(x, 0)])\n else : raise NotHandled()",
"def find_clearing_to_land():\n # Find a place on the lower half of the screen where there is no identifiable ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints out the default "Taken." message. | def report_taking_default(actor, x, ctxt) :
ctxt.write("Taken.") | [
"def on_take(self):\n print(Fore.MAGENTA + f\"\\nYou have picked up the item: {self.name}!\")\n print()",
"def insurance(player, taken=False):\n pass",
"def summary(self):\n return render_output(\n [\n 'Test Name: %s' % self.name,\n 'Success: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One can't drop oneself. | def before_dropping_self(actor, x, ctxt) :
raise AbortAction("{Bob|cap} can't be dropped.", actor=actor) | [
"def at_drop(self, dropper):\r\n pass",
"def is_drop_target(self):\n return True",
"def run_backward(self):\n # If the document has 'allow_inheritance' then drop only if\n # no derived or parent documents left which are point to\n # the same collection\n skip = self.par... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints the default "Dropped." message. | def report_drop_default(actor, x, ctxt) :
ctxt.write("Dropped.") | [
"def on_drop(self):\n print(Fore.MAGENTA, f\"\\nYou have dropped {self.name} item!\")\n print()",
"def message_dropped(self, message):\n pass",
"def at_drop(self, dropper):\r\n pass",
"def toolDropped(string):\n pass",
"def print_droplets(self):\n for drop in self.cloud... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets up some important variables such as where the destination is as well as through what one is getting there. Also checks that there is an exit in that particular direction, and issues the appropriate NoGoMessage. | def trybefore_going_setup_variables(action, actor, direction, ctxt) :
action.going_from = ctxt.world[VisibleContainer(ctxt.world[Location(actor)])]
if direction not in ctxt.world.activity.get_room_exit_directions(action.going_from) :
action.going_via = None
action.going_to = None
else :
... | [
"def before_going_check_destination(action, actor, direction, ctxt) :\n if not action.going_to :\n raise AbortAction(ctxt.world[NoGoMessage(action.going_from, direction)])",
"def report_going_default(action, actor, direction, ctxt) :\n msg = ctxt.world[WhenGoMessage(action.going_from, direction)]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that the going_via is open if it is an openable door. | def before_going_check_door(action, actor, direction, ctxt) :
if ctxt.world[IsA(action.going_via, "door")] :
if ctxt.world[Openable(action.going_via)] and not ctxt.world[IsOpen(action.going_via)] :
ctxt.actionsystem.do_first(Opening(actor, action.going_via), ctxt, silently=True)
if n... | [
"def is_open(self, direction):\n if not isinstance(direction, int): \n raise ValueError('direction must be an integer, not {:s}'.format(type(direction)))\n\n if direction >3 or direction < 0:\n raise ValueError('direction must be 0, 1, 2 or 3, not {:d}'.format(direction))\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that there is a destination for the going action. If there isn't one, then it issues the NoGoMessage. | def before_going_check_destination(action, actor, direction, ctxt) :
if not action.going_to :
raise AbortAction(ctxt.world[NoGoMessage(action.going_from, direction)]) | [
"def report_going_default(action, actor, direction, ctxt) :\n msg = ctxt.world[WhenGoMessage(action.going_from, direction)]\n if msg :\n ctxt.write(msg)",
"def dispatch_one(self, msgcause, destinations):\n \n if destinations != None and len(destinations)>0:\n for next_hop, me... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We report the WhenGoMessage property, if it's not None. Other | def report_going_default(action, actor, direction, ctxt) :
msg = ctxt.world[WhenGoMessage(action.going_from, direction)]
if msg :
ctxt.write(msg) | [
"def generate_msg(self) -> typing.Optional[CommonMSG]:\n raise NotImplementedError(\"generate_msg: not implemented\")",
"def tellMeWhyNot(self):\n return \"You can't reach through the glass box.\"",
"def pre_send_message(self, msg):\r\n return msg",
"def send_message(self, msg):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Something is goingtoable if it is a door, if it is actually visited, or if it is the destination (we want to make sure the planned path doesn't go through unvisited rooms!) | def is_going_to_able(a) :
if ctxt.world[IsA(a, "door")] or ctxt.world[Visited(a)] :
return True
elif a == x :
return True
else :
return False | [
"def is_going_into_able(a) :\n if ctxt.world[IsA(a, \"door\")] or ctxt.world[Visited(x)] :\n return True\n elif a == x :\n return True\n else :\n return False",
"def is_going_into_able(a) :\n if ctxt.world[IsA(a, \"door\")] or ctxt.world[Visited(a)] :\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Something is goingintoable if it is a door, if it is actually visited, or if it is the destination (we want to make sure the planned path doesn't go through unvisited rooms!) | def is_going_into_able(a) :
if ctxt.world[IsA(a, "door")] or ctxt.world[Visited(x)] :
return True
elif a == x :
return True
else :
return False | [
"def is_going_into_able(a) :\n if ctxt.world[IsA(a, \"door\")] or ctxt.world[Visited(a)] :\n return True\n elif a == x :\n return True\n else :\n return False",
"def is_going_to_able(a) :\n if ctxt.world[IsA(a, \"door\")] or ctxt.world[Visited(a)] :\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Something is goingintoable if it is a door, if it is actually visited, or if it is the destination (we want to make sure the planned path doesn't go through unvisited rooms!) | def is_going_into_able(a) :
if ctxt.world[IsA(a, "door")] or ctxt.world[Visited(a)] :
return True
elif a == x :
return True
else :
return False | [
"def is_going_into_able(a) :\n if ctxt.world[IsA(a, \"door\")] or ctxt.world[Visited(x)] :\n return True\n elif a == x :\n return True\n else :\n return False",
"def is_going_to_able(a) :\n if ctxt.world[IsA(a, \"door\")] or ctxt.world[Visited(a)] :\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
At this point, we assume x is not an enterable, so we abort the action with the NoEnterMessage. | def before_entering_default(actor, x, ctxt) :
raise AbortAction(ctxt.world[NoEnterMessage(x)], actor=actor) | [
"def before_entering_default_enterable(actor, x, ctxt) :\n raise ActionHandled()",
"def before_entering_check_not_already_entered(actor, x, ctxt) :\n if x == ctxt.world[Location(actor)] :\n raise AbortAction(str_with_objs(\"{Bob|cap} {is} already on [the $x].\", x=x),\n actor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
By default, since we've passed all the checks, the actor can enter the enterable thing. | def before_entering_default_enterable(actor, x, ctxt) :
raise ActionHandled() | [
"def before_entering_check_not_possession(actor, x, ctxt) :\n loc = ctxt.world[Location(x)]\n while not ctxt.world[IsA(loc, \"room\")] :\n if loc == actor :\n raise AbortAction(\"{Bob|cap} can't enter what {bob} {is} holding.\", actor=actor)\n loc = ctxt.world[Location(loc)]",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implicitly exits and enters until actor is one level away from x. | def before_entering_implicitly_exit(actor, x, ctxt) :
# first figure out what the enterable which contains both x and
# the actor is. We go up the ParentEnterable location chains, and
# then remove the shared root.
actor_parent_enterables = [ctxt.world[ParentEnterable(actor)]]
while not ctxt.world[... | [
"def before_entering_check_not_possession(actor, x, ctxt) :\n loc = ctxt.world[Location(x)]\n while not ctxt.world[IsA(loc, \"room\")] :\n if loc == actor :\n raise AbortAction(\"{Bob|cap} can't enter what {bob} {is} holding.\", actor=actor)\n loc = ctxt.world[Location(loc)]",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensures that the actor is not already in or on x. | def before_entering_check_not_already_entered(actor, x, ctxt) :
if x == ctxt.world[Location(actor)] :
raise AbortAction(str_with_objs("{Bob|cap} {is} already on [the $x].", x=x),
actor=actor) | [
"def before_entering_check_not_possession(actor, x, ctxt) :\n loc = ctxt.world[Location(x)]\n while not ctxt.world[IsA(loc, \"room\")] :\n if loc == actor :\n raise AbortAction(\"{Bob|cap} can't enter what {bob} {is} holding.\", actor=actor)\n loc = ctxt.world[Location(loc)]",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |