query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Determines if the map object has the sight feature. | def check_map_obstacle_has_sight(self):
return self.map_obstacle.sight_range > 0 | [
"def has_wcs(self):\n return self.wcs is not None",
"def has_features(self): # 当前slot实例是否可抽取特征值\n return self.feature_dimensionality() != 0",
"def is_spatial(self):\n return self in FeatureTypeSet.SPATIAL_TYPES",
"def has_wcs(self):\n return self._wcs is not None",
"def has_feat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the current facing direction of the map_obstacle. | def get_current_facing_direction(self, DIRECTIONS=DIRECTIONS):
return self.map_obstacle.get_current_facing_direction(DIRECTIONS=DIRECTIONS) | [
"def get_direction(self):\n return self.actual_coordinates[2]",
"def get_direction(self):\n pt0 = self.get_start_location()\n pt1 = self.get_end_location()\n if self.is_latlon:\n return calculate_initial_compass_bearing(pt0, pt1)\n else:\n return azimuth(pt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if the map_obstacle is within the bounds of whatever is on screen at the moment. If the object is of a type that is capable of moving, and it is not on screen, then it is not moving. | def is_map_obstacle_in_screen_range(self):
raise NotImplementedError | [
"def check_for_obstacles(self):\n obs = False\n obs_p = []\n for point in self.obstacles:\n if -0.15 <= point[1] <= 0.15: # robot is 178mm wide\n # Obstacles should be less than or equal to 0.2 m away before being detected\n if 0 <= point[0] <= .2:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Based on the nodes in this threat zone, mark each main graph's nodes as members of this threat zone. | def mark_nodes_as_members_of_threat_zone(self):
for y in range(self.top_left_y, self.top_left_y + self.height):
for x in range(self.top_left_x, self.top_left_x + self.width):
main_node = self.main_graph[y][x]
main_node.threat_zones.add(self)
self.nod... | [
"def _set_node_lists(self, new):\n for edge in self.edges:\n edge._nodes = self.nodes",
"def link_nodes_and_edges_to_zones(self):\n\n # Clear old information.\n for z in self.Zones:\n z.Nodes.clear()\n z.Edges.clear()\n\n self.set_zones_ids()\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates which node has the obstacle. This does not recompute the graph based on this new information. Each threat zone is responsible for updating its own map objects. So there will never be a time when the current x value attached to the map_obstacle does not represent the actual previous location. | def update_obstacle_location(self):
# find the previous location of the obstacle
old_y = self.map_obstacle.y
old_x = self.map_obstacle.x
# remove it from the main graph
self.main_graph[old_y][old_x].contents.remove(self.map_obstacle)
# get the latest location
s... | [
"def update_obstacles(self, new_obs):\n self.obstacles = new_obs",
"def add_obstacle(self, x, y):\n self.BOARD[y][x].traversable = False\n self.board_array[y][x] = 1",
"def set_obstacle(self):\n self.state = self.Obstacle",
"def add_new_obstacle(self, obstacle):\n self.obsta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the node is in the range of the threat zone. | def is_node_in_threat_zone(self, y, x):
y_condition = self.top_left_y <= y < self.top_left_y + self.height
x_condition = self.top_left_x <= x < self.top_left_x + self.width
return y_condition and x_condition | [
"def is_in_range(data):\n return (data.apparentTemperatureHigh >\n berm_const.OVERSEED_DAYTIME_LOW and\n data.apparentTemperatureHigh <\n berm_const.OVERSEED_DAYTIME_HIGH\n ) and (\n data.apparentTemperatureLow >\n berm_const.OVERSEED_NIGH... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the node is in the sight range of the threat. | def is_node_in_sight_range(self, y, x, skip_range_check=False):
if not skip_range_check:
if not self.is_node_in_threat_zone(y, x):
return False
if self.sight_range == 0:
return False
# TODO: sight range can be blocked by collidable map objects. But this
... | [
"def check_map_obstacle_has_sight(self):\n return self.map_obstacle.sight_range > 0",
"def is_node_in_threat_zone(self, y, x):\n y_condition = self.top_left_y <= y < self.top_left_y + self.height\n x_condition = self.top_left_x <= x < self.top_left_x + self.width\n return y_condition a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the cost of the node w.r.t this threat zone. Turn off consider_sight_range when not in the threat zone. | def calculate_node_cost(self, y, x, consider_sight_range=True, PENALTIES=PENALTIES):
penalty = 0
# The node is probably in the threat zone because otherwise why would
# this cost function be called? Only the nodes that are members of the
# current threat zone would have a reference to t... | [
"def determine_cost(self):\n pass",
"def calculate_cost(self):\n costs = {}\n if np.abs(self.agent.get_position()[1]) > self.y_lim:\n costs['cost_outside_bounds'] = 1.\n if self.agent.velocity_violation:\n costs['cost_velocity_violation'] = 1.\n # sum all c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws a path on an image of the current map. The path must be an iterable of nodes to visit in (y, x) format. | def draw_path(self, path):
palettes = pokemontools.map_gfx.read_palettes(self.config)
map_image = pokemontools.map_gfx.draw_map(self.map_group_id, self.map_id, palettes, show_sprites=True, config=self.config)
for coordinates in path:
y = coordinates[0]
x = coordinates[1]... | [
"def plot_path(self,\n gridmap: np.array,\n path: Tuple[List[int], List[int]],\n visited: Tuple[List[int], List[int]]) -> plt.Figure:\n fig = plt.figure(figsize=(15, 10))\n plt.title(\"Obstacle Map and Path (A* Planner)\", fontsize=18)\n plt.xl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a dictionary mapping the index of each [ command with its corresponding ] command. If the program is illformatted, raise a RuntimeError. | def _preprocess(program: str) -> Dict[int, int]:
i_map = {}
stack = []
for p_ptr in range(len(program)):
if program[p_ptr] == "[":
stack.append(p_ptr)
elif program[p_ptr] == "]":
if len(stack) == 0:
raise RuntimeError
... | [
"def get_indexes(prog):\n # 'Nice' one-liner that iterates through prog, reads each line and stores if it's jmp or nop command.\n return {idx:val for idx,val in enumerate(prog) if read_line(val)[0] in ['jmp','nop']}",
"def _commands(self) -> Dict[str, List[str]]:\r\n pass",
"def indexed_undefines(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the sum of absolute differences between each index in the given tuple and the memory array created by interpreting the given program. | def _evaluate(expect: Tuple[int, ...], program: str) -> int:
actual = FitnessEvaluator.interpret(program, len(expect))
z = sum(abs(x - y) for x, y in zip(expect, actual))
return z | [
"def diff_index_calc(oct_abund_list1, oct_abund_list2):\n rel_index_list = []\n abs_index_list = []\n smty_index_list = []\n for i in range(10):\n abund_data_array = sc.asarray(oct_abund_list1[i], dtype='double')\n abund_sim_array = sc.asarray(oct_abund_list2[i], dtype = 'double')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a single random program object no larger than max_len | def generate_random_program(max_len: int) -> Program:
# TODO: min length of loop sequence 12
# TODO uncomment valid cmds and program_str
if max_len == 0:
max_len = 35
sequence_str = ""
valid_commands = "><+-"
for _ in range(random.randint(0, max_len)):
sequence_str += valid_com... | [
"def generate():\n s = random_data.random_bytes(100)\n return generate_from_string(s)",
"def create_program(fe: FitnessEvaluator, max_len: int) -> str:\n\n # mut_prob = {\"<\": 0.8, \">\": 0.8, \"+\": 0.6, \"-\": 0.6, \"[\": 0.1, \"]\": 0.1}\n\n # new_population: List[Program] = []\n\n # k = 1000\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a program string no longer than max_len that, when interpreted, populates a memory array that exactly matches a target array. Use fe.evaluate(program) to get a program's fitness score (zero is best). | def create_program(fe: FitnessEvaluator, max_len: int) -> str:
# mut_prob = {"<": 0.8, ">": 0.8, "+": 0.6, "-": 0.6, "[": 0.1, "]": 0.1}
# new_population: List[Program] = []
# k = 1000
# N = 0.5 # N is top percentile for selection process
converges = True
gen_no = 0
while 1:
... | [
"def generate_random_program(max_len: int) -> Program:\n # TODO: min length of loop sequence 12\n # TODO uncomment valid cmds and program_str\n\n if max_len == 0:\n max_len = 35\n\n sequence_str = \"\"\n valid_commands = \"><+-\"\n for _ in range(random.randint(0, max_len)):\n sequen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience function to retrieve a template filename from the config | param key (str) | return value (str) | def _get_config_template(self, key):
tmp_path = self._get_config_value('templates', 'path') + key
return tmp_path | [
"def get_template_filename(template):\n config = read_config(SETTINGS_PATH)\n #String templates\n if (template in STRING_TEMPLATES):\n options = config.options(STRING_TEMPLATES_SECTION) \n for option in options:\n if (option==template):\n #Get root path for the temp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the client address formatted for logging. Only lookup the hostname if really requested. | return hostname (str) | def address_string(self):
if self.server.log_ip_activated:
host = self.client_address[0]
else:
host = '127.0.0.1'
if self.server.resolve_clients:
return socket.getfqdn(host)
else:
return host | [
"def address_string(self):\n\n host, port = self.client_address[:2]\n return host # socket.getfqdn(host)",
"def get_hostname():\n return socket.gethostname()",
"def get_host(self) -> str:\n return self.socket.getsockname()[0]",
"def client_hostname(self):\n hostname = self.find... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite the default log_request() method to make it a noop. We call the original method ourselves to pass also the response size. | def log_request(self, code='-', size='-'):
pass | [
"def log_request(self, code='-', size='-'):\n if self._log_data is None:\n return BaseHTTPRequestHandler.log_request(self, code, size)\n code = None if code == '-' else int(code)\n size = None if size == '-' else int(size)\n self._log_data.update(code=code, size=size)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends the default startpage. |param message (str) Optional message that should appear on startpage | def _send_homepage(self, message=''):
template_filename = self._get_config_template('homepage')
text = read_template(
template_filename,
title=SERVER_NAME,
header=SERVER_NAME,
msg=message)
self._send_response(text, 200) | [
"def send_message(self, msg,switch=0):\n self.message_tree_class.store.prepend(None, [msg])\n if switch:\n self.console.set_current_page(0)\n else:\n pass",
"def send_start_message(self, chat_id=None, call=None):\n text = self._form_text_main_manu(chat_id)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a block page which tells the user that the URL has been blocked for some reason. | param reason Reason, why page has been blocked (str) | def _send_blocked_page(self, reason):
template_filename = self._get_config_template('blocked')
text = read_template(
template_filename,
title=SERVER_NAME,
header=SERVER_NAME,
comment=reason)
self._send_response(text,... | [
"async def block(self, ctx, *, url):\n blocked = await self.db.get('blocked', [])\n if url in blocked:\n return await ctx.send('😾 That image is already blocked.')\n blocked.append(url)\n await self.db.set('blocked', blocked)\n await ctx.send('😾 That image will not be ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send the result page for a new created short URL. | param shorthash new shorthash for URL | def _send_return_page(self, shorthash):
template_filename = self._get_config_template('return')
if shorthash == '1337':
messagetext = '<p>Hey, you are 1337!</p>'
else:
messagetext = ''
text = read_template(
template_filename,
... | [
"def create_short_url():\n user_input = request.form[\"URL\"]\n long_url = user_input\n short_url = \"\"\n try:\n if long_url and not long_url.startswith(\"http\"):\n long_url = \"https://\" + long_url\n if long_url:\n short_url = random_string()\n attribut... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send HTTP status code 301 | param new_url (str) | def _send_301(self, new_url):
try:
self.send_response(301)
self.send_header('Location', new_url)
self.send_header('Content-type', 'text/html')
self.end_headers()
except UnicodeEncodeError:
self._send_internal_server_error() | [
"def redirect(url, code=307):\n response.status = code\n response.header['Location'] = url\n raise BreakTheSparrow(\"\")",
"def redirect(location, status=302, trusted=False):",
"def redirect(url, code=302):\n exc = status_map[code]\n raise exc(location=url).exception",
"def redirect(url):",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send HTTP status code 500 due to a database connection error | param header_only (bool) | def _send_database_problem(self):
template_filename = self._get_config_template('databaseerror')
text = read_template(
template_filename,
title='%s - Datebase error' % SERVER_NAME,
header='Database error')
if not text:
self._send_internal_server_er... | [
"def handler500(request):\n response = render(request, '500.html')\n response.status_code = 500\n return response",
"def handler500(request):\n response = render_to_response('500.html', {}, RequestContext(request))\n response.status_code = 500\n return response",
"def error_500(request):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split the URL, decode the Network location part and unsplit the URL again | param url (str) | return url_splitted (str) | def _split_url(self, url):
url_split = urlsplit(url)
try:
if url_split.netloc is not None and url_split.netloc.find(" ") > 0:
return None
decoded_netloc = url_split.netloc.decode("utf-8").encode("idna")
url_parts = (
url_split.scheme,
... | [
"def urlsplit(url):\n netloc = urlparse.urlsplit(url).netloc\n return _extract(netloc)",
"def split_url(url: str):\n if url.endswith(\".git\"):\n url = url[:-4]\n return url[url.find(\"://\") + 3:].split(\"/\")",
"def _urlparse_splitnetloc(url, start=0):\r\n\r\n # By default, the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper function which returns the SHA1hash of given set of strings | param args set of strings (str) | return hash | def _get_hash(self, *args):
url_hash = hashlib.sha1()
try:
for value in args:
value = unicode(value).encode('utf-8', 'replace')
url_hash.update(value)
return url_hash.hexdigest()
except UnicodeDecodeError:
return None | [
"def hash_(*args):\n return hash(\"\".join([str(x) for x in args]))",
"def nice_hash(*args):\n h = sha1()\n for item in args:\n h.update(unicode(item))\n return b32encode(h.digest())",
"def _hash_args(args, secret=None, prefix = \"oauth_signature\"):\n # get the parameters for the sig calc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is intented to do the part of inserting to database and fetching (if already available) short URL It will return the short hash in case of everything worked well None in case of there was general issue with the URL 1 in case of there was an issue with the database. 2 in case of the hash is already in data... | def _insert_url_to_db(self, url=None):
if url and len(url) < 4096 and not self.server.hostname.lower() in url.lower():
# Now check, whether some protocol prefix is
# available. If not, assume http:// was intended to put
# there.
if not '://' in url:
... | [
"def _create_url_hash(url):\n try:\n url_obj = Urlshort.objects.create(hash_value=\"\", original_url=\"\")\n url_obj.save()\n url_obj = Urlshort.objects.latest(\"id\")\n\n url_hash = _url_id_encode(url_obj.id)\n url_encoded = url.encode(\"utf8\")\n Urlshort.objects.filte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows a page with some statistics for a short URL | param shorthash (string) | def _show_link_stats(self, shorthash=None):
# First doing some basis input validation as we don't want to
# get fucked by the Jesus
if shorthash == None or not shorthash.isalnum():
self._send_404()
return
else:
blocked = self._db.is_hash_blocked(short... | [
"def stats(short_url):\n stats = get_stats(short_url)\n click.echo(stats)",
"def statistics():\n return render_template('statistics.html'), 200",
"def get_usage():\n return render_template(\n 'pages/usage.html', \n usage = True\n ), 200",
"def show_url(request):\n if request.GE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
determines whether e is contained in the list | def contains(list, e):
for elem in list:
if elem == e:
return True
return False | [
"def _listContains(self, l, entry):\n for i in range(0, len(l)):\n if l[i] == entry:\n return True\n return False",
"def exist(self,list,a):\r\n\t\ti = 0\r\n\t\tfor elem in list:\r\n\t\t\tif (elem == a):\r\n\t\t\t\ti=i+1\r\n\t\tif (i>0):\r\n\t\t\treturn True\r\n\t\telse:\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads key argument from stream. If taproot is set to True allows both xonly and sec pubkeys. If taproot is False will raise when finds xonly pubkey. | def read_from(cls, s, taproot: bool = False):
first = s.read(1)
origin = None
if first == b"[":
prefix, char = read_until(s, b"]")
if char != b"]":
raise ArgumentError("Invalid key - missing ]")
origin = KeyOrigin.from_string(prefix.decode())
... | [
"def readPubkey():\n return run(\n [\"pkcs15-tool\", \n \"--read-public-key\", Crypto.PKCS15_KEY_NUMBER])",
"def read_public_key(f: IO[str]) -> Tuple[str, str, str, str]:\n data = f.read()\n try:\n kind, key, comment = data.split(\" \")\n if kind.startswith(\"ssh-\") and comment:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a DataFrame of trips from the 2018 data and returns each pair of adjacent stops for each trip separately in a DataFrame | def create_adjacent_stop_pairs(trips):
stop_pairs = []
sorted_trips = trips.sort_values(
['TRIPID', 'PROGRNUMBER']).reset_index(drop=True)
# For each trip match up pairs of adjacent stops and calculate how long it
# took to travel between them
for trip_id in sorted_trips['TRIPID'].unique(... | [
"def two_stop_trip(self, start: str, end: str, airports: list) -> List[list]:\n paths = []\n visited = []\n if start in self._vertices and end in self._vertices:\n for i in list(self.get_neighbours(start)):\n for j in list(self.get_neighbours(i)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The 2021 Dublin Bus data uses Stop IDs instead of the actual stop numbers presented to the public. This method tries to extract the stop number from the stop name and if this fails it tries to extract it from the ID instead. Args | def parse_stop_num(stop_name, stop_id):
try:
stop_num = int(stop_name.split(" ")[-1])
except ValueError:
# stop number isn't in the name
# try parse out of ID instead
stop_num = int(stop_id.split("DB")[-1])
return stop_num | [
"def stop_id(stop_id):\n stop=bus_stops_collection.find({\"stop_id\": stop_id})\n return stop",
"def get_stop_info(stops):\n\tapi_url = 'http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=sf-muni&stopId='\n\t\"\"\"Stop_dict = {bus_name:'38',\n\t\t\t\t\tminutes: 7,\n\t\t\t\t\tstop_loc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test main call to read_configs() which returns both config and auth | def test_read_valid_configs(self):
args = argparse.Namespace(server=None, force=False)
with open(self._config) as config_f:
with open(self._auth) as auth_config_f:
(config_data, auth_tuple) = imageroller.main.read_configs(
args,
config_... | [
"def mocked_read_config():\n # login, passwd, DEFAULT_RECIPIENT, PROVIDER, CUSTOM_PROVIDER_URLS\n data = (\"03141592653\", \"MySecr3t\", None, \"yesss\", None)\n with mock.patch(\"YesssSMS.CLI.CLI.read_config_files\", return_value=data):\n yield",
"def testGetConfig():\n configs = GetConfig()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test config with no [DEFAULT] section Subsequently, the ConcurrentWorkers will not be defined | def test_no_default(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_config(
self._cmd_args,
imageroller.test.get_config_parser(self._no_default))
# ConcurrentWorkers is the first value that is checked
self.assertEqual(str(cm.exc... | [
"def test_no_workers(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_config(\n self._cmd_args,\n imageroller.test.get_config_parser(self._no_workers))\n self.assertEqual(str(cm.exception),\n \"Config must cont... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test config with no ConcurrentWorkers key | def test_no_workers(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_config(
self._cmd_args,
imageroller.test.get_config_parser(self._no_workers))
self.assertEqual(str(cm.exception),
"Config must contain Concurre... | [
"def test_no_default(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_config(\n self._cmd_args,\n imageroller.test.get_config_parser(self._no_default))\n # ConcurrentWorkers is the first value that is checked\n self.assertEqual... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test config with no server sections | def test_no_server(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_config(
self._cmd_args,
imageroller.test.get_config_parser(self._no_server))
self.assertEqual(str(cm.exception),
"You must configure at least on... | [
"def test_nats_stan_config(app):\n assert app.config.get('NATS_SERVERS')\n assert app.config.get('NATS_CLIENT_NAME')\n assert app.config.get('NATS_CLUSTER_ID')\n assert app.config.get('NATS_FILER_SUBJECT')\n assert app.config.get('NATS_QUEUE')",
"def testFakeLongHandConfigurables(self):\n co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test config with no server sections cmdline Server is specified on the command line that is not configured | def test_no_server_cmdline(self):
invalid_server = "invalid.example.com"
self._cmd_args.server = invalid_server
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_config(
self._cmd_args,
imageroller.test.get_config_parser(self._no_server)... | [
"def test_no_server(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_config(\n self._cmd_args,\n imageroller.test.get_config_parser(self._no_server))\n self.assertEqual(str(cm.exception),\n \"You must configure... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test server config with no SaveTimeoutMinutes | def test_server_no_save_timeout(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_config(self._cmd_args,
imageroller.test.get_config_parser(
self._server_no_save_timeout))
self.assertE... | [
"def test_timeout_setting(self):\n self.assertEqual(self.es.sse_kwargs.get('timeout'),\n config.socket_timeout)",
"def fxt_sdp_start_up_test_exec_settings(\n integration_test_exec_settings: fxt_types.exec_settings,\n):\n integration_test_exec_settings.time_out = 30",
"def te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test server config with no RetainImageMinutes | def test_server_no_retain_image(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_config(self._cmd_args,
imageroller.test.get_config_parser(
self._server_no_retain_image))
self.assertE... | [
"def test_server_no_save_timeout(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_config(self._cmd_args,\n imageroller.test.get_config_parser(\n self._server_no_save_timeout))\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test server config with no Region | def test_server_no_region(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_config(self._cmd_args,
imageroller.test.get_config_parser(
self._server_no_region))
self.assertEqual(
... | [
"def test_no_server(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_config(\n self._cmd_args,\n imageroller.test.get_config_parser(self._no_server))\n self.assertEqual(str(cm.exception),\n \"You must configure... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test auth config with no [AUTH] section | def test_no_section(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_authconfig(
imageroller.test.get_config_parser(self._no_section))
self.assertEqual(str(cm.exception), "AuthConfig must contain [AUTH]") | [
"def test_auth0_config_anon(anontestapp, registry):\n _test_auth_config(anontestapp, registry)",
"def test_rest_call__default_auth(self):\n assert self._rest_call_auth_test() is self.syn.credentials",
"def test_auth0_config_admin(testapp, registry):\n _test_auth_config(testapp, registry)",
"def t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test auth config with no ApiUser key | def test_no_user(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_authconfig(
imageroller.test.get_config_parser(self._no_user))
self.assertEqual(str(cm.exception), "AuthConfig must contain ApiUser") | [
"def test_blank_user(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_authconfig(\n imageroller.test.get_config_parser(self._blank_user))\n self.assertEqual(str(cm.exception), \"AuthConfig must contain ApiUser\")",
"def test_auth0_config_anon(anon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test auth config with a blank user | def test_blank_user(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_authconfig(
imageroller.test.get_config_parser(self._blank_user))
self.assertEqual(str(cm.exception), "AuthConfig must contain ApiUser") | [
"def test_no_user(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_authconfig(\n imageroller.test.get_config_parser(self._no_user))\n self.assertEqual(str(cm.exception), \"AuthConfig must contain ApiUser\")",
"def test_auth0_config_anon(anontestap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test auth config with no ApiKey key | def test_no_key(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_authconfig(
imageroller.test.get_config_parser(self._no_key))
self.assertEqual(str(cm.exception), "AuthConfig must contain ApiKey") | [
"def test_blank_key(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_authconfig(\n imageroller.test.get_config_parser(self._blank_key))\n self.assertEqual(str(cm.exception), \"AuthConfig must contain ApiKey\")",
"def test_auth0_config_anon(anontes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test auth config with no a blank key | def test_blank_key(self):
with self.assertRaises(ConfigError) as cm:
imageroller.main.read_authconfig(
imageroller.test.get_config_parser(self._blank_key))
self.assertEqual(str(cm.exception), "AuthConfig must contain ApiKey") | [
"def test_auth0_config_anon(anontestapp, registry):\n _test_auth_config(anontestapp, registry)",
"def test_no_key(self):\n with self.assertRaises(ConfigError) as cm:\n imageroller.main.read_authconfig(\n imageroller.test.get_config_parser(self._no_key))\n self.assertEqua... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test reading the correct values from a valid auth config | def test_valid(self):
auth_tuple = imageroller.main.read_authconfig(
imageroller.test.get_config_parser(self._valid))
self.assertTupleEqual(auth_tuple, (AUTH_DATA["ApiUser"],
AUTH_DATA["ApiKey"])) | [
"def test_read_valid_configs(self):\n args = argparse.Namespace(server=None, force=False)\n with open(self._config) as config_f:\n with open(self._auth) as auth_config_f:\n (config_data, auth_tuple) = imageroller.main.read_configs(\n args,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
help fuction for the command quit | def help_quit(self):
print("Quit command to exit the program") | [
"def help_quit(self):\n\n print(\"Quit command to exit the program\")\n print()",
"def help_exit():\n print(\"Exits the application. Shorthand: x, q, or Ctrl-D.\")",
"def quit_prompt():",
"def menu_quit():\n return \"Quit\"",
"def test_quit(self):\n _help = 'Quit method to exi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
help fuction for the command EOF | def help_EOF(self):
print("EOF command to exit the program") | [
"def help_EOF(self):\n\n print(\"End of file\")\n print()",
"def help_EOF(self):\n print(\"ctrl+d\")\n print(\"\\tClean up and close CLI cleanly.\")",
"def test_EOF(self):\n _help = 'EOF method to exit cmd program\\n'\n with patch('sys.stdout', new=StringIO()) as f:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
help function for the create command | def help_create(self):
print("create instances") | [
"def help_create(self):\n print(CREATE)",
"def help_create(self):\n print(\"Usage: create <class name>\")",
"def help_create(self):\n\n print(\"Create an object.\")\n print(\"Usage: create <class name>\")\n print()",
"def create(ctx):",
"def test_create(self):\n _he... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
help function for the command destroy | def help_destroy(self):
print("delete an instance based on the class name and id") | [
"def help_destroy(self):\n print(\"Usage: destroy <class name> <id>\")",
"def help_destroy(self):\n\n print(\"Destroy an object.\")\n print(\"Usage: destroy <class name> <id>\")\n print()",
"def help_delete(self):\n print(DELETE)",
"def help_quit(self):\n print(\"Quit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test if val is a float | def is_float(self, val):
try:
float(val)
return True
except ValueError:
return False | [
"def could_be_float(val):\n if val == None:\n return False\n\n if isinstance(val, float):\n return True\n\n # allow coercion from str\n if isinstance(val, (str, unicode)):\n try:\n f = float(val)\n if not isinstance(f, float)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test if val is an integer | def is_int(self, val):
try:
int(val)
return True
except ValueError:
return False | [
"def check_val_int(val):\n\treturn isinstance(val, int)",
"def is_integer_value(val: Union[int, str]) -> bool:\n try:\n int(val)\n return True\n except ValueError:\n return False",
"def could_be_int(val):\n if val == None:\n return False\n\n if isinstance(val,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes the GitHub API client and prefetches the `organization` and repositories | def __init__(self, github_access_token, organization):
self.github_access_token = github_access_token
self.organization = organization
self.cli = Github(self.github_access_token)
self.org = self.cli.get_organization(organization)
# http://pygithub.readthedocs.io/en/latest/github... | [
"def __fetch_org(self):\n try:\n resp = requests.get(\"https://api.github.com/orgs/{}\".format(self.name), auth=(username, password))\n\n if resp.status_code != 200:\n if resp.status_code == 401:\n Utils.handle_auth_error()\n\n print(resp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a Markdownformatted message for this organization's pull requests | def pull_request_reminder(self):
greeting = random.choice([u'Hola', u'Como estas', u'Greetings', u'你好', u'Hello', u'Aloha', u'Ciao', u'Salut', u'안녕하세요', u'こんにちは', u'שלום', u'chào bạn',])
def pluralize(s, num):
plural_suffix = '' if num == 1 else 's'
value = '%s %s' % (num, s + p... | [
"def description(self):\n return self._github_issue.body",
"def as_markdown(self) -> str:\n output = f\"## {self.title}\\n\\n\"\n output += f\"* {self.time}\\n* {self.feed}\\n* {self.link}\\n\\n\"\n output += f\"{self.summary}\\n\\n---\"\n return output",
"def format_changes(g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
synthesize maze.array and characters' position to create a new graphic array to be rendered by plt | def update_synthetic_graph_array(self):
# create maze copy
array = self.maze.array.copy()
# delete the dot eaten by agent
self.dots.array[tuple(self.agent.position)] = 0
# draw the remaining dots
array[self.dots.mask()] = self.dots.color
# draw characters
... | [
"def _updateGlyphs(self, pos, char=None):\n allVertices = []\n allIndices = []\n for k in range(len(self.text) - pos):\n idx = pos + k\n # Metric\n off, kern = self._updateMetric(idx, self.text[idx])\n # Handle special char\n if self.text[i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
query if exists timestamp from the ilm_ilm table | def check_observation_exists(dt, path=''):
conn = None
row = dict()
try:
params = utils.config(path)
conn = psycopg2.connect(**params)
cur = conn.cursor(cursor_factory=RealDictCursor)
# cur = conn.cursor()
condition_y = f"date_part('year', timestamp) = {dt.year}"
... | [
"def test_timestamp_not_found(self, l):\n extract_columns(data=self.data, columns=['a'], timestamps=['timestamp'])\n l.check(\n ('pynts.util', 'WARNING', \"Couldn't find timestamps '['timestamp']' in data, using 'ts' instead\"),\n )",
"def _exists(self, model, identity, time):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The titles are currently stored in our dataframe in a list of size 1 with all the words mushed together. This method uses regex to separate the title based on capital letters | def fix_title(title):
words = re.findall('[A-Z][^A-Z]*', title[0])
final_str = ""
for word in words:
final_str += word + " "
return final_str.strip() | [
"def extract_titles(self, preprocessed_input):\n titles = []\n\n if (preprocessed_input.find(\"\\\"\") != -1):\n\n # if the doc contains quotations\n start = preprocessed_input.find(\"\\\"\")\n while start != -1:\n end = preprocessed_input.find(\"\\\"\",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in a properly formatted title and mushes all the words together by removing the spaces. It does this to ensure that the given title is formatted the same way it was in our original dataframe. | def mush_title(title):
words = title.split(" ")
mushed_title = ""
for word in words:
mushed_title += word
return [mushed_title] | [
"def fix_title(title):\n words = re.findall('[A-Z][^A-Z]*', title[0])\n final_str = \"\"\n for word in words:\n final_str += word + \" \"\n return final_str.strip()",
"def book_title(title):\n # this will capitalize the first letter of every word\n title = title.title()\n p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Se ejecuta cada consulta libre | def aplicarConsultasLibres(self):
for consultaCL in self.ConsultasLibres:
print(consultaCL)
resultoCL=self.consulta(consultaCL)
for resul in resultoCL['results']['bindings']:
uri = resul['s']['value']
uri=uri.replace('http://dbpedia.or... | [
"def ejecutarproceso(self):\n self.generarConsultasLibres()\n self.aplicarConsultasLibres()\n self.generarCombinaciones()\n self.generarConsultasConexion()\n self.archivoSalida()",
"def generarConsultasConexion(self):\n for parRecursos in self.CombiConsultaLibre:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Genera consultas de conexion entre dos recursos | def generarConsultasConexion(self):
for parRecursos in self.CombiConsultaLibre:
parRecursosL0=self.limpiaRecursos(parRecursos[0])
parRecursosL1=self.limpiaRecursos(parRecursos[1])
if self.nivel_profundidad>=1:
consultasparql = self.busConex1 % (pa... | [
"def pesquisar_condominios(self):\n\n lst_dic = []\n try:\n conn = psycopg2.connect(self.ge_dic_param_sis['DSN'])\n conn.set_client_encoding(self.ge_dic_param_sis['CLIENTEENCODING'])\n cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n cur.execut... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ejecuta de forma sequencial el proceso de consultas a DBpedia y genera un archivo output | def ejecutarproceso(self):
self.generarConsultasLibres()
self.aplicarConsultasLibres()
self.generarCombinaciones()
self.generarConsultasConexion()
self.archivoSalida() | [
"def executar(self):\n\t\tpass",
"def all_gen(self):\n\n self.connecting()\n print(\"connexion au serveur MYSQL...\")\n time.sleep(1)\n print(\"connexion établie\")\n print(\"Création de la base de donnée...\")\n self.schema_gen()\n print(\"Création des catégories ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
args should not be allowed in a task definition | def test_010_args(self):
with self.assertRaisesRegex(RuntimeError, "Task .* contains an unsupported parameter \"[*]args\""):
self.get_caller([ArgsTaskOverride]) | [
"def assert_task_args(cls, args: Dict[str, Any]):\n return",
"def task(*args, **kwargs):\n print(f\"task declared, args: {args}, kwargs:{kwargs}\")\n return FalseCeleryApp",
"def test_task_with_args():\n assert HELLO_WORLD_STR == hello_world_with_args()",
"def shared_task(*args, **kwar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test task override with kwargs | def test_020_kwargs(self):
caller = self.get_caller([KwargsTaskOverride])
self.assertEqual(["A", "B"], caller("A", "B")) | [
"def setup_task(self, *args, **kwargs):\n pass",
"def test_taskify_apply_with_kwargs(self):\n fixtures.task_divide.apply_async(kwargs={\"b\": 5, \"a\": 0})\n\n task = Task.objects.first()\n self.assertEqual(task.function_name, \"tests.fixtures.task_divide\")\n self.assertEqual(t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get urlid via url query in database. | def get_urlid(self, url):
sql = "select rowid from urllist where url='%s'" % (url)
res = self.cur.execute(sql).fetchone()
if res is None:
return 0
else:
return res[0] | [
"def get_id(url):\n\n return re.search(GET_ID_REGEX_URL, url)[0]",
"def get_page_id(page_url):\r\n db = connect()\r\n cursor = db.cursor()\r\n sql_statement = \"\"\"\r\n SELECT page_id FROM `domain_pages` WHERE page_url = %(d)s\r\n \"\"\"\r\n try:\r\n cu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the linkrelationship in the index database. | def save_pr(self):
sql = "drop table if exists pagelink"
self.cur.execute(sql)
sql = "create table pagelink(urlid integer, fromids text, toids text, pagerank real)"
self.cur.execute(sql)
for urlid in self.url_ids:
fromids = ' '.join([str(v) for v in self.from_ids[urlid]])
toids = ' '.join([str(... | [
"def mark_as_indexed(self, con, url):\n con.execute(\"insert into Indexed_Links \\\n values ('{:s}')\".format(url))\n self.dbcommit(con)",
"def save(self, node):\n if node:\n nextId = node.nref.nodeId if node.nref else None\n record = dict(nextId=nextId, child... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the pagerank scores from multiinterations. | def pagerank(self, limit=20):
for urlid in self.url_ids:
self.all_scores[urlid] = 1.0
for i in range(limit):
for urlid in self.url_ids:
score = self.all_scores[urlid]
for fromid in self.from_ids[urlid]:
score += self.all_scores[fromid] / \
(len(self.from_ids[fromid])+len(self.to... | [
"def page_rank_score(self, rows):\n pageranks = dict([(row[0], self.con.execute('select score from pagerank where urlid=%d'\n % row[0]).fetchone()[0]) for row in rows])\n maxrank = max(pageranks.values())\n normalizedscores = dict([(u, float(l)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the new transition using `time_step` to the replay buffer. Adds the transition from `self._prev_timestep` to `time_step` by `self._prev_action`. | def add_transition(self, prev_time_step, prev_action, time_step):
assert prev_time_step is not None
legal_actions = (
prev_time_step.observations["legal_actions"][self.player_id])
legal_actions_mask = np.zeros(self._num_actions)
legal_actions_mask[legal_actions] = 1.0
... | [
"def _add_trajectory(self, prev_time_step, action, new_time_step):\n\n traj = tf_agents.trajectories.trajectory.from_transition(\n prev_time_step, action, new_time_step)\n\n self.replay_buffer.add_batch(traj)\n self.replay_buffer_position += 1\n\n if self.replay_buffer_positio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a valid epsilongreedy action and valid action probs. Action probabilities are given by a softmax over legal qvalues. | def _epsilon_greedy(self, info_state, legal_actions, epsilon):
probs = np.zeros(self._num_actions)
if np.random.rand() < epsilon:
action = np.random.choice(legal_actions)
probs[legal_actions] = 1.0 / len(legal_actions)
else:
info_state = np.reshape(info_state,... | [
"def get_greedy_actions(self, state):\n state_action_values = self.get_action_values(state) # What are the value that we could get from current state\n\n max_action_value = max(state_action_values) # What is the higher value\n max_value_indices = [i for i, value in enumerate(state_action_valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Context manager to temporarily overwrite the mode. | def temp_mode_as(self, mode):
previous_mode = self._mode
self._mode = mode
yield
self._mode = previous_mode | [
"def cooked_mode(self) -> ContextManager[None]:",
"def raw_mode(self) -> ContextManager[None]:",
"def __update_saved_mode(self, value):\n self._current_mode = value\n self.adb._current_mode = value\n self.shell._current_mode = value\n self.fastboot._current_mode = value",
"def norm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
通过查找到哪些为 O 的元素,来决定其余为 O 的元素不能为 X 来解决问题 1. 找出所有为 O 的元素 2. 找到边界 O 3. 与边界 O 相连的不能为 X | def solve(self, board: List[List[str]]) -> None:
invalidPosList, validPosList = set(), set()
lenBoard = len(board)
for i, iBoard in enumerate(board):
widthBoard = len(iBoard)
for j, item in enumerate(iBoard):
if item == 'O':
# 在边界上的 O 元... | [
"def check_neighbours(self, i,j):\r\n \r\n if (i == 0):\r\n if (self.objects[i+1, j] == 1 or self.objects[i, j+1] == 1 or self.objects[i, j-1] == 1):\r\n return True\r\n elif (i == self.N-1):\r\n if (self.objects[i-1, j] == 1 or self.objects[i, j+1] == 1 or ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set the variable for the softwareAutoPID emit signal to notify Thread store it in settings | def ITC_useAutoPID(self, boolean):
self.temp_ITC_useAutoPID = boolean
self.MTsigs["ITC"]["useAutocheck"].emit(boolean)
settings = QSettings("TUW", "CryostatGUI")
settings.setValue("ITC_useAutoPID", int(boolean))
del settings | [
"def _update_PID(self):\n self.pid = PID(p=self.paramP, i=self.paramI, d=self.paramD, setpoint=self.voltageSetpoint, memory=self.paramMemory)",
"def set_pid(self,san,key,val='',test=0):\n if val == str(self.pid):\n return (0,'')\n if self.state <> ObjState.created:\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
restore a preset from a json file | def tempcontrol_preset_restore(self, filename: str) -> None:
if filename == "-":
return
filename = os.path.join(self.tempcontrol_presets_path, str(filename) + ".json")
# print(filename)
try:
with open(filename) as f:
tempcontrol_preset = json.loads... | [
"def restore(self, filename=\".azimint.json\"):\n logger.debug(\"Restore\")\n if not os.path.isfile(filename):\n logger.error(\"No such file: %s\" % filename)\n return\n data = json.load(open(filename))\n setup_data = { \"poni\": self.poni.setText,\n# \"dete... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save the current tempcontrol configuration (self.tempcontrol_conf) as a preset | def tempcontrol_preset_save(self):
with open(
self.tempcontrol_presets_path
+ "{}.json".format(self.tempcontrol_preset_currentFilename),
"w",
) as output:
output.write(json.dumps(self.tempcontrol_conf)) | [
"def tempcontrol_preset_restore(self, filename: str) -> None:\n if filename == \"-\":\n return\n filename = os.path.join(self.tempcontrol_presets_path, str(filename) + \".json\")\n # print(filename)\n try:\n with open(filename) as f:\n tempcontrol_pre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
store key and value in self.tempcontrol_conf | def tempcontrol_conf_store(self, key: str, value: str) -> None:
self.tempcontrol_conf[key] = value | [
"def temp(cls, key):\n return cls.config_parser.get('TEMP', key)",
"def __setitem__(self, key, value):\n self.template_vars[key] = value",
"def setKey(self, key, value ):\n self.conf[key] = value",
"def set_keyvalues(event, consulsrv):\n if consulsrv.ignore:\n logger.info(\"Not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Forces a page break, creating a new page. | def page_break(self):
raise NotImplementedError | [
"def add_page_break(self, *, to_back: bool = True) -> \"Paginator\":\n to_back and self.chunks.append(_PAGE_BREAK) or self.chunks.appendleft(\n _PAGE_BREAK\n )\n return self",
"def PaintPageBreak():\n pass",
"def page_break(orientation):\n return [\n p.NextPageTempla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts a new paragraph, using the specified style name. | def start_paragraph(self, style_name, leader=None):
raise NotImplementedError | [
"def start_paragraph(self, stylename=None):\n if stylename is None:\n stylename = _get_paragraph_style(self._item_level, self._ordered)\n super(PacktODFDocument, self).start_paragraph(stylename)",
"def BeginParagraphStyle(*args, **kwargs):\n return _richtext.RichTextBuffer_BeginPar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ends the current paragraph. | def end_paragraph(self):
raise NotImplementedError | [
"def end(text=None):\n global _current_line\n if _current_line is not None:\n _current_line.end(text)\n _current_line = None",
"def end_p(self):\n return self._create_end_tag(u'p')",
"def close(self):\n\n Widget.close(self)\n\n self._paragraph=''",
"def section_end(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ends the current row on the current table. | def end_row(self):
raise NotImplementedError | [
"def end_table(self):\n pass",
"def end_table(self):\n raise NotImplementedError",
"def end_cell(self):\n raise NotImplementedError",
"def endtable(self):\n return '</tbody></table>'",
"def _HandleTableRowEnd(self, input_line, unused_match, output_stream):\n # Table cells end pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts a new table cell, using the paragraph style specified. | def start_cell(self, style_name, span=1):
raise NotImplementedError | [
"def init_td_style(instance, style=td_style):\n def new_td(*pargs, **kwargs):\n new_style = kwargs.pop('style', style)\n instance.__class__.td(instance, *pargs, style=new_style, **kwargs)\n instance.td = new_td",
"def __cell_style(self):\n cell = TableCellStyle()\n self.default_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ends the current table cell. | def end_cell(self):
raise NotImplementedError | [
"def end_table(self):\n pass",
"def end_table(self):\n raise NotImplementedError",
"def close_cell(self) -> str:\n self.html_table = self.html_table + \"\"\"</td>\\n\"\"\"\n return self.html_table",
"def end_row(self):\n raise NotImplementedError",
"def endEditor(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes the note's text and take care of paragraphs, depending on the format. | def write_note(self, text, format, style_name):
raise NotImplementedError | [
"def note_append_text(self, text: str):\n if not text:\n return\n note = self.note\n if note and not note.endswith(\"\\n\"):\n note += \"\\n\"\n note += text\n self.note = note",
"def _write_notes(paper, paper_id, paper_dir):\n bullet_points = [('Tit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience function to write a styledtext to the cairo doc. | def write_styled_note(self, styledtext, format, style_name,
contains_html=False, links=False):
text = str(styledtext)
self.write_note(text, format, style_name) | [
"def DocumentAppendStyledText(self, wave_id, wavelet_id, blip_id, text, style):\n raise NotImplementedError()",
"def writec(text, color='black', style='normal'):\n\n sys.stdout.write(strc(text, color, style))",
"def text_draw(self, x, y, text, style={}):",
"def create_colored_text(text: str, color: Colo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to write text with Gramps citation marks. | def write_text_citation(self, text, mark=None, links=None):
if not text:
return
parts = text.split("<super>")
markset = False
for piece in parts:
if not piece:
# a text '<super>text ...' splits as '', 'text..'
continue
p... | [
"def write_note(self, text, format, style_name):\n raise NotImplementedError",
"def write_code_of_conduct_citizen(content):\n write_code_of_conduct(content)\n print(\"> Remember to update the many replacements in this code of conduct!!!\")",
"def bibtex(self):\n return \"@comment{%(id)s: %(messa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start a link section. This defaults to underlining. | def start_link(self, link):
self.start_underline() | [
"def start_underline(self):\n pass",
"def stop_link(self):\n self.stop_underline()",
"def doAnchor(bunch, text, env):\n return \"<a name='%s'> </a>\" % (bunch[\"name\"], )",
"def doLINK(bunch, text, env):\n return \"<a href='%s'>%s</body>\" % text",
"def add_link(self, text, li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop the link section. Defaults to stopping the underlining for docgen types that don't support links. | def stop_link(self):
self.stop_underline() | [
"def stop_underline(self):\n pass",
"def start_link(self, link):\n self.start_underline()",
"def remove_link():",
"def delete_link(self, link):",
"def enable_doc_link(self):\n return True",
"def unset_underline_style(self):\n self.font.set_underline(False)",
"def unhighlight(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start a section of underlining. This passes without error so that docgen types are not required to have this. | def start_underline(self):
pass | [
"def start_link(self, link):\n self.start_underline()",
"def illustration(single_line:str, start:int, width:int=0, *, prefix='') -> str:\n\tblanks = ''.join(c if c == '\\t' else ' ' for c in prefix + single_line[:start])\n\tunderline = '^'*(width or 1)+'-- near here'\n\treturn prefix + single_line.rstrip()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stops a section of underlining. This passes without error so that docgen ntypes are not required to have this. | def stop_underline(self):
pass | [
"def stop_link(self):\n self.stop_underline()",
"def start_underline(self):\n pass",
"def stop_highlight(self):\r\n\r\n self.highlight(duration=1, alphaMax=1)",
"def SectionEnd():\n pass",
"def stop(self):\n return _ncofdm_swig.add_cp_underlay_sptr_stop(self)",
"def EndUnder... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert a Table of Contents at this point in the document. This passes without error so that docgen types are not required to have this. | def insert_toc(self):
pass | [
"def insertMarkdownTOC(self: Self, event: Event = None) -> None:\n insert_toc(c=self, kind='markdown')",
"def add_content(self, cont):\n if not self._flip:\n assert len(cont) == self._num_cols, (\n \"Row of the wrong length added to Table %s\" % self._tag)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert an Alphabetical Index at this point in the document. This passes without error so that docgen types are not required to have this. | def insert_index(self):
pass | [
"def _add_index(self):\n self.add_column(\"index\", [str(i) for i in range(len(self))])",
"def _insert_alphabetically (self, ws, term, verant=None, quali=None):\n\n line=self._line_alphabetically(ws, term)\n ws.insert_rows(line)\n ws[f'A{line}'] = term\n ws[f'B{line}'] = quali\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that dilates the vessel into regions such that the contribution from each region can be calculated. Input | def syed_dilation(data, vessel): | [
"def fold(self, regions):\n pass",
"def extend_regions(self):\n\t\tself.regions_expanded = []\n\t\tfor reg in self.region_endpoints:\n\t\t\ti = reg[0]\n\t\t\twhile (i > 0) and (self.dataset.flux[i] < 1.):\n\t\t\t\ti -= 1\n\t\t\tj = reg[1] \n\t\t\twhile (j < self.num_pixels-1) and (self.dataset.flux[j] < 1.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that does a naive reverse diffusion, moving 1/6 of the concentration at each point into the locations adjacent. Sticks to the vessel walls Input | def rev_diffusion_dist(data, vessel):
#Pseudo reverse diffusion
data_temp = data
for t in np.arange(0,40):
for i in np.arange(1,data.shape[0]-1):
for j in np.arange(1,data.shape[1]-1):
for k in np.arange(1,data.shape[2]-1):
if vessel[i,j,k] == 0:
... | [
"def circulationFieldUpdate(pnts,pnts_ijk,pnts_circ,pnts_vect_swirl,CircF,PosF,L2):\n\n X,Y,Z = PosF \n\n decay = 2 #-> DECAY DISTANCE FOR CIRCULATION <-#\n \n for i in range(len(pnts)):\n circ_p = pnts[i]\n circ_p_ijk = ic,jc,kc = pnts_ijk[i]\n circ_p_swirl_vect = pnts_vect_swir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function:交叉验证(Cross Validation) parameter:mall:商场ID alg:参数 dtrain:训练数据 dtest:测试数据集 feature:特征 num_class:分类个数 useTrainCV:是否使用CV cv_folds:训练、测试占比 early_stopping_rounds:early_stopping次数 return:dtest_predictions:预测结果 | def modelfit(mall, alg, dtrain, dtest, feature, num_class, useTrainCV = True, cv_folds = 5, early_stopping_rounds = 20):
#默认使用交叉验证
if useTrainCV:
xgb_param = alg.get_xgb_params()
xgb_param['num_class'] = num_class
xgtrain = xgb.DMatrix(dtrain[feature], label=dtrain['label'])
xgtest = xgb.DMatrix(dtest[featur... | [
"def crossValidate_algorithm():\n\n if not state.corpus:\n return 'No corpus loaded.', 428\n\n classifier_name = request.json.get(\"classifierId\")\n crossvalidation_name = request.json.get(\"crossvalidationMethod\")\n n_folds = int(request.json.get(\"nFolds\"))\n\n # set_feature_expressions()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
filePath full directory and filename for file Function returns True is file is successfully written to media data content to write to file fileType json JSON object txt text string csv Comman Separated Variable string option a append w overwrite c choose option based on file existance | def fileWrite(filePath,data,fileType,option="c"):
if option.lower() == "c":
if os.path.exists(filePath) and os.path.getsize(filePath) > 0:
print "Appending data to file:%s" %filePath
fileOp = "a"
else:
print "Creating file %s to write data to" %filePath
... | [
"def write_json_file(filepath, data):\n try:\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4, separators=(',', ': '))\n return True\n except Exception as e:\n logging.error(\"Unable to write JSON file: \".format(e))\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to start/stop active search | def start_stop_active_search(self):
delay = self.sb_sr_delay.value()
if self.pb_active_search.text() == "Stop Search":
self.active_search.stop_event = True
self.active_search.stop()
self.pb_active_search.setStyleSheet("color: rgb(85, 255, 127);")
self.pb_... | [
"def runNewSearch(self):\n self.__searchJob = self.__startSearch()\n\n self.monitorSearchJob()",
"def launch_search(self):\n \n # gets the active selections from pymol\n active_selections = cmd.get_names('selections', 1)\n if len(active_selections) == 0:\n cmd.get_wiza... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to start/stop feedback timer. sb_feedback_sec spinBox set seconds for timer pb_feedback pushBatton Off/On feedback_timer timer | def start_stop_feedback(self):
if self.pb_start_statistics.text() == "Statistics Accum On":
return 0
if self.mi_standard_fb is not None and self.mi_standard_fb.is_running():
self.error_box("Standard FeedBack is running!")
logger.info("start_stop_feedback: St.FB is ru... | [
"def _stop_loop_feedback(self): # Connect to Stop-button clicked()\n if self._timerId_feedback is not None:\n self.killTimer(self._timerId_feedback)\n self._generator_feedback = None\n self._timerId_feedback = None\n self.fbtn.setIcon(self.style().standardIcon(QtWidgets.QStyl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to the Orbit correctiion. Method calculate correctors strengths (kicks) and call function to calculate (self.calc_orbit()) and draw orbit on the plot but does not send it to the DOOCS server. | def correct(self):
stop_flag = False
self.orbit_class.online_calc = False
# read orbit devs
for elem in self.orbit.corrs:
try:
elem.kick_mrad = elem.mi.get_value()
except Exception as e:
stop_flag = True
logger.warni... | [
"def updateOrbit(self):\n orbits.orbitParams(self)\n self.nu += self.nudot * self.dt",
"def set_up_orbit_correctors(ps_beg, delay, id_slice1, ds_slice, zplot, id_slices, U_core, lambdaref):\n SXSS = Chicane(3.2716, 0.362, 0.830399, delay[0])\n HXSS = Chicane(3.2, 0.3636, 0.5828, delay[1])\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to set objective function from the GUI (channels A,B,C) or reload module obj_function.py | def set_obj_fun(self):
# disable button "Edit Objective Function"
# self.ui.pb_edit_obj_func.setEnabled(False)
a_str = str(self.le_a.text())
state_a = self.is_le_addr_ok(self.le_a)
b_str = str(self.le_b.text())
state_b = self.is_le_addr_ok(self.le_b)
c_str = str(... | [
"def set_objective(self, *args, **kwargs):\n raise NotImplementedError",
"def update_objective(self, objective: str) -> None:\n self.objective = objective",
"def set_objective(self, objective):\n ind, val = unpack_pair(objective)\n CPX_PROC.prechgobj(self._env._e, self._cplex._lp, in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reconstruct = True, means we are reconstructing image data from filter data | def __init__(self,reconstruct=True,bytesPerPixel=3):
self.prev = None
self.reconstruct = reconstruct
self.bpp = bytesPerPixel
#filter dispatch
if reconstruct:
self.dispatch = {}
self.dispatch[1] = self.__rfilter_sub
self.dispatch[2] = self.__rf... | [
"def _reconstruct(self, num_samples=None):",
"def reconstruct_images(self, images):\n\n q_y = self.encoder_y(images)\n y = q_y.sample(seed=self.random_seed)\n\n q_z = self.encoder_gmm(images, y)\n z = q_z.sample(seed=self.random_seed)\n\n p_x_given_z = self.decoder(z)\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
IEND MUST be the last chunk, so we are Done reading image. It is now safe to decompress IDAT. | def IEND(self,data=None,read=True):
if read:
try:
self.raster = self.getRaster()
except:
print "ERROR getRaster failed!"
raise
else:
return '' | [
"def iteridat():\r\n while True:\r\n try:\r\n type, data = self.chunk()\r\n except ValueError, e:\r\n raise ChunkError(e.args[0])\r\n if type == 'IEND':\r\n # http://www.w3.org/TR/PNG/#11IEND\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns an integer raster, i = r<<16+g<<8+b if entire raster is one color that color is returned in a set if entire raster is blank, None is returned. | def iraster(self):
r = self.raster
n = len(r)
slic = itertools.islice
rast = [(a<<16)+(b<<8)+c for a,b,c in itertools.izip(slic(r,0,n,3), slic(r,1,n,3), slic(r,2,n,3))]
s = set(rast)
if len(s) == 1 and 0 in s:
return None
elif len(s) == 1:
... | [
"def craster(self):\n r = self.iraster()\n if r:\n if len(r) == 1:\n return r\n head = self.data['IHDR']\n size = head['width']*head['height']\n r = pack('!%si'%size,*r)\n return compress(r)\n else:\n return None",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
same as iraster, but full rasters are compressed | def craster(self):
r = self.iraster()
if r:
if len(r) == 1:
return r
head = self.data['IHDR']
size = head['width']*head['height']
r = pack('!%si'%size,*r)
return compress(r)
else:
return None | [
"def iraster(self):\n r = self.raster\n n = len(r)\n slic = itertools.islice\n rast = [(a<<16)+(b<<8)+c for a,b,c in itertools.izip(slic(r,0,n,3), slic(r,1,n,3), slic(r,2,n,3))]\n s = set(rast)\n if len(s) == 1 and 0 in s:\n return None\n elif len(s) == 1:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
same as craster, but full rasters are compressed and base64 enocded | def b64raster(self):
r = self.craster()
if r:
if len(r) == 1:
return r
return b64encode(r)
else:
return None | [
"def craster(self):\n r = self.iraster()\n if r:\n if len(r) == 1:\n return r\n head = self.data['IHDR']\n size = head['width']*head['height']\n r = pack('!%si'%size,*r)\n return compress(r)\n else:\n return None",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that the ChemicalSystem component has the right solvent composition for an input nonbonded_methtod. | def validate_solvent(state: ChemicalSystem, nonbonded_method: str):
solv = [comp for comp in state.values()
if isinstance(comp, SolventComponent)]
if len(solv) > 0 and nonbonded_method.lower() == "nocutoff":
errmsg = "nocutoff cannot be used for solvent transformations"
raise ValueE... | [
"def test_nonbonded_cutoff_no_box_vectors(self, mod_cuoff, force_field):\n top = Topology.from_molecules(create_ethanol())\n assert top.box_vectors is None\n\n if mod_cuoff:\n # Ensure a modified, non-default cutoff will be propogated through\n force_field[\"vdW\"].cutoff ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |