query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Calculates easting, northing and coordinate precision from the station grid reference. Returns dictionary with the additional keys. | def calcStationCoords(station, gridSquares):
# calculate coordinates and precision
gridRef = station["gridReference"]
gridCode = gridRef[:2]
station["precision"] = 10 ** (5 - len(gridRef[2:])/2) # Units: meters
station["easting"] = (
gridSquares[gridCode][0] + int(gridRef[2:len(gridRef[2:]... | [
"def _compute_generic_parameters(self, projection, ellipsoid):\n lines, cols = self.lons.shape\n lat_0 = self.lats[int(lines / 2), int(cols / 2)]\n lon_0 = self.lons[int(lines / 2), int(cols / 2)]\n return {'proj': projection, 'ellps': ellipsoid,\n 'lat_0': lat_0, 'lon_0':... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds river ID to station dictionary. | def addStationRiverID(station, riverIDs):
stationID = station["id"]
riverID = riverIDs.get(stationID)
station["riverId"] = riverID
return station | [
"def add_station(self, station_id=None, time=None, location=None):",
"def add_router(self, router_id):\n pass",
"def station_id(self, station_id: str):\n\n self._station_id = station_id",
"def save_new_lid(self):\n region = 'world' if self.city is None else self.city\n id_ = str(ha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Field gain is in T/A so to get Amps we need to devide the field value by the field Gain | def set_field(coil, fieldValue, fieldGain):
current = (fieldValue/fieldGain)*1e3 # set the current to be in milliamps
print(current)
coil.current(current)
return | [
"def gain(dB):\n return 10.**(dB/10.)",
"def dB2gain(dB):\n V = math.exp(dB/20)\n return V",
"def microphone_transferfactor(sensitivity: float) -> float:\n a = db2amp(sensitivity)\n return a * 1000 # convert it to mV",
"def get_mod_gain_val(self):\n return self.mod_gain_table[self.tx_pwr_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a validation schema for a required object property. | def with_required_property(self, name, typ, *rules):
self.properties = self.properties if self.properties != None else []
schema = PropertySchema(name, typ)
schema.rules = rules
schema.make_required()
return self.with_property(schema) | [
"def validate_property_schema(self, schema):\n json_schema_path = os.path.join(_ROOT,\n 'data',\n 'property_json_schema.json')\n json_schema = load_json_or_yaml(json_schema_path)\n return validate(schema, json_schema)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert address to ip and prefix. | def address_to_ip_prefix(address):
return address.split('/') | [
"def normalizeAddress(address):\n return address",
"def format_ip(addr):\n return \\\n str(ord(addr[0])) + '.' + \\\n str(ord(addr[1])) + '.' + \\\n str(ord(addr[2])) + '.' + \\\n str(ord(addr[3]))",
"def morseToPubIP(self, address):\n ip_from_morse = address[0];\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set ip addresses of all interfaces. | def set_ip_adresses(self):
# unfold a config tree for the current suffix, if any
for interface, details in self.interfaces.items():
for k, v in details.items():
if k == 'address':
ip, prefix = address_to_ip_prefix(v)
self.interfaces[int... | [
"def ips(self, ips):\n\n self._ips = ips",
"def ip_addresses(self, ip_addresses):\n self._ip_addresses = ip_addresses",
"def ip_addresses(self, ip_addresses):\n\n self._ip_addresses = ip_addresses",
"def set_all(self, host_names, ip_address):\n for host_name in host_names:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve pci addresses for network interfaces. | def retrieve_pci_addresses(self):
debug('Retrieve PCI addresses...')
try:
lshw_json = self.run_ssh('lshw -json').stdout
except SSHError:
fatal('Cannot connect to node:', self.ip_address)
lshw = json.loads(lshw_json)
pci_addresses = []
for component... | [
"def getNetInterfaces():\n net_interface = {}\n net_info = psutil.net_if_addrs()\n for k, v in net_info.items():\n for snicaddr_item in v:\n if snicaddr_item.family == 2:\n net_interface[k] = snicaddr_item.address\n # print(net_interface)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a slope raster from the input DEM raster. | def generate_slope_raster(in_path, out_path):
cmd = "gdaldem slope -alg ZevenbergenThorne {} {}".format(in_path, out_path)
os.system(cmd) | [
"def compute_slope(self):\n\n # assign variables\n slope = 'slope'\n aspect = 'aspect'\n dx = 'dx'\n dy = 'dy'\n grow_slope = 'grow_slope'\n grow_aspect = 'grow_aspect'\n grow_dx = 'grow_dx'\n grow_dy = 'grow_dy'\n\n # compute slope and partial d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes noise (high elevation data points like roofs, etc.) from the ground DEM raster. Replaces values in those pixels with No data Value (99999.0) | def remove_noise(ground_dem_path, out_path, ignore_value=-99999.0):
ground_np = np.array(gdal.Open(ground_dem_path).ReadAsArray())
std = ground_np[ground_np != ignore_value].std()
mean = ground_np[ground_np != ignore_value].mean()
threshold_value = mean + 1.5 * std
ground_np[ground_np >= threshold_v... | [
"def perform_noise_removal(mask):\n trans1 = cv.dilate(mask, KERNEL, iterations=4)\n trans1 = cv.erode(trans1, KERNEL, iterations=5)\n return cv.dilate(trans1, KERNEL, iterations=7)",
"def remove_noise(self, thr):\n if thr >= 0:\n mask = self.data_pred > thr\n self.data_pred ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces values in input rasterA with no_data_value where cell value >= threshold in rasterB | def replace_values(
rasterA_path, rasterB_path, out_path, no_data_value=-99999.0, threshold=0.98
):
cmd = 'gdal_calc.py -A {} --NoDataValue={} -B {} --outfile {} --calc="{}*(B>={}) + (A)*(B<{})"'.format(
rasterA_path,
no_data_value,
rasterB_path,
out_path,
no_data_value,
... | [
"def reclassify_raster(self):\n profile = self.make_profile_from_template()\n with rasterio.open(self.in_raster) as src, rasterio.open(self.mask_raster) as msk, rasterio.open(self.out_raster, 'w', **profile) as dst:\n src_data = src.read()\n msk_data = msk.read()\n src... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expands holes (cells with no_data_value) in the input raster. | def expand_holes_in_raster(
in_path, search_window=7, no_data_value=-99999.0, threshold=50
):
np_raster = np.array(gdal.Open(in_path).ReadAsArray())
height, width = np_raster.shape[0], np_raster.shape[1]
for i in range(int((search_window - 1) / 2), width, 1):
for j in range(int((search_window - ... | [
"def fill_holes(self):\n # Function fill_holes requires a binary input\n self.data_pred = threshold_predictions(self.data_pred)\n self.data_pred = fill_holes(self.data_pred)",
"def fill_holes(splatty):\n #indices = filter_not_nans(splatty)\n indices = filter_not_infs(splatty)\n indic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the CRS (Coordinate Reference System) of the raster | def get_raster_crs(raster_path):
raster = rasterio.open(raster_path)
return raster.crs | [
"def _get_raw_crs(self) -> riocrs.CRS:\n # Open metadata\n root, _ = self.read_mtd()\n\n # Get CRS\n crs_name = root.findtext(\".//MapProjection\")\n\n if not crs_name:\n crs_name = vectors.WGS84\n\n return riocrs.CRS.from_string(crs_name)",
"def crs(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the position of the missed_value in all square neighbors | def position_surroundings(self, neighbour_pos, missed_value):
pos = []
for x, y in neighbour_pos:
position = self._square_matrix[x][y].get_pos_from_number(missed_value)
if position:
pos.append(position)
return pos | [
"def __find_empty_spot(self, board):\n\t\tfor i in range(9):\n\t\t\tfor j in range(9):\n\t\t\t\tif board[i][j] == 0:\n\t\t\t\t\treturn i, j\n\t\treturn",
"def _get_neighbours(self, position):\n grid = self._grid\n x, y = position\n neighbours = []\n offsets = [(0,1),(1,0),(0,-1),(-1,0)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Zero out (but remember) the weight on this node | def clear(self):
self.weight = 0 | [
"def zero_weight():\n return Weight(kg=0)",
"def clear(self):\n for i in range(0, len(self.weights)):\n self.weights[i] = 0",
"def reset_weights(self):\r\n self._weights = deepcopy(self._tmp_weights)\r\n self._tmp_weights = None",
"def prune_weights(self):\n pass",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dijkstra's algorithm to compute the shortest distance to all vertices vs from a given source vertex s by traveling the edges e | def dijkstra(vs, es, s, stop = None):
initialize_single_source(vs, es, s)
key = lambda x: -1 * x._ss_d
Q = pq(vs)
edict = defaultdict(set)
for e in es:
edict[e.v1].add(e)
edict[e.v2].add(e)
for i in range(len(vs)):
# min path to u is determined at end of loop
u =... | [
"def Dijkstra(G,l,s):\r\n # Esta implementación es muy costosa en espacio:\r\n # Usamos un conjunto S para guardar los nodos cuya etiqueta es definitiva\r\n # es decir, aquellos que en determinada iteración tuvieron la menor etiqueta\r\n # Usamos un pqdict (implementación externa no nativa de python) co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return min path from source to target, on the graph described the vertices vs and edges es | def min_path(vs, es, source, target):
dijkstra(vs, es, source, stop = target)
test = target
result = []
while test != source:
e = test._ss_edge
result.append(e)
test = e.v1 if e.v1 != test else e.v2
assert test == source and test._ss_edge is None
return result[::-1] | [
"def shortest_path_example():\n graph = Graph({\n (0, 1): 4,\n (0, 7): 8,\n (1, 2): 8,\n (1, 7): 11,\n (2, 3): 7,\n (2, 5): 4,\n (2, 8): 2,\n (3, 4): 9,\n (3, 5): 14,\n (5, 4): 10,\n (6, 5): 2,\n (7, 6): 1,\n (6, 8): 6,\n (7, 8): 7,\n })\n src = 0\n V_sorted = sorted(gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Require that user is a designated study admin or site admin. | def _requireStudyAdmin(self, user):
studyAdminsGroup = self.model('group').findOne({'name': 'Study Administrators'})
if not studyAdminsGroup or studyAdminsGroup['_id'] not in user['groups']:
if not user.get('admin', False):
raise AccessException(
'Only mem... | [
"def check_admin():\n\tif not current_user.is_admin:\n\t\tabort(403)",
"def check_admin():\r\n if not current_user.is_admin:\r\n abort(403)",
"def validate_admin(self, request):\n\n self.validate_login(request)\n\n if request.session['id'] not in self.admins:\n handler.logHelp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to retrieve the current values of the RAMSTKSurvivalData data model attributes. | def get_attributes(self):
_attributes = (self.survival_id, self.record_id, self.name,
self.source_id, self.failure_date, self.left_interval,
self.right_interval, self.status_id, self.quantity,
self.tbf, self.mode_type_id, self.nevada_chart,
... | [
"def set_attributes(self, attributes):\n\n _error_code = 0\n _msg = \"RAMSTK SUCCESS: Updating RAMSTKSurvivalData {0:d} attributes.\". \\\n format(self.record_id)\n\n try:\n self.name = str(none_to_default(attributes[0], ''))\n self.source_id = int(none_to_de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to set the RAMSTKSurvivalData data model attributes. | def set_attributes(self, attributes):
_error_code = 0
_msg = "RAMSTK SUCCESS: Updating RAMSTKSurvivalData {0:d} attributes.". \
format(self.record_id)
try:
self.name = str(none_to_default(attributes[0], ''))
self.source_id = int(none_to_default(attributes... | [
"def set_attributes(self, attributes):\n _error_code = 0\n _msg = \"RAMSTK SUCCESS: Updating RAMSTKRevision {0:d} attributes.\".\\\n format(self.revision_id)\n\n try:\n self.availability_logistics = float(\n none_to_default(attributes['availability_logistics... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load dataset from files in a given folder. This function looks for files train_x.npy, train_y.npy, val_x.npy, val_y.npy, test_x.npy and test_y.npy Returns a DataSet instance | def load_from_path(name, folder):
tx_file = "{0:s}/train_x.npy".format(folder)
if not os.path.isfile(tx_file):
raise DataSetException("Training file not found.")
ty_file = "{0:s}/train_y.npy".format(folder)
if not os.path.isfile(ty_file):
ty_file = None
... | [
"def load_datasets(self):\n file_prefix = self._load_datasets_from\n\n self._train_set.load_images(file_prefix + \"_training.pkl\")\n self._test_set.load_images(file_prefix + \"_testing.pkl\")\n\n self.__loaded_datasets = True",
"def load_datasets(data_dir: str) -> Tuple[List[Annotation], List[Annotat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read vapor pressure parameters file and fill in parameters that are needed for vapor pressure curve | def readVP(self,species):
f = open('VPparams.txt', 'rU')
lines = f.readlines()
f.close()
parsing = False
for i in np.arange(len(lines)):
if lines[i].startswith(species):
parsing = True
else:
parsing = False
... | [
"def read_parameters_from_file(self,file_name):\n counter = 0\n input_data = open(file_name,'rt')\n for line in input_data.readlines():\n parameter_description = line.split()\n if parameter_description[0][0] != '#':\n assert int(parameter_description[4]) =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subclasses should implement this method in order to take action when a task is scanned There is no diff passed, because this method is called when there is no information about the previous state of a task. | def task_scanned(now_task): | [
"def task_changed(old_task, diff, now_task):",
"def has_task_changed(self, task):\n raise NotImplementedError()",
"def test_search_task_runner_history(self):\n pass",
"def handle_regular_task(self):\n pass",
"def test_search_task_status(self):\n pass",
"def task_status():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Template method strategy for creating action for taskChanged we have old and now states, and can pass this to a handler. | def task_changed_template(task_id):
#Assume for now that we can definitely get the event from an event stream
old_task = self._storage_service.get_stored_task(task_id)
now_task = self._task_api_service.get_current_task_state(task_id)
diff = self._task_diff_service.calculate_diff_for_task... | [
"def task_changed(old_task, diff, now_task):",
"def test_update_task_states(self):\r\n changed = self.combinedoe.update_task_states()\r\n self.assertFalse(changed)\r\n\r\n current_task = self.combinedoe.current_task\r\n current_task.change_state(CombinedOpenEndedV1Module.DONE)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subclasses should implement this method in order to take action when a task changes It should be assumed that the difference between the old and the new task is represented accurately, but that there may have been intermediate changes in the meantime. For instance, if the task had State A and then becomes State B, and ... | def task_changed(old_task, diff, now_task): | [
"def timestamper(task, old_state, new_state):\n new_state.timestamp = pendulum.now(\"utc\")\n if hasattr(old_state, \"timestamp\"):\n duration = (new_state.timestamp - old_state.timestamp).in_seconds()\n task.logger.info(\n \"{} seconds passed in between state transitions\".format(dur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The task may be stagnant. What stagnant means depends on the business logic. One example may be that you expect that the task needs to have, say, a comment placed on it every week; and if that's the requirement, you should check the task that we think might be stagnant in order to verify. | def is_task_stagnant(task): | [
"def is_task():\n return False",
"def test_need_run(self):\n\n self.assertEqual(self.task.need_run(self.datetime), True)",
"def test_ignore_future_task(self):\n future_task = todotxt.Task(\"(A) 9999-01-01 Start preparing for five-digit years\")\n regular_task = todotxt.Task(\"(B) Loo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get all the children on gmac_id from redis DB, much FASTER | def get_all_children_from_redis(gmac_id, as_objects=True):
conn = get_redis_connection()
klass = GoogleMapsAddressComponent
results = klass.get_all_children_id_list_from_redis_by_pk(gmac_id)
if as_objects:
results = klass.objects.filter(pk__in=results)
return results | [
"def sync_all_children_to_redis(self):\n conn = get_redis_connection()\n key = GoogleMapsAddressComponent.get_redis_all_children_key(self.pk)\n # First, we make sure the key gets destroyed if it exists\n conn.delete(key)\n # Now we add the keys of the children to the list\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
synchronizes all the children to a Redis list | def sync_all_children_to_redis(self):
conn = get_redis_connection()
key = GoogleMapsAddressComponent.get_redis_all_children_key(self.pk)
# First, we make sure the key gets destroyed if it exists
conn.delete(key)
# Now we add the keys of the children to the list
children =... | [
"def _children(self, children):\n existing = self._immed_raw_children()\n if (existing is None) or (existing != children):\n for fn in self.__ch_cbs.values():\n self.__zk._run_async(lambda: fn( children ))\n self.__children._set(children)\n print self.path, \"children set\"",
"def updateId... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator function that outputs the paper title, index, and citations for each entry | def __citationsFromFile(file):
# Tokens for parsing
titleToken = '#*'
indexToken = '#index'
citationToken = '#%'
# Predicates for error checking
noneNone = lambda *items: all([item is not None for item in items])
allNone = lambda *items: all([item is None for item in items])
# Next en... | [
"def citation_meta(document):\n\n for cit in document.citations or []:\n c_dict = {}\n\n c_dict['titles'] = []\n c_dict['url'] = document.html_url()\n c_dict['issn'] = document.journal.scielo_issn\n c_dict['pid'] = document.publisher_id\n c_dict['code'] = document.publis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read GFF3formatted data in the specified file (or filelike object) Return a pandas dataframe with ID, Parent, seqid, source, type, start, end, score, strand, phase, and attributes columns. The ID and Parent are extracted from the attributes columns, and the dataframe is indexed by ID | def gff3_to_dataframe( file ):
result = _read_gff3_using_pandas( file )
extract_attributes_to_columns( result, ['ID', 'Parent', 'Name' ] )
return result | [
"def parse_gff3_to_dataframe( file ):\n result = read_gff3_using_pandas( file )\n add_ID_and_Parent( result )\n return result",
"def _read_gff3_using_pandas( file ):\n import pandas\n result = pandas.read_table(\n file,\n comment = '#',\n names = [ 'seqid', 'source', 'type', 's... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to read the given GFF3 file into a dataframe, without any postprocessing. | def _read_gff3_using_pandas( file ):
import pandas
result = pandas.read_table(
file,
comment = '#',
names = [ 'seqid', 'source', 'type', 'start', 'end', 'score', 'strand', 'phase', 'attributes' ],
na_values = ".",
dtype = {
'seqid': str,
'source': ... | [
"def parse_gff3_to_dataframe( file ):\n result = read_gff3_using_pandas( file )\n add_ID_and_Parent( result )\n return result",
"def gff3_to_dataframe( file ):\n result = _read_gff3_using_pandas( file )\n extract_attributes_to_columns( result, ['ID', 'Parent', 'Name' ] )\n return result",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GFF3 files from the Ensembl ftp site list sequences and their lengths in the file metadata. This function parses this information and returns it as a pandas dataframe. It's use may be specific to the Ensembl files. | def parse_sequences_from_gff_metadata( file ):
import pandas
result = []
for line in file:
if line.startswith( '##sequence-region' ):
parts = line.strip().split( " " )
nameStartEnd = parts[-3:] # last 3 elements
result.append({
"seqid": nameStartEn... | [
"def parse_gff3_to_dataframe( file ):\n result = read_gff3_using_pandas( file )\n add_ID_and_Parent( result )\n return result",
"def parseGff(gff: TextIO) -> pd.core.frame.DataFrame:\n gff_df = pd.DataFrame(columns = ['Chromosome', 'Start', 'Stop', 'Strand'])\n col_nums = [0, 3, 4, 6]\n for line... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
use the multiprocessing to speed up trees construction | def construct_trees_with_mp(self, nodes):
cores = multiprocessing.cpu_count() // 2
pool = multiprocessing.Pool(cores)
new_nodes = []
n_node_per_core = self.n_node // cores
for i in range(cores):
if i != cores - 1:
new_nodes.append(nodes[i * n_node_per... | [
"def _initialize_trees(self):",
"def runPidGen ( tree , ## initial tree/chain to be updated \n pidgen , ## PidGen object \n newpid , ## name of new PID variable \n seed = None , ## random seed\n silent = Fal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a path from root to a sampled node, generate all the node pairs within the given windows size e.g., path = [1, 0, 2, 4, 2], window_size = 2 > node pairs= [[1, 0], [1, 2], [0, 1], [0, 2], [0, 4], [2, 1], [2, 0], [2, 4], [4, 0], [4, 2]] | def get_node_pairs_from_path(path):
path = path[:-1]
pairs = []
for i in range(len(path)):
center_node = path[i]
for j in range(max(i - config.window_size, 0), min(i + config.window_size + 1, len(path))):
if i == j:
continue
... | [
"def generate_window_pairs(self, sample_path):\n\t\tsample_path = sample_path[:-1]\n\t\tpairs = []\n\n\t\tfor i in range(len(sample_path)):\n\t\t\tcenter_node = sample_path[i]\n\t\t\tfor j in range(max(i-self.window_size, 0), min(i+self.window_size+1, len(sample_path))):\n\t\t\t\tif i == j:\n\t\t\t\t\tcontinue\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
write embeddings of the generator and the discriminator to files | def write_embeddings_to_file(self):
modes = [self.generator, self.discriminator]
for i in range(2):
embedding_matrix = modes[i].embedding_matrix
embedding_matrix = embedding_matrix.detach().to('cpu').numpy()
index = np.array(range(self.n_node)).reshape(-1, 1)
embeddin... | [
"def save_generated(self, logdir, filename):\n with open(filename, 'w') as f:\n for s in self.generated:\n f.write(s + '\\n')\n \n self.ran.save_fasta(logdir + '/random_sequences.fasta')\n self.hel.save_fasta(logdir + '/helical_sequences.fasta')",
"def save_ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Emit an Operation at the current position. Sets result register if not set already. | def emit(self, op):
assert self._curblock, "Builder is not positioned!"
if op.result is None:
op.result = self.func.temp()
if self._lastop == 'head' and self._curblock.ops.head:
op.insert_before(self._curblock.ops.head)
elif self._lastop in ('head', 'tail'):
... | [
"def emit(self, op):\n assert self._curblock\n\n if op.result is None:\n op.result = self.func.temp()\n\n if self._lastop == 'head' and self._curblock.ops.head:\n op.insert_before(self._curblock.ops.head)\n elif self._lastop in ('head', 'tail'):\n self._c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Position the builder at the beginning of the given block. | def position_at_beginning(self, block):
self._curblock = block
self._lastop = 'head' | [
"def position_at_beginning(self, bblk):\r\n\r\n # Instruction list won't be long anyway,\r\n # Does not matter much to build a list of all instructions\r\n instrs = bblk.instructions\r\n if instrs:\r\n self.position_before(instrs[0])\r\n else:\r\n self.positi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Position the builder at the end of the given block. | def position_at_end(self, block):
self._curblock = block
self._lastop = block.tail or 'tail' | [
"def position_after(self, op):\n if isinstance(op, FuncArg):\n self.position_at_beginning(op.parent.startblock)\n else:\n self._curblock = op.block\n self._lastop = op",
"def position_after(self, op):\n self._curblock = op.block\n self._lastop = op",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Position the builder before the given op. | def position_before(self, op):
if isinstance(op, FuncArg):
raise error.PositioningError(
"Cannot place builder before function argument")
self._curblock = op.block
self._lastop = op._prev | [
"def position_before(self, op):\n self._curblock = op.block\n self._lastop = op._prev",
"def position_after(self, op):\n self._curblock = op.block\n self._lastop = op",
"def position_after(self, op):\n if isinstance(op, FuncArg):\n self.position_at_beginning(op.pare... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Position the builder after the given op. | def position_after(self, op):
if isinstance(op, FuncArg):
self.position_at_beginning(op.parent.startblock)
else:
self._curblock = op.block
self._lastop = op | [
"def position_after(self, op):\n self._curblock = op.block\n self._lastop = op",
"def position_before(self, op):\n if isinstance(op, FuncArg):\n raise error.PositioningError(\n \"Cannot place builder before function argument\")\n self._curblock = op.block\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Propagate an exception. If `exc` is not given it will be loaded to match in 'except' clauses. | def gen_error_propagation(self, exc=None):
assert self._curblock
block = self._curblock
exc_setup = findop(block.leaders, 'exc_setup')
if exc_setup:
exc = exc or self.load_tl_exc(types.Exception)
self._find_handler(exc, exc_setup)
else:
self.g... | [
"def raise_exc(self, exctype):\n\t\tself.async_raise(self.get_my_tid(), exctype)",
"def raise_exc(self, exctype):\n\t\t_async_raise(self._get_my_tid(), exctype)",
"def add_exceptionhook(h):\n _hooks.insert(0, h)",
"def process_exception(self, request, exc):\n return None",
"def visit_ExceptHandler... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a return with undefined value | def gen_ret_undef(self):
type = self.func.type.restype
if type.is_void:
self.ret(None)
else:
self.ret(Undef(type)) | [
"def return_none() -> None:\n pass",
"def none():\n return ValueFactory._none_value",
"def undefined(self):\n\t\treturn self.expr(core.LLIL_UNDEF)",
"def get_none(): # noqa: D401\n return None",
"def null() -> SetupVal:\n return NullVal()",
"def no_ret(self):\n\t\treturn self.expr(core.LL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split the current block, returning (old_block, new_block) | def splitblock(self, name=None, terminate=False):
# -------------------------------------------------
# Sanity check
# Allow splitting only after leaders and before terminator
# TODO: error check
# -------------------------------------------------
# Split
oldbl... | [
"def split_block(block, pos=None, newname=\"splitblock\"):\n\n downstream_phis = []\n for successor_block in block.successors:\n for phi in successor_block.phis:\n downstream_phis.append(phi)\n\n if pos is None:\n pos = int(len(block) / 2)\n first = block.instructions[:pos]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Patch uses of the instructions in `ops` when a predecessor changes from `oldblock` to `newblock` | def _patch_phis(self, ops, oldblock, newblock):
for op in ops:
for use in self.func.uses[op]:
if use.opcode == 'phi':
# Update predecessor blocks
preds, vals = use.args
preds = [newblock if pred == oldblock else pred
... | [
"def test_replace_block_by_instruction(self):\n sub_block1 = pulse.ScheduleBlock()\n sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))\n sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))\n\n sub_block2 = pulse.ScheduleBlock()\n sub_block2 = sub_block2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a loop given start, stop, step and the index variable type. The builder's position is set to the end of the body block. Returns (condition_block, body_block, exit_block). | def gen_loop(self, start=None, stop=None, step=None):
assert isinstance(stop, Value), "Stop should be a Constant or Operation"
ty = stop.type
start = start or Const(0, ty)
step = step or Const(1, ty)
assert start.type == ty == step.type
with self.at_front(self.func.sta... | [
"def gen_loop(self, start=None, stop=None, step=None):\n self._assert_position()\n assert isinstance(stop, Value), \"Stop should be a Constant or Operation\"\n\n ty = stop.type\n start = start or Const(0, ty)\n step = step or Const(1, ty)\n assert start.type == ty == step.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a weight variable to the layer. | def add_weight(self,
name,
shape,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
constraint=None):
if dtype is None:
dtype = K.floatx()
weight = self.add_variable(name, s... | [
"def add_weight(self, point, weight):\n self.weights[point] = weight",
"def AddInputWeight(self, weight: float):\n\n self.weights.append(weight)",
"def _add_existing_weight(self, weight, trainable=None):\n if trainable is None: trainable = weight.trainable\n self.add_weight(name=weight.name,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the input mask tensor(s) of a layer at a given node. | def get_input_mask_at(self, node_index):
inputs = self.get_input_at(node_index)
if isinstance(inputs, list):
return [getattr(x, '_keras_mask', None) for x in inputs]
else:
return getattr(inputs, '_keras_mask', None) | [
"def get_input_masks(nx_node, nx_graph):\n input_edges = list(nx_graph.in_edges(nx_node['key']))\n input_masks = [nx_graph.nodes[input_node]['output_mask'] for input_node, _ in input_edges]\n return input_masks",
"def get_input_masks(nx_node, nx_graph):\n input_edges = list(nx_graph.in_edges(nx_node[\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the output mask tensor(s) of a layer at a given node. | def get_output_mask_at(self, node_index):
output = self.get_output_at(node_index)
if isinstance(output, list):
return [getattr(x, '_keras_mask', None) for x in output]
else:
return getattr(output, '_keras_mask', None) | [
"def generate_output_mask(cls, node: NNCFNode, graph: NNCFGraph) -> Union[tf.Tensor, None]:\n input_edges = graph.get_input_edges(node)\n previous_nodes = [edge.from_node for edge in input_edges]\n input_masks = [input_node.data['output_mask'] for input_node in previous_nodes]\n\n if all... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the input mask tensor(s) of a layer. Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer. | def input_mask(self):
inputs = self.input
if isinstance(inputs, list):
return [getattr(x, '_keras_mask', None) for x in inputs]
else:
return getattr(inputs, '_keras_mask', None) | [
"def get_input_mask_at(self, node_index):\n inputs = self.get_input_at(node_index)\n if isinstance(inputs, list):\n return [getattr(x, '_keras_mask', None) for x in inputs]\n else:\n return getattr(inputs, '_keras_mask', None)",
"def get_input_masks(nx_node, nx_graph):\n input_edges = list(n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the output mask tensor(s) of a layer. Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer. | def output_mask(self):
output = self.output
if isinstance(output, list):
return [getattr(x, '_keras_mask', None) for x in output]
else:
return getattr(output, '_keras_mask', None) | [
"def get_output_mask_at(self, node_index):\n output = self.get_output_at(node_index)\n if isinstance(output, list):\n return [getattr(x, '_keras_mask', None) for x in output]\n else:\n return getattr(output, '_keras_mask', None)",
"def generate_output_mask(cls, node: NNCFNode, graph: NNCFGraph)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`Input()` is used to instantiate a Keras tensor. A Keras tensor is a tensor object from the underlying backend (Theano or TensorFlow), which we augment with certain attributes that allow us to build a Keras model just by knowing the inputs and outputs of the model. For instance, if a, b and c are Keras tensors, | def Input( # pylint: disable=invalid-name
shape=None,
batch_size=None,
name=None,
dtype=None,
sparse=False,
tensor=None,
**kwargs):
if 'batch_shape' in kwargs:
batch_shape = kwargs.pop('batch_shape')
if shape and batch_shape:
raise ValueError('Only provide the shape OR '
... | [
"def get_tensor_from_input(self, input_data: Dict[str, Any],\n **kwargs) -> torch.Tensor:\n raise NotImplementedError",
"def identity_model(input_shape=image_input_shape, weights=None, classes=None,\n input_tensor=None):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the `updates` from all layers that are stateful. This is useful for separating training updates and state updates, e.g. when we need to update a layer's internal state during prediction. | def state_updates(self):
state_updates = []
for layer in self.layers:
if getattr(layer, 'stateful', False):
if hasattr(layer, 'updates'):
state_updates += layer.updates
return state_updates | [
"def updates(self):\r\n return list(self.state_updates)",
"def updates(self):\n if context.in_eager_mode():\n return []\n\n if not self.trainable and not self.stateful:\n return []\n\n updates = []\n for layer in self.layers:\n updates += layer.updates\n\n # `updates` might co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves a layer based on either its name (unique) or index. Indices are based on order of horizontal graph traversal (bottomup). | def get_layer(self, name=None, index=None):
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None:
if len(self.layers) <= index:
raise ValueError('Was asked to retrieve layer at index ' + str(index) +
... | [
"def get_layer(model, layer_name=None, layer_idx=None):\n\n _validate_args(layer_name, layer_idx, layer=None)\n if layer_idx is not None:\n return model.layers[layer_idx]\n\n layer = [layer for layer in model.layers if layer_name in layer.name]\n if len(layer) > 1:\n print(warn_str + \"mul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the network's updates. Will only include updates that are either unconditional, or conditional on inputs to this model (e.g. will not include updates that were created by layers of this model outside of the model). Effectively, `network.updates` behaves like `layer.updates`. | def updates(self):
if context.in_eager_mode():
return []
if not self.trainable and not self.stateful:
return []
updates = []
for layer in self.layers:
updates += layer.updates
# `updates` might contain irrelevant updates, so it needs to be filtered
# with respect to inputs t... | [
"def get_updates(self, layers=None):\n # check asserts\n if layers is not None:\n assert isinstance(layers, list), '\"layers\" should be None or list.'\n\n updates = OrderedDict()\n if layers is None:\n for ll in self.layers:\n updates = merge_dicts([... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the network's losses. Will only include losses that are either unconditional, or conditional on inputs to this model (e.g. will not include losses that depend on tensors that aren't inputs to this model). | def losses(self):
losses = []
for layer in self.layers:
losses += layer.losses
if context.in_eager_mode():
return losses
relevant_inputs = self.inputs or []
for i in range(1, len(self._inbound_nodes)):
inputs = self.get_input_at(i)
if isinstance(inputs, list):
releva... | [
"def get_losses(self):\n if self.loss is not None:\n return [self.loss]\n else:\n return []",
"def losses(self):\n return {\n \"loss_cls\": self.drop_loss(),\n \"loss_box_reg\": self.smooth_l1_loss(),\n }",
"def losses(self):\n loss ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the network's input specs. | def input_spec(self):
# If not a graph network, can't assume anything.
if not self._is_graph_network:
return None
specs = []
for layer in self._input_layers:
if layer.input_spec is None:
specs.append(None)
else:
if not isinstance(layer.input_spec, list):
rais... | [
"def getInputSpecs(cls, spec):\n # this unit probably has some economics\n spec.addSub(Component.getInputSpecs())\n return spec",
"def get_input_specs(cls):\n input_specs = InputData.parameterInputFactory('Component', ordered=False, baseNode=None,\n descr=r\"\"\"defines a component as an elemen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deserialize a layer, then call it on appropriate inputs. | def process_layer(layer_data):
layer_name = layer_data['name']
# Instantiate layer.
from tensorflow.python.keras._impl.keras.layers import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top
layer = deserialize_layer(layer_data, custom_objects=custom_objects)
created_... | [
"def deserialize(cls, serialized):\n if serialized.WhichOneof(\"layer_data\") == \"relu_data\":\n return cls()\n return None",
"def from_translated_layer(self, layer, shape_dict):\n\n self.shape_dict = shape_dict\n program = layer.program()\n parameters = dict()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads all layer weights from a HDF5 save file. If `by_name` is False (default) weights are loaded based on the network's topology, meaning the architecture should be the same as when the weights were saved. Note that layers that don't have weights are not taken into account in the topological ordering, so adding or rem... | def load_weights(self, filepath, by_name=False):
if h5py is None:
raise ImportError('`load_weights` requires h5py.')
with h5py.File(filepath, 'r') as f:
if 'layer_names' not in f.attrs and 'model_weights' in f:
f = f['model_weights']
if by_name:
load_weights_from_hdf5_group_by_... | [
"def _load_layer_weights(self, layer, name, h5file): \n group = h5file[name]\n length = group['length'][0]\n weights = [group[\"{}\".format(idx)] for idx in range(length)]\n layer.set_weights(weights)",
"def _load_local_weights(self, h5file):\n for name, layer in self._la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a JSON string containing the network configuration. To load a network from a JSON save file, use `keras.models.model_from_json(json_string, custom_objects={})`. | def to_json(self, **kwargs):
if not self._is_graph_network:
raise NotImplementedError
def get_json_type(obj):
# If obj is any numpy type
if type(obj).__module__ == np.__name__:
return obj.item()
# If obj is a python 'type'
if type(obj).__name__ == type.__name__:
r... | [
"def from_json(filename):\n path = os.path.join(os.getcwd(), filename)\n with open(path, 'r') as fp:\n config = json.load(fp=fp)\n\n return layered_network_builder(config)",
"def load_network(file_name):\n with open(file_name) as file:\n data = json.load(file)\n\n cost_fn = getattr(sy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of input tensors necessary to compute `tensor`. Output will always be a list of tensors (potentially with 1 element). | def get_source_inputs(tensor, layer=None, node_index=None):
if not hasattr(tensor, '_keras_history'):
return tensor
if layer is None or node_index:
layer, node_index, _ = tensor._keras_history
if not layer._inbound_nodes:
return [tensor]
else:
node = layer._inbound_nodes[node_index]
if not ... | [
"def list_input_tensors(node):\n return [node.input_tensors] if hasattr(node.input_tensors, 'dtype') else node.input_tensors",
"def list_output_tensors(node):\n return [node.output_tensors] if hasattr(node.output_tensors, 'dtype') else node.output_tensors",
"def tensor_list_from_tensor(tensor, element_sha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts layers weights from Keras 1 format to Keras 2. | def preprocess_weights_for_loading(layer,
weights,
original_keras_version=None,
original_backend=None):
if layer.__class__.__name__ == 'Bidirectional':
num_weights_per_layer = len(weights) // 2
forward_wei... | [
"def get_conv_1_1_weights(vgg_weights_path):\r\n\ttemp_mod = Sequential()\r\n\ttemp_mod.add(ZeroPadding2D((1,1),input_shape=(224, 224, 3)))\r\n\ttemp_mod.add(Convolution2D(64, (3, 3), activation='relu', name='conv1_1'))\r\n\ttemp_mod.load_weights(vgg_weights_path, by_name=True)\r\n\tconv1_1_weigths = temp_mod.get_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator that handles tuple/TensorShape conversion. Used in `compute_output_shape` and `build`. | def shape_type_conversion(fn):
def wrapper(instance, input_shape):
if input_shape is not None:
if isinstance(input_shape, list):
input_shape = [
tuple(tensor_shape.TensorShape(x).as_list()) for x in input_shape]
else:
input_shape = tuple(tensor_shape.TensorShape(input_shap... | [
"async def infer_shape_make_tuple(track, *args):\n sh = [await x['shape'] for x in args]\n return TupleShape(sh)",
"def tupleize(func):\n def wrapper(*args, **kargs):\n return func(*args, **kargs),\n return wrapper",
"def wrap(func, *args, unsqueeze=False):\n\n # Convert input types where ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a map of the graph of layers. This recursively updates the map `layer_indices`, the list `nodes_in_decreasing_depth` and the set `network_nodes`. | def build_map(tensor,
finished_nodes,
nodes_in_progress,
layer,
node_index,
tensor_index):
node = layer._inbound_nodes[node_index] # pylint: disable=protected-access
# Prevent cycles.
if node in nodes_in_progress:
raise ... | [
"def construct_map(self) -> None:\n first_id = self.network_id\n visited = []\n self.__update_map(first_id, self._nb_modules, self._nb_modules,\n prev_id=-1, toward=(1, 0), visited=visited)",
"def createLevelMaps(self):\n # For neighborhood maps\n self.l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to Track Moisture Level Returns Moisture Value | def track_moisture_level():
try:
normal_level_init = 470
low_level_init = 560
global LIMIT_FLAG
sensor_read = sensorData.read_moisture()
generate_json.define_structure("moisture", sensor_read)
if sensor_read > low_level_init:
if LIMIT_FLAG != 3:
... | [
"def current_moisture(self) -> int:\n return int(self.get_state(self.entity_ids['current_moisture']))",
"def moisture(self):\n if self.moisture_sensor is None:\n return None\n else:\n return self.moisture_sensor.percent",
"def test_get_muveto_gain_measurements(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
explainerdashboard CLI tool. Used to launch an explainerdashboard from the commandline. \b explainerdashboard run Run explainerdashboard and start browser directly from command line. \b | def explainerdashboard_cli(ctx): | [
"def cli():\n config, auth, execute_now = read_command_line_arguments()\n main(config, auth, execute_now)",
"def main():\n\tcli = Cli()\n\tcli.run()",
"def dashboard(self):\n self.program()\n self._url_name = 'gsoc_dashboard'\n return self",
"def boilerplate_cli():\n\twith open(os.path.join(\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(file open for reading) > list of float Read and return list of grades in gradefile | def read_grades(gradefile):
#skip over header
line = gradefile.readline()
while line != '\n':
line = gradefile.readline()
#read the grades, accumlating them into a list.
grades = []
line = gradefile.readline()
while line != '':
#We have a string containing info for singl... | [
"def read_grades(gradefile):\n\n # skip over the header.\n line = gradefile.readline()\n while line != '\\n':\n line = gradefile.readline()\n\n # Read the grades, accumulating them into a dict.\n grade_to_ids = {}\n line = gradefile.readline()\n while line != '':\n # Now we have a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is automatically called when the task has completed (successfully or not). You implement finished() to do whatever followup stuff should happen after the task is complete. finished is always called from the main thread, so it's safe to do GUI operations and raise Python exceptions here. result is the retu... | def finished(self, result):
raise NotImplementedError("Subclasses mut override finished()") | [
"def finished(self, result):\n raise NotImplementedError",
"def finished(self, result):\n if result:\n QgsMessageLog.logMessage(\n 'RandomTask \"{name}\" completed\\n' \\\n 'RandomTotal: {total} (with {iterations} '\\\n 'iterations)'.format(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch license artifacts associated with the service model and search licensekeygroupUUID and entitlementpooluuid associated with the given att part number and nominal throughput in a request | def license_optim(request_json):
mdc_from_json(request_json)
req_id = request_json["requestInfo"]["requestId"]
model_name = request_json.get('placementInfo', {}).get('serviceInfo', {}).get('modelInfo', {}).get('modelName')
service_name = model_name
license_info = []
for demand in request_json... | [
"def apply_licenses(**kwargs):\n\n auth = kwargs['auth']\n args = kwargs['args'].__dict__\n\n license_type = args['licenseType']\n\n if license_type is None:\n print('--licenseType should not be None')\n sys.exit(1)\n\n url = f'{BURL}/compute/PhysicalSummaries'\n response = requests.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a random start point for a new snake and return its coordinates. | def get_new_snake():
global direction, snake, X_start, Y_start
X = [x for x in range(40, WINDOWWIDTH - 80, 20)] #multiplier list 20
Y = [y for y in range(40,WINDOWHEIGHT - 80, 20)]#multiplier list 20
X_start = random.choice(X)#random multiplier of 20
Y_start = random.choice(Y)#random multiplier of ... | [
"def _random_start_position(self):\r\n self.position = np.array(random.choice(self.start_positions),\r\n dtype=np.int16)",
"def gen_start_pt(self):\n if self._start_coord is not None:\n # If starting coordinate is specified\n coord = self._start_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make a list of recent acis observation | def get_recent_obsid():
#
#--- extract a list of the last two weeks of acis observations
#
stop = time.strftime('%Y:%j:%H:%M:%S', time.gmtime())
stop = Chandra.Time.DateTime(stop).secs
start = stop - 86400 * 14
a_list = make_obsid_list(start, stop)
return a_list | [
"def get_observation_list(self):\n return self.observations",
"def __recent_events(self):\n\n events_list = []\n #restrict to events which have already happened\n restrict_committed = 'AND journal.committed=1 '\n #restrict to the latest events\n #assuming that max 1 event... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
compress older plots files | def zip_old_plot_file(a1=30, a2=60):
today = time.strftime('%Y:%j:%H:%M:%S', time.gmtime())
today = Chandra.Time.DateTime(today).secs
stop = today - 86400 * a1
start = today - 86400 * a2
a_list = make_obsid_list(start, stop)
for obsid in a_list:
cdir = plot_dir + 'Ind_Plots/acis... | [
"def save_fig(ax_data, file_name):\n with open(file_name,'wb') as fid:\n pickle.dump(ax_data, fid)",
"def save_all_plots(self):\n widget = self.current_widget()\n if widget:\n widget.thumbnails_sb.save_all_figures_as()",
"def savexPlot(self):\n for p in self.getSpatialP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates the value of the cost function for given parameters by communicating with client. | def __call__(self, parameters) -> ValueEstimate:
# Encode params to json string
save_circuit_template_params(parameters, "current_optimization_params.json")
with open("current_optimization_params.json", "r") as f:
current_params_string = f.read()
# POST params to proxy
... | [
"def eval_cost(self, params, **kwargs):\n raise NotImplementedError",
"def evaluate_cost(self, msg):\n raise NotImplementedError()",
"def EvaluateFunction(self, p_float=..., p_float=..., p_float=...):\n ...",
"def callFunction(self, nodeId, params):\n try:\n self.lock_ac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Kills excel Background process inorder to fetch the active worksheet. This is dangerous and close all other excel sheets before using this function. | def kill_excel_bg():
excel_process = [
process for process in psutil.process_iter() if process.name() == "EXCEL.EXE"
]
for process in excel_process:
xl_files = [f.path for f in process.open_files() if ".xl" in f.path]
print(xl_files)
if len(xl_files) == 0:
process... | [
"def CloseExcelFile(self):\r\n self.ss.close(False) # SaveChanges = False\r\n self.xl.Application.Quit()",
"def close(self):\r\n self.workbook.close()",
"def open_excel_workbook():\n wb = openpyxl.Workbook()\n del wb[\"Sheet\"]\n # wb.remove_s(wb.get_sheet_by_name(\"Sheet\"))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Connects to the current active excel workbook and return win32com client object. Using this function has known issues. | def connect_to_excel() -> w32:
xl = xl_app()
if xl.ActiveWorkbook is None:
kill_excel_bg()
xl = xl_app() # type: w32
logging.info(f"Connected to excel sheet {xl.ActiveWorkbook.Name}")
return (
xl
if check_jupyter_excel_connection(xl)
else Exception("Not conne... | [
"def xl_app():\n # get the Excel application object from PyXLL and wrap it\n xl_window = get_active_object()\n xl_app = win32com.client.Dispatch(xl_window).Application\n # it's helpful to make sure the gen_py wrapper has been created\n # as otherwise things like constants and event handlers won't wor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load modules from the pyxll config file. Useful in a jupyter notebook environment | def load_modules_from_config(cfg: str):
pyxll_cfg = ConfigParser()
pyxll_cfg.read(cfg)
for path in pyxll_cfg["PYTHON"]["pythonpath"].split("\n"):
sys.path.append(path) | [
"def load_modules(bot, config):\n for item in MODULES:\n importlib.import_module(\"cogs.\" + item).setup(bot, config)",
"def test_load_extension():\n config_set({\n 'extensions': {\n # These modules are chosen because:\n #\n # 1. They are in the standard librar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a callback for comm_close Will be called with the `data` of the close message. Call `on_close(None)` to disable an existing callback. | def on_close(self, callback):
self._close_callback = callback | [
"def on_close(self, callback: Optional[PyGuiCallback]) -> Callable:\n if callback is not None:\n callback = wrap_callback(callback)\n self._on_close_callback = callback\n return callback",
"def register_on_closed(self, callback: Callable[[Exception], None]) -> None:\n self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle a comm_close message | def handle_close(self, msg):
self.log.debug("handle_close[%s](%s)", self.comm_id, msg)
if self._close_callback:
self._close_callback(msg) | [
"def comm_close(self, msg):\n content = msg['content']\n comm_id = content['comm_id']\n comm = self.get_comm(comm_id, closing=True)\n if comm is None:\n return\n\n self.unregister_comm(comm)\n\n try:\n comm.handle_close(msg)\n except Exception:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
verifier si un element existe dans une list | def exist(self,list,a):
i = 0
for elem in list:
if (elem == a):
i=i+1
if (i>0):
return True
else:
return False | [
"def check_list_exists(this_list=[]):\n if isinstance(this_list, list) and len(this_list) > 0:\n return True\n else:\n return False",
"def listExists(self,id):\n return id in self.lists",
"def esta_en_lista(self, elemento, lista):\n rta = False\n for subl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to handle filtered items comma delimited string | def split_cmdline_filter_items(string):
filter_items = string.split(',')
return filter_items | [
"def test_comma_separated_values(self):\n handler = ReservoirQueryParameters(\n included_keywords='bear, cat, dog',\n excluded_keywords='eagle, fox, gator'\n )\n terms = handler._create_searchterms()\n self.make_comparisons_for_words(terms)",
"def parse_comma_sepa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to parse commandline arguments of serving size and filter items | def parse_arguments():
global parser
parser = argparse.ArgumentParser(
description='Certainly this isn\'t how Food Network does it',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent('''
Recipe List must appear as follows. **... | [
"def parse_args(args=None, filter=None):\n parser = OptionParser(usage=\"Usage: %prog [<program options>] <filter [<filter options>] ...>\\n\\n\"\n \"Options that require a number of Bytes as an argument also accept values given \\n\"\n \"as e.g. 256k = 256 * 1024 Bytes. Units that are understood a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to parse txt file of recipes and construct 2D list tokenizing each of the recipes metadata and ingredient content | def construct_list_of_recipes():
sub_list = []
with open(args.input_file, 'r') as f:
lines = [line if line == '\n' else line.rstrip('\n') for line in f]
recipes_list = []
for element in lines:
if element == '\n':
recipes_list.append(sub_list)
sub_list = []
... | [
"def read_foods(foods_txt):\n foods = []\n for line in foods_txt:\n ingredients_txt, allergens_txt = line.split(\" (contains \")\n ingredients = ingredients_txt.split()\n allergens = allergens_txt[:-1].split(\", \")\n\n foods.append((ingredients, allergens))\n\n return foods",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to construct a new output_dict excluding recipes with filter_ingredients | def filter_output_dict(output_dict):
global filter_ingredients
if filter_ingredients:
filtered_dict = {k: v for k, v in
output_dict.iteritems() if
all(filter_item in v['ingredients']
for filter_item in filter_ingredients)}
... | [
"def filter_recipes(self, path: str, output: str) -> None:\n\n data = self.load(path)\n\n for recipe in data[:]:\n if (\n recipe['image_url'] == 'none'\n or len(recipe['ingredients']) == 0\n or len(recipe['instructions']) == 0\n ):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over the recipes and wrap them into a output dict | def construct_output_dict():
list_of_recipes = construct_list_of_recipes()
output_dict = {}
for recipe_list in list_of_recipes:
recipe_instance = construct_recipe_object(recipe_list)
recipe_dict = recipe_instance.construct_json_rep_obj()
for k, v in recipe_dict.iteritems():
... | [
"def GetRecipes(self) -> Dict[str, str]:\n recipes = {}\n for recipe in self.recipe_manager.GetRecipes():\n recipes[recipe.name] = recipe.contents.get(\n 'short_description', 'No description.')\n return recipes",
"def _process_ingredients(recipes):\n ingredients = {}\n counter = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
interest_param is a tuple containing a dict containing the satellite name, orbit parameters, and orbit classifications | def __init__(self, interest_param):
self.name, self.orbit_param, self.orbit_class, self.orbit_type = interest_param
# dict containing NEO, MEO, GEO,
# apogee, perigee, or elliptical
# inclination, period,
# and eccentricity | [
"def interest(self, interest):\n self._interest = interest",
"async def on_interest(self, param: InterestParam, app_param: Optional[BinaryStr], raw_packet: BinaryStr):\n # Cache search\n cache_policy = self.policies.get(policy.Cache, None)\n if cache_policy and isinstance(cache_policy,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extend to encode random f and cr values onto each member of the population. | def __init__(self, *args, **kwargs):
super(jDE, self).__init__(*args, **kwargs)
for i in range(self.population.size):
self.population.members[i].f = 0.1 + 0.9 * numpy.random.rand()
self.population.members[i].cr = numpy.random.rand() | [
"def mutate_all(self):\n for indiv in self.individuals[self.elite_count:]:\n self.update_mutation_factor()\n new_genotype = indiv.genotype\n for j in range(self.num_vars):\n if random.random() < self.mut_rate:\n offset = (2*(random.random()-0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
生成第i个个体变异重组后的个体 Base f and cr upon parent member, or regenerate (p=0.1). | def generateTrialMember(self, i):
# Pick f and cr
parent = self.population.members[i]
if numpy.random.rand() > 0.1:
f = parent.f
else:
f = 0.1 + 0.9 * numpy.random.rand()
if numpy.random.rand() > 0.1:
cr = parent.cr
else:
cr... | [
"def produce_next_generation(self):\n size = 5\n start = random.randint(0,self.gene_size-size)\n end = start+size\n length = int(len(self.parents)/2)\n for i in range(length):\n p1 = self.parents[i*2][1]\n p2 = self.parents[i*2+1][1]\n p1copy = cop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Profiles a given cuda application using the command provided The profile data is returned as a dict of kernels with their metrics and the data for each call | def ProfileApp(command):
logging.info("Command to profile: {0}".format(" ".join(command)))
kernelMetrics = dict()
# get execution time first because for whatever reason
# we need a different nvprof command
# build the profiling command
profileCommand = ["nvprof", "--print-gpu-trace", "--csv"]... | [
"def test_cuda_profiler1():\n if fluid.is_compiled_with_cuda():\n if os.path.exists(\"./cuda_profile.txt\"):\n os.remove(\"./cuda_profile.txt\")\n main_program = fluid.Program()\n startup_program = fluid.Program()\n with profiler.cuda_profiler(\"cuda_profile.txt\", \"kvp\")... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a set of metrics and adds a set of derived metrics A given set of throughput metrics will be converted to its equivalent counts using the duration given in statistics Metrics from combined metrics will then be summed together to generate a new combined metric | def generateDerivedMetrics(kernelMetrics, statistics, throughputMetrics = {}, countMetrics = {}, combinedMetrics = {}):
# combine single metrics
for combinedMetric in combinedMetrics:
for kernel in kernelMetrics:
logging.debug("Combining metrics for kernel {}".format(kernel))
#... | [
"def add_stats(self):\n units = self.get_unit_map()\n for metric in self.raw_metrics:\n unit, metric_type = units.get(metric, (DEFAULT_UNIT, DEFAULT_TYPE))\n if metric_type == \"counter\":\n # Unit/Second\n unit = \"/\".join((unit, \"Second\"))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates roofline points from a set of kernel metrics The flops type is automatically selected to be the one with the highest throughput | def generateRooflinePoints(kernelMetrics):
rooflines = dict()
memRooflines = dict()
# one point for each kernel
# runs are averaged
for kernel in kernelMetrics:
logging.debug("Starting roofline generation for kernel {}".format(kernel))
# figure out which flops is highest
fl... | [
"def roofline_plot():\n\n def attainable_performance(operational_intensity):\n return min(PEAK_PERFORMANCE, MEMORY_BANDWIDTH * operational_intensity)\n\n oi_values = np.logspace(-4, 12, 1000, base=2)\n perf_values = [attainable_performance(oi) for oi in oi_values]\n fig, ax = viz_utils.setup_figu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates and aspen model based on kernel metrics counts will be based on profile data | def generateAspenModel(kernelMetrics, modelName=None, rooflines=None):
# metrics we care about and the mapping to aspen resources
aspenMetricsFlops = {"flop_count_dp" : "as dp",
"flop_count_sp" : "as sp"}
aspenMetricsMem = {"dram_read_bytes" : "loads",
"d... | [
"def output_models(self):\n bounds = self.manipulator.get_bounds()\n cfg_vecs = self.manipulator.get_random_vecs(self.sample_cnt, bounds)\n\n results = {}\n for model in self.models:\n results[model.metric] = model.sample_models(cfg_vecs)\n\n info = DebugInfo(tuning_run=self.driver.tuning_run,\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tries to cast the port to integer. If it's not possible, the initial string value is returned. | def valid_port(ctx, param, value):
try:
value = int(value)
except ValueError:
pass
return value | [
"def _port_to_int(port):\n if isinstance(port, int):\n return port\n # Assume it's two bytes in NBO:\n return struct.unpack('!H', port)[0]",
"def _grab_port(self):\r\n port = \"\"\r\n while self._char != -1 and self._char in \"0123456789\":\r\n port += self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function creates the SQL query depending on the specified port and the like option. | def get_ports(port, like=False):
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
where_field = "port" if isinstance(port, int) else "name"
where_value = "%{}%".format(port) if like else port
cursor.execute(BASE_SQL + where_field + " LIKE ?", (where_value,))
return cursor | [
"def buildQuery():",
"def psql(self, query, **kwargs):\n\n self.set_default_connection_options(kwargs)\n connect_options = \" \".join([f\"{k}={v}\" for k, v in kwargs.items()])\n\n run([\"psql\", f\"port={self.port} {connect_options}\", \"-c\", query], shell=False)",
"def specific_ports(pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function returns a pretty table used to display the port results. | def get_table(ports):
table = PrettyTable(["Name", "Port", "Protocol", "Description"])
table.align["Name"] = "l"
table.align["Description"] = "l"
table.padding_width = 1
for p in ports:
table.add_row(p)
return table | [
"def get_table(ports):\n table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n table.align[\"Name\"] = \"l\"\n table.align[\"Description\"] = \"l\"\n table.padding_width = 1\n\n for port in ports:\n table.add_row(port)\n\n return table",
"def pretty_print(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return phase and composition. | def get_phase_and_composition(self):
data = self.data
total = data.sum()
if total <= 0.: raise RuntimeError(f"'{phase_names[self.phase]}' phase does not exist")
return self.phase, data / total | [
"def getPhase(phase):",
"def GetPhase(self):\n ...",
"def _phase(self):\n re = self.real\n im = self.imag\n \n return im._atan2(re)",
"def phase(self):\n return Integer(-1)",
"def _phase(self):\n return UncertainReal._constant(0.0)",
"def m_phase(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over phasedata pairs. | def __iter__(self):
return zip(self._phases, self.data) | [
"def _iter_items(data_sequence):\n for time, element in data_sequence:\n for item in element:\n yield time, item",
"def iter_over_pairs(pairs):\r\n if isinstance(pairs, dict):\r\n return pairs.iteritems()\r\n else:\r\n return pairs",
"def variableIter(self):\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over phasecomposition pairs. | def iter_composition(self):
array = self.data
total = array.sum() or 1.
return zip(self._phases, array/total) | [
"def __iter__(self):\n return zip(self._phases, self.data)",
"def iter_components(self):\n for iv in range(len(self._var_names)):\n yield self._var_names[iv], self._vals[iv]",
"def phi_iter(atoms):\n res_iter1 = struct.residue_iter(atoms)\n res_iter2 = struct.residue_iter(atoms)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a ChemicalMassFlowIndexer that references this object's molar data. | def by_mass(self):
try:
mass = self._data_cache['mass']
except:
chemicals = self.chemicals
self._data_cache['mass'] = mass = \
ChemicalMassFlowIndexer.from_data(
SparseVector.from_dict(
MassFlowDict(self.data.dct, chemicals.MW),
chemica... | [
"def Mol(self):\n return self.Molecule",
"def ion_to_molecule(self):\n data_dict = self.data_dict\n\n formal_charge = data_dict.pop(\"formal_charge\")\n explicit_hs = data_dict.pop(\"explicit_hs\")\n radical_electrons = data_dict.pop(\"radical_electrons\")\n pos_nitrogen ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a ChemicalVolumetricFlowIndexer that references this object's molar data. | def by_volume(self, TP):
try:
vol = self._data_cache['vol', TP]
except:
chemicals = self._chemicals
V = [i.V for i in chemicals]
phase = self._phase
self._data_cache['vol', TP] = \
vol = ChemicalVolumetricFlowIndexer.from_data(
SparseVector.from_dict(
... | [
"def by_volume(self, TP):\n try:\n vol = self._data_cache[TP]\n except:\n phases = self._phases\n chemicals = self._chemicals\n V = [i.V for i in chemicals]\n size = chemicals.size\n self._data_cache[TP] = \\\n vol = VolumetricFlowIndexer.from_data(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a VolumetricFlowIndexer that references this object's molar data. | def by_volume(self, TP):
try:
vol = self._data_cache[TP]
except:
phases = self._phases
chemicals = self._chemicals
V = [i.V for i in chemicals]
size = chemicals.size
self._data_cache[TP] = \
vol = VolumetricFlowIndexer.from_data(
SparseArray.fr... | [
"def by_volume(self, TP):\n try:\n vol = self._data_cache['vol', TP]\n except:\n chemicals = self._chemicals\n V = [i.V for i in chemicals]\n phase = self._phase\n self._data_cache['vol', TP] = \\\n vol = ChemicalVolumetricFlowIndexer.from_data(\n SparseVec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns first task in the individual robot buffer. Task is deleted. | def get_first_task(self, robot_id):
individual_buffer = self.all_buffers[robot_id]
task = individual_buffer[-1]
individual_buffer = np.delete(individual_buffer, -1, 0)
self.all_buffers[robot_id] = individual_buffer
return task | [
"def check_first_task(self, robot_id): \n individual_buffer = self.all_buffers[robot_id]\n return individual_buffer[-1]",
"def get_task(self): \n task = self.buffer[0]\n self.buffer = np.delete(self.buffer, 0, 0)\n return task",
"def get_last_task(self, robot_id)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check first task info without deletion. | def check_first_task(self, robot_id):
individual_buffer = self.all_buffers[robot_id]
return individual_buffer[-1] | [
"def is_task_stagnant(task):",
"def check_done(self):\n return not bool(len(self.tasks))",
"def check_repeated_task(self, task):\n task_status = task in self.tasks_asked\n\n # append if never asked\n if task_status == False:\n self.tasks_asked.append(task)\n\n return ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |