query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Given a process object, wait for it to complete then return a tuple with stdout and stderr
def process_results(process_object): (stdout, stderr)=process_object.communicate() return (process_object.returncode, stdout, stderr)
[ "def wait(self):\n if self.process is not None:\n stdout, stderr = self.process.communicate()\n exit_code = self.process.wait()\n # Ensure that we reap the file descriptors.\n self.cleanup()\n return (exit_code, decode_bytes(stdout), decode_bytes(stderr)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pipe a python string to standard input for cmd_string >>> pipestring_process('grep 2', '1\n2\n3\n')[1] '2\n'
def pipestring_process(cmd_string, stdin_string=''): f=SpooledTemporaryFile() f.write(stdin_string) f.seek(0) results=process(cmd_string, stdin=f) f.close() return results
[ "def pipe_string(engine: str, format: str, input_string: str,\n *, encoding: str,\n renderer: typing.Optional[str] = None,\n formatter: typing.Optional[str] = None,\n quiet: bool = False) -> str:\n cmd = command(engine, format, renderer=renderer, formatt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a dictionary generated by crm2dict into a format compatible with the haresources2 library. There are a few key format differences. Instead of a key map, there is a list with 'name' fields. The "members" field is dropped, as this information is implied from the other fields. Finally, the loadbalancers are placed...
def crmdict2haresources(anydict): lst=[] for k in anydict.keys(): d={} for subkey in anydict[k].keys() + ['name']: if subkey == 'name': d.setdefault(subkey, k) elif subkey == 'loadbalancers': numbalancers=len(anydict[k][subkey].keys()) ...
[ "def _transform_loadbalancer(loadbalancer, haproxy_base_dir):\n listeners = [_transform_listener(x, haproxy_base_dir)\n for x in loadbalancer.listeners if x.admin_state_up]\n pools = [_transform_pool(x) for x in loadbalancer.pools]\n return {\n 'name': loadbalancer.name,\n 'vip_address...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a candidate filename, returns (candidate_config, live_config)
def get_configs(candidate_filename): return (sortby('name')(haresources2.load(haresources2_file)), sortby('name')(crmdict2haresources(crm2dict(configure_parse()))))
[ "def load_merge_candidate(self, filename=None, config=None):\n raise NotImplementedError", "def findcfg():\n candidates = find_configs()\n if not candidates:\n click.echo(\n click.style(\n 'No candidate config files were found.',\n fg='yellow')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize with the attr name
def __init__(self, attr=None): self.attr = attr
[ "def load_attr(self, name):\n self.code_ops.append( # TOS -> obj\n (bp.LOAD_ATTR, name), # TOS -> value\n )", "def init_attrs(self):\n raise NotImplementedError", "def map_attr(self, **kwargs):\n attr_name, spec = getargs('at...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the attr name
def getAttrName(self, context): return self.attr if self.attr is not None else context.attr
[ "def attribute_name(self) -> str:\n return self._attribute_name", "def getAttrName(self, *args):\n return _libsbml.XMLToken_getAttrName(self, *args)", "def attrname(self):\n return self.path[-1] if self.path else None", "def get_attr_name(attr_id, obj_db):\n result = obj_db.select('att...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an iterator that repeats until a timeout is reached timeout is in seconds
def until_timeout(timeout, value=None): start = time.time() while True: if time.time() - start >= timeout: raise Exception("timed out before success!") yield value
[ "def repeater(at_least, timeout):\n timer = Timer(timeout)\n repeat = 0\n while repeat < at_least or timer.remaining():\n yield repeat\n repeat += 1", "def itime(iterable, seconds):\n items = iter(iterable)\n\n end = time.time() + seconds\n yield items.next()\n\n for item in ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if any actuator message is available.
def _IsActuatorMessageAnyValid(mode, node_labels, node_label_helper, max_no_update_count, *attributes): if mode == common.SPARSE_COMMS_MODE: # Check the `valid` variable for TetherDown. if attributes[1]: for label in node_labels: idx = node_label_helper.Value(label...
[ "def check_status_message_is_clear(self):\n pattern = '(Unit is ready|Unit is ready and clustered)$'\n for unit in zaza.model.get_units(self.application_name):\n zaza.model.block_until_unit_wl_message_match(\n unit.entity_id,\n pattern)\n zaza.model.bloc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if all actuator message are available.
def _IsActuatorMessageAllValid(mode, node_labels, node_label_helper, max_no_update_count, *attributes): if mode == common.SPARSE_COMMS_MODE: # Check the `valid` variable for TetherDown. if attributes[1]: for label in node_labels: idx = node_label_helper.Value(label...
[ "def _check_all_systems_ready(self):\n self._check_all_sensors_ready()\n return True", "def _check_all_systems_ready(self):", "def __reader_check_complete_all_event(self):\n if self._complete_all_event.is_set():\n self.logger.info(\"Received complete all request event in reader\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check status flags per node and set stoplight accordingly. Normal if all nodes have the expected statuses, warning otherwise.
def _CheckStatusFlags(self, raw_node_status, status_helper, expected_statuses, failed_stoplight): if self._mode == common.FULL_COMMS_MODE: filtered_nodes = checks.GetActuatorsWithStatus( raw_node_status, status_helper, expected_statuses) node_status = {key: 1 if key in...
[ "def check_nodes():\n failed_nodes = []\n for node, status in monitoring_results.items():\n if status == 'down':\n failed_nodes.append(node)\n return failed_nodes", "def test_get_node_status_batterystatus(self):\n pass", "def test_monitorNetworkStatus(self):\n self.setup...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the stoplight according to the values.
def _GetStoplight(self, values, any_values, missing_values, flight_mode): if not any_values: stoplight = stoplights.STOPLIGHT_UNAVAILABLE elif missing_values: stoplight = stoplights.STOPLIGHT_ERROR else: stoplight = stoplights.STOPLIGHT_NORMAL if values and flight_mode in self._limits...
[ "def getStop(self, i):\n stopID = self.trip_update.stop_time_update[i].stop_id\n stop = self.stops[stopID]\n return stop", "def get_traffic_light(self):\n for light in self.model.traffic_lights: # loop over all lights\n # if light has same direction as car\n if l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract avionics monitor data fields.
def GetMonitorFields(message, monitor_field, monitor_type, monitor_helper, warning_helper, error_helper, monitor_names, aio_node, read_error_name): monitor = getattr(message, monitor_field) populated = getattr(monitor, monitor_type + '_populated') warning = False error ...
[ "def parseMonitor(self, monitor):\r\n param = \"\"\r\n if monitor[\"opcode\"] == \"data_variable\":\r\n cmd = \"getVar:\"\r\n param = monitor[\"params\"][\"VARIABLE\"]\r\n color = self.monitorColors[\"data\"]\r\n elif monitor[\"opcode\"] == \"data_listcontents\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the ief_instance_id of this ListAppsRequest. 铂金版实例ID,专业版实例为空值
def ief_instance_id(self): return self._ief_instance_id
[ "def app_id(self):\n return self._app_id", "def get_app_instance_name(self):\n engine = self.get_engine()\n if engine is None:\n return None\n\n if \"app\" not in self.properties:\n return None\n\n app_instance = self.properties[\"app\"]\n\n for (app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the ief_instance_id of this ListAppsRequest. 铂金版实例ID,专业版实例为空值
def ief_instance_id(self, ief_instance_id): self._ief_instance_id = ief_instance_id
[ "def ief_instance_id(self):\n return self._ief_instance_id", "def instance_id(self, instance_id):\n self._instance_id = instance_id", "def instance_id(self, instance_id):\n\n self._instance_id = instance_id", "def _set_instance_id(self, v, load=False):\n parent = getattr(self, \"_paren...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the alias of this ListAppsRequest. 通过别名过滤,模糊匹配
def alias(self, alias): self._alias = alias
[ "def setAlias(self, alias):\n \n pass", "def set_alias(self, alias):\n\n self.alias = alias", "def update_app_alias(self, api_key, device_name, app_raw_name, app_alias):\n raise NotImplementedError", "def set_aliases(self, aliases):\n self.client.prefs.team_put('aliases', aliase...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return default blank user extra data
def extra_data(self, user, uid, response, details): try: return self.get_steam_profile(response) except: return ""
[ "def augment_user_data(self, data):\n user_id = data.get('id')\n if user_id:\n data['name'] = user_id\n data['avatar'] = ''\n user_details = api.users.get_user_details(\n self.context,\n user_id,\n portal_url=self.tools['por...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return Steam OpenID service url
def openid_url(self): return STEAM_OPENID_URL
[ "def openid_url(self):\r\n return GOOGLE_OPENID_URL", "def openid_url(self):\r\n return YAHOO_OPENID_URL", "def make_openid_url( email ):\n return os.path.join( CONFIG.SYNDICATE_OPENID_TRUSTROOT, \"id\", email )", "def openid_url(self):\n return TURKCELL_OPENID_URL", "def get_service...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a new linked list containing the given items. The first node in the linked list contains the first item in .
def __init__(self, items): if len(items) == 0: # No items, and an empty list! self._first = None else: self._first = _Node(items[0]) curr = self._first for item in items[1:]: curr.next = _Node(item) curr = curr.next
[ "def __init__(self, items: List) -> None:\n if len(items) == 0: # No items, and an empty list!\n self._first = None\n else:\n self._first = Node(items[0])\n current_node = self._first\n for item in items[1:]:\n current_node.next = Node(item)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds and runs a model given a dictionary of hyperparameters
def model(self, hyperparams, test_mode=False): run_doc = OrderedDict() # Document important hyperparameters run_start_time = time.time() run_id = str(uuid4()) # TODO: Not ideal: Loads from memory every time. Use generator? train_data, train_targets, test_data, test_targets = \ ...
[ "def build_model(train_inputs,train_labels,model_params,model_mode='classification',\n model_type='naive_bayes'):\n if model_mode == \"classification\":\n if model_type == \"naive_bayes\":\n model = GaussianNB()\n if model_type == \"knn\":\n model = KNeighbo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the iSCSI initiator node name IQN
def get_initiator(self): out, err = self.execute('/usr/sbin/iscsiadm', 'list', 'initiator-node') # Sample first line of command output: # Initiator node name: iqn.1986-03.com.sun:01:e00000000000.4f757217 initiator_name_line = out.splitlines()[0] return initiator_name_line.rsplit...
[ "def iscsi_node_get_name(self):\n return self.request( \"iscsi-node-get-name\", {\n }, {\n 'node-name': [ basestring, False ],\n } )", "def _get_iqn(self, port, hostgroup):\n hba_iscsis = self.client.get_hba_iscsis_by_name(port, hostgroup)\n return hba_iscsis[0]['iscs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use a Fibonacci spiral to distribute points uniformly on a sphere.
def fib_sphere_grid(npoints): phi = (1.0 + np.sqrt(5.0)) / 2.0 i = np.arange(npoints, dtype=float) i2 = 2*i - (npoints-1) theta = (2.0*np.pi * i2/phi) % (2.*np.pi) sphi = i2/npoints phi = np.arccos(sphi) return theta, phi
[ "def fermat_spiral_points(center, beam_diam, overlap, num_points):\n return spiral", "def create_spiral(r1, r2, N):\n Pi = 3.141592\n points = []\n finished = [False]\n\n def rad(phi):\n return phi / (2 * Pi)\n\n def ang(rad):\n return 2 * Pi * rad\n\n def coord(phi):\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Divide el tileset en tiles que pueden ser accedidos mediante una fila y una columna.
def split_tileset(self, tileset): tiles = self.tiles firstgid = tileset.firstgid tilewidth = self.tilewidth tileheight = self.tileheight margin = tileset.margin # carga la imagen del tileset y obtiene sus dimensiones image = pygame.image.load(tileset.image_path)...
[ "def divide_bricks(pyramid):\n for row in pyramid:\n for i in range(0, len(row)):\n row[i] /= 990", "def split_main_image(image: Image, tile_size: int) -> list:\n rgb_img = image.convert('RGB')\n img_grid = list()\n\n if rgb_img.width % tile_size == 0 and rgb_img.height % tile_size =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ordena una lista de tiles en un diccionario donde pueden ser accedidos mediante una fila y una columna.
def arrange_tiles(self, layer): # número de tiles en 'x' width = self.width arranged_tiles = layer.arranged_tiles row = -1 # convierte una lista en un diccionario for col, tile in enumerate(layer.tiles): # calcula la ubicación en dos dimensiones (fila y col...
[ "def get_tiles(self):\n\n tiles = []\n for x in range(self.position[0],\n self.position[0] + CAR_LENGTH if self.is_horizontal else self.position[0] + CAR_WIDTH):\n for y in range(self.position[1],\n self.position[1] + CAR_WIDTH if self.is_hori...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dibuja solo los tiles dentro del campo visual de la cámara.
def draw(self, screen, camera): tilewidth = self.tilewidth tileheight = self.tileheight tiles = self.tiles # si el rectángulo que ocupa el tilemap no se encuentra en el campo visual de la cámara, no se dibuja nada if not camera.colliderect(self.rect): return ...
[ "def render_tiles(self, tiles):\n for row in tiles:\n for tile in row:\n if tile is not None:\n if tile.height < 0:\n color = (0, 100, 0)\n else:\n z = max(0, tile.height)\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Access graph generated by covariance
def graph(self): assert self._modeled, "Need to do calc_covariance" return self._graph
[ "def get_covariance_copy(self):\n return copy.deepcopy(self._covariance)", "def graph(self):", "def graph(self):\n return self._func_graph", "def _construct_graph(self):\n raise NotImplementedError", "def build_covariance(self):\n raise RuntimeError(\"Your Gaussian covariance code needs ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a string message to the C2 server and get the decrypted result.
def send_to_c2(msg: str) -> str: msg_as_ord = [ord(c) for c in msg] msg_encrypted = crypt1(msg_as_ord) resp = requests.post(C2_URL, data=str(msg_encrypted)) if resp.status_code != 200: print('Got status code', resp.status_code) return None raw_resp = resp._content.decode('utf-8') ...
[ "def decrypt_message(encrypted_message):", "def _send_echo(self, conn):\n # Re-encrypt the echo message\n iv = Random.new().read(self.AES_IV_SIZE)\n cipher = AES.new(self._session_secret, AES.MODE_CBC, iv)\n ciphertext = iv\n ciphertext += cipher.encrypt(self._echo_msg)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Init pylirc and connect to the mainloop.
def init(appname = None, cfg = None): global _dispatcher if _dispatcher: # already running return False if not pylirc: # not installed return False if cfg == None: cfg = os.path.expanduser("~/.lircrc") if appname == None: appname = "kaa" try: ...
[ "def start_event_loop(self):", "def init():\n\tglobal settings\n\t\n\tsettings = settings_manager.Singleton()\n\t\n\tsettings._telnet = False\n\tsettings._counters = { 'send': 0, 'recv': 0, 'flush': 0 }\n\tsettings._seqSave = {}\n\t\n\tif settings.skip_shutdown == False:\n\t\tsignal.signal(signal.SIGINT, graceful...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to create an agent set with tasks, impostors
def create_agents(game_map, km, num_crew, num_imp, num_tasks, num_visuals, cooldown, stat_thres): agents = [Crewmate(x, num_crew, num_imp, game_map, km, num_tasks, num_visuals) for x in range(num_crew)] # noinspection PyTypeChecker [agents.append(Impostor(num_crew + x, num_crew, num_imp, game_map, km, coold...
[ "def setup_agents(self):\n for i in range(self.num_agents):\n agent_id = 'agent-' + str(i)\n agent = MatrixAgent(agent_id, self.game)\n self.agents[agent_id] = agent", "def _init_agents(self):\n self.agents = [Agent(e=0.1, a=0.1, row=self.row, col=self.col) for i in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crewmates vote for an agent if they're sure they are the impostor. Otherwise, they have a chance of either voting an agent that they still suspect, or passing.
def vote(self, agents): suspects = [] known_impostor = -1 # Check which agents the current agent still suspects for a in agents: if self.km.knows_imp(self.agent_id, a.agent_id): known_impostor = a.agent_id self.logger.log(f"Crewmate {self.agen...
[ "def vote(self, agents):\n\n # If the impostors have a set target, vote that\n if self.target != -1:\n vote = self.target\n else: # Vote a random living agents\n vote = random.sample([a.agent_id for a in agents if not a.agent_id == self.agent_id and a.alive and not a.is_im...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The impostor chooses a target to vote off. It chooses the crewmate that suspects the least number of people, e.g. the one that is most onto the impostors.
def choose_target(self, agents): number_of_suspects = [0]*(len(agents)) number_of_suspects_per_agent = [] index = 0 for a1 in agents: if not a1.is_impostor(): for a2 in agents: if self.km.suspects(a1.agent_id, a2.agent_id): ...
[ "def vote(self, agents):\n\n # If the impostors have a set target, vote that\n if self.target != -1:\n vote = self.target\n else: # Vote a random living agents\n vote = random.sample([a.agent_id for a in agents if not a.agent_id == self.agent_id and a.alive and not a.is_im...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The impostor votes the agents that are closest to finding them. If there is no such agent, vote for a random living agent that is not an impostor.
def vote(self, agents): # If the impostors have a set target, vote that if self.target != -1: vote = self.target else: # Vote a random living agents vote = random.sample([a.agent_id for a in agents if not a.agent_id == self.agent_id and a.alive and not a.is_impostor()], ...
[ "def vote(self, agents):\n\n suspects = []\n known_impostor = -1\n # Check which agents the current agent still suspects\n for a in agents:\n if self.km.knows_imp(self.agent_id, a.agent_id):\n known_impostor = a.agent_id\n self.logger.log(f\"Crewm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
String representation of the BoutDataset. Accessed by print(ds.bout)
def __str__(self): styled = partial(prettyformat, indent=4, compact=True) text = ( "<xbout.BoutDataset>\n" + "Contains:\n{}\n".format(str(self.data)) + "Metadata:\n{}\n".format(styled(self.metadata)) ) if self.options: text += "Options:\n{...
[ "def __str__(self):\n\n styled = partial(prettyformat, indent=4, compact=True)\n text = \"<xbout.BoutDataset>\\n\" + \\\n \"Contains:\\n{}\\n\".format(str(self.data)) + \\\n \"Metadata:\\n{}\\n\".format(styled(self.metadata))\n if self.options:\n text += \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a fieldaligned version of a variable, calculating (and caching in the Dataset) if necessary
def get_field_aligned(self, name, caching=True): aligned_name = name + "_aligned" try: result = self.data[aligned_name] if result.direction_y != "Aligned": raise ValueError( aligned_name + " exists, but is not field-aligned, it " ...
[ "def getFieldAligned(self, name, caching=True):\n aligned_name = name + '_aligned'\n try:\n result = self.data[aligned_name]\n if result.direction_y != 'Aligned':\n raise ValueError(aligned_name + \" exists, but is not field-aligned, it \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Integrate using the midpoint rule for spatial dimensions, and trapezium rule for time. The quantity being integrated is assumed to be a scalar variable. When doing a 1d integral in the 'y' dimension, the integral is calculated as a poloidal integral if the variable is on the standard grid (``direction_y`` attribute is ...
def integrate_midpoints(self, variable, *, dims=None, cumulative_t=False): ds = self.data if isinstance(variable, str): variable = ds[variable] location = variable.cell_location suffix = "" if location == "CELL_CENTRE" else f"_{location}" tcoord = ds.metadata["bout...
[ "def integrate(x, y, xmin, xmax):\n indexes = get_interval(x, xmin, xmax)\n integral = np.trapz(y[indexes], x[indexes])\n\n return integral", "def integrate_between(t, y, t1, t2):\n mask = ((t >= t1) & (t <= t2))\n y_integrated = np.trapz(y[mask], x=t[mask])/(t2-t1)\n return y_integr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interpolate the Dataset to a regular Cartesian grid. This method is intended to be used to produce data for visualisation, which normally does not require doubleprecision values, so by default the data is converted to `numpy.float32`. Pass ``use_float32=False`` to retain the original precision.
def interpolate_to_cartesian( self, nX=300, nY=300, nZ=100, *, use_float32=True, fill_value=np.nan ): ds = self.data ds = ds.bout.add_cartesian_coordinates() if not isinstance(use_float32, bool): raise ValueError(f"use_float32 must be a bool, got '{use_float32}'") ...
[ "def convert_to_same_grid(reference_ds, ds, method=\"nearest_s2d\"):\n assert (\"lat\" in reference_ds.dims) & (\n \"lon\" in reference_ds.dims\n ), f\"Need (lat,lon) in reference_ds dims Currently: {reference_ds.dims}\"\n assert (\"lat\" in ds.dims) & (\n \"lon\" in ds.dims\n ), f\"Need (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add Cartesian (X,Y,Z) coordinates. Returns Dataset with new coordinates added, which are named 'X_cartesian', 'Y_cartesian', and 'Z_cartesian'
def add_cartesian_coordinates(self): return _add_cartesian_coordinates(self.data)
[ "def to_cartesian(self):\n\n if self.cartesian is None:\n theta = math.radians(self.lat)\n phi = math.radians(self.long)\n x = R_EARTH * math.cos(theta) * math.cos(phi)\n y = R_EARTH * math.cos(theta) * math.sin(phi)\n z = R_EARTH * math.sin(theta)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove yboundary points, if present, from the Dataset
def remove_yboundaries(self, **kwargs): variables = [] xcoord = self.data.metadata["bout_xdim"] ycoord = self.data.metadata["bout_ydim"] new_metadata = None for v in self.data: if xcoord in self.data[v].dims and ycoord in self.data[v].dims: variables....
[ "def remove_none_from_arrays(self):\r\n\r\n is_nan = numpy.isnan(self.y_values) # array of booleans, element is True if the corresponding element in\r\n # self.y_values is None\r\n\r\n self.x_values = self.x_values[numpy.logical_not(is_nan)]\r\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get bounding surfaces. Surfaces are returned as arrays of points describing a polygon, assuming the third spatial dimension is a symmetry direction.
def get_bounding_surfaces(self, coords=("R", "Z")): return _get_bounding_surfaces(self.data, coords)
[ "def _get_surfaces(idf):\n surfaces = idf.getsurfaces() + idf.getshadingsurfaces() + idf.getsubsurfaces()\n return surfaces", "def surfaces(self):\n return self._surfaces", "def surfaces(self):\n surfaces = []\n for i in range(1000):\n surface = self.surfaceInfo(i)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save data variables to a netCDF file.
def save( self, savepath="./boutdata.nc", filetype="NETCDF4", variables=None, save_dtype=None, separate_vars=False, pre_load=False, ): if variables is None: # Save all variables to_save = self.data else: to_...
[ "def save_nc(filename, *args):\n\n ds = xr.vars_to_dataset(*args)\n ds.to_netcdf(filename)\n return None", "def save2nc(file_name,**var):\n if file_name[-3:] != '.nc':\n file_name += '.nc'\n f = DataFile(file_name, write=True, create=True)\n for v in var:\n try:\n varg = var[v]\n f.wri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write out a timestep as a set of netCDF BOUT.restart files. If processor decomposition is not specified then data will be saved using the decomposition it had when loaded.
def to_restart( self, variables=None, *, savepath=".", nxpe=None, nype=None, tind=-1, prefix="BOUT.restart", overwrite=False, ): if isinstance(variables, str): variables = [variables] # Set processor decomposition ...
[ "def write_restart(self):\n\n x = self.state.to_dataframe(self.mask).to_xarray()\n filename = Path(f'{self.config.get(\"simulation.output_path\")}/{self.name}/restart_files/{self.name}_restart_{self.current_time.year}_{self.current_time.strftime(\"%m\")}_{self.current_time.strftime(\"%d\")}.nc')\n x = x.ri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct wowdburl for given filter settings.
def construct_wowdb_url(itype, slot, expansion, source): #url = f"https://www.wowdb.com/items/{itype}?filter-bind={bind}&filter-expansion={xpac_filt}&filter-slot={slot_filt}&filter-source={sour_filt}" url = f'https://www.wowhead.com/{itype}' if itype == "armor" or itype == "weapons": url += f'/slot:...
[ "def create_query_url(self):\n self.__log('Starting to create the query URL.')\n query_url = self.config['API_URI']\n for key, value in self.options.items():\n if value:\n if query_url == self.config['API_URI']:\n query_url = query_url + str(key) + \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the forecasted streamflow as CSV
def get_forecast_streamflow_csv(params): try: # retrieve statistics forecast_statistics, watershed_name, subbasin_name, river_id, units = \ get_ecmwf_forecast_statistics(params) # prepare to write response for CSV si = StringIO() writer = csv_writer(si) ...
[ "def get_output_as_csv(dataset, engines, db):\n wt.reload_scripts()\n eng = wt.join_postgres(\n dataset,\n database=testdb,\n database_name=testschema,\n host=pgdb_host,\n password=os_password,\n )\n # Wait for 5 seconds\n time.sleep(5)\n csv_file = eng.to_csv()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves n disks from A to C.
def do_hanoi(A, B, C, n): # TODO: IMPLEMENT THIS FUNCTION. if n == 1: # TODO: 1. Initial case - only one disk will be moved from A to C. pass else: # TODO: 2. General case - All disks must be moved from A to C. pass
[ "def move_disks(self, n, dest_tower, aux_tower):\n if n > 0:\n self.move_disks(n - 1, aux_tower, dest_tower)\n self.move_top_to(dest_tower)\n aux_tower.move_disks(n - 1, dest_tower, self)", "def towers_of_hanoi(n):\n a = list(range(n, 0, -1))\n b = []\n c = []\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw cross at p
def draw_point(self, p): length = 3 self.set_line_width(0.1) self.set_source_rgba(0, 0, 1, 1) self.move_to(p.x + length, p.y) self.line_to(p.x - length, p.y) self.stroke() self.move_to(p.x, p.y + length) self.line_to(p.x, p.y - length) self.stroke(...
[ "def drawcross():\n medic.fillcolor(255,0,0)\n medic.penup()\n medic.right(90)\n medic.forward(80)\n medic.right(90)\n medic.pendown()\n medic.begin_fill()\n for i in range(2):\n medic.forward(15) #This line of code makes a cross!\n medic.right(90)\n medic.forward(25)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw line between p and q... later
def draw_line(self, p, q, line_width=0.8, line_cap=cairo.LINE_CAP_ROUND, procrastinate=1000): if procrastinate == 0: self.set_line_width(line_width) self.set_line_cap(line_cap) self.move...
[ "def draw_point(self, p):\n length = 3\n self.set_line_width(0.1)\n self.set_source_rgba(0, 0, 1, 1)\n self.move_to(p.x + length, p.y)\n self.line_to(p.x - length, p.y)\n self.stroke()\n self.move_to(p.x, p.y + length)\n self.line_to(p.x, p.y - length)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw a cube and some adjacent lines. (Lines which cannot be drawn without knowledge of edges.)
def draw_cube(self, middle, edges, coloring=None, explain=False): # edges = set(e - 2 for e in edges) top = middle - Point(0, self.edge) # No comment would help you. Draw it (with explain=True). if explain: self.set_source_rgb(1, 0, 0) for i in [0, 2, 4]: ...
[ "def drawcube_old():\n allpoints = list(zip(CUBE_POINTS, CUBE_COLORS))\n\n GL.glBegin(GL.GL_QUADS)\n for face in CUBE_QUAD_VERTS:\n for vert in face:\n pos, color = allpoints[vert]\n GL.glColor3fv(color)\n GL.glVertex3fv(pos)\n GL.glEnd()\n\n GL.glColor3f(1.0, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all registered stores with postal_code relation
def get(self): return StoreModel.with_postal_code().all()
[ "def find_zip_codes(self, zip_code):\n zip_code = str(zip_code).strip()\n cursor = self.households.find({\"addresses.zip_code\":zip_code})\n results = [Household.from_dict(dct) for dct in cursor]\n\n cursor = self.businesses.find({\"address.zip_code\":zip_code})\n results += [Busi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a store given its identifier
def get(self, store_id): store = StoreModel.query.filter_by(id=store_id).first() if not store: store_api.abort(404, "Store {} doesn't exist".format(store_id)) else: return store
[ "def get_store(store_name: str):\n return store_handler.get_store(store_name)", "def get_store_by_id_service(store_id):\n if not store_id.isdigit():\n return None\n return store_dao.get_store_by_id_dao(store_id, is_dict_result=True)", "def get_store(self, store_name):\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a store given its identifier
def delete(self, store_id): store = StoreModel.query.filter_by(id=store_id).first() if not store: store_api.abort(404, "Store {} not found".format(store_id)) store.delete() return '', 204
[ "def delete_store(self, store_path):\n raise NotImplementedError(\"Should have implemented this\")", "def delete_store(request, store_name):\n # Search for store: if doesn't exist, return different message\n\n storedb = redis.Redis(host=HOST, db=STOREDB)\n\n if store_name not in get_store(request)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Associate product to the given store with the intermediate table 'stocks'
def post(self, store_id): store = StoreModel.query.filter_by(id=store_id).first() if not store: store_api.abort(404, "Store {} not found".format(store_id)) data = request.json product = ProductModel.query.filter_by(id=data['product_id']).first() if not product: ...
[ "def add_store(self, product, store):\n self.db.query(\"\"\"\n INSERT IGNORE INTO product_store(product_id, store_id)\n VALUES (:product_id, :store_id)\n \"\"\", product_id=product.id, store_id=store.id)", "def add_product(self, store, product):\n self.db.query(\"\"\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiate a dictionary of child nodes of actions as keys.
def create_child(self, actions, probs): games = [copy(self.game) for a in actions] for action, game in zip(actions, games): game.move(action) self.child = {tuple(a): Node(g, self, p) for a, g, p in zip(actions, games, probs)}
[ "def action_map(self) -> Dict[str, CLIActionType]:\n return add_dicts({\n \"dump\": self.dump_action,\n \"dump-macrosizes\": self.dump_macrosizes_action,\n \"dump_macrosizes\": self.dump_macrosizes_action,\n \"synthesis\": self.synthesis_action,\n \"syn\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
OverSampling dataset augmentation The main function will augment the given dataset with synthetic instances associated to the less representative target class, through a variant of SMOTE that allows categorical features
def augment_dataset( data: pd.DataFrame, categorical_features: list, target_feature: str = 'target', k_parameter: int = 3 ) -> pd.DataFrame: categorical_mask = [True if feature in categorical_features else False for feature in data.columns] smote_obj = SMOTENC( categori...
[ "def augment_dataset(ds, sp, device, random_state):\n dsx, dsy = ds.tensors[0].cpu().numpy(), ds.tensors[1].cpu().numpy()\n classes, n_per_class = np.unique(dsy, return_counts=True)\n if sp.classifier_type == 'ordinal':\n if 'ordinal_augment_beta_params' in sp:\n bp = sp.ordinal_augment_b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Poll the state of the desired object or function. If it has satisfied the conditions then set self.met = True
def poll(self): self.met = self.button.poll()
[ "def update_waiting(self):\n if self.variant(map(lambda x: x is not None, self.get_value(0, True))):\n values = list(filter(lambda x: x is not None, self.get_value(0, True)))\n if self.name == \"and\":\n self.set_value(all(values), 0)\n elif self.name == \"or\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract the cell and previous output tensors from the given state.
def _extract_states(self, state): conf = self._config # c_prev is `m` (cell value), and # m_prev is `h` (previous output) in the paper. # Keeping c and m here for consistency with the codebase c_prev = [None] * conf.num_dims m_prev = [None] * conf.num_dims # for LSTM : state = memory cel...
[ "def _get_final_state(cell, state):\n # If the cell is LSTMCell, then `state` is an `LSTMStateTuple`\n # and we want the second (output) Tensor -- see\n # https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/LSTMStateTuple\n #\n if isinstance(cell, tf.nn.rnn_cell.LSTMCell):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fills in c_prev and m_prev with projected input, for input dimensions.
def _project_input(self, inputs, c_prev, m_prev, with_c): conf = self._config if (inputs is not None and inputs.get_shape().with_rank(2)[1].value > 0 and conf.inputs): if isinstance(inputs, tuple): if len(conf.inputs) != len(inputs): raise ValueError('Expect inputs as a tuple of...
[ "def _advance_iteration_variables(self):\n Algorithm._advance_iteration_variables(self)\n for m in range(self.M):\n self.cur[m].traj_info.last_kl_step = \\\n self.prev[m].traj_info.last_kl_step\n self.cur[m].pol_info = copy.deepcopy(self.prev[m].pol_info)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Total size of the state of the inner cell used in this grid.
def _cell_state_size(self): state_sizes = self._cells[0].state_size if isinstance(state_sizes, tuple): return sum(state_sizes) return state_sizes
[ "def state_size(self):\n return self.cell.state_size", "def cell_size(self):\r\n\r\n return self.__cell_size", "def cells_total(self):\n return self._inv.get(\"cells\", len(self))", "def size(self):\n bbox = self.bbox\n return bbox[1] - bbox[0]", "def size(self):\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Propagates through all the cells in dim_indices dimensions.
def _propagate(dim_indices, conf, cells, c_prev, m_prev, new_output, new_state, first_call): if len(dim_indices) == 0: return # Because of the way RNNCells are implemented, we take the last dimension # (H_{N-1}) out and feed it as the state of the RNN cell # (in `last_dim_output`). # The i...
[ "def _propagate(self, indices):\n for d in reversed(range(self.depth)):\n indices = set([i // 2 for i in indices])\n for index in indices:\n self.tree[d][index] = (\n self.tree[d + 1][2 * index] + self.tree[d + 1][2 * index + 1]\n )", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
open log system by the specified outputs
def open( self, stdout = True, outputs = { "fulltrace": logging.INFO, "error": logging.ERROR, } ): # create logger self.__logger = logging.getLogger("log-{0}".format(self.case)) self.__logger.setLevel(logging.INFO) # create st...
[ "def logtool(ctx):", "def openLogfileConnection(self,):\n \n #\n # Imports\n #\n import sys\n import time\n import os\n \n #\n # for logmessages\n # \n tmpLogMessages = []\n \n #\n # check if logfile pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
close log system, flush all messages to log file, and clear message counters
def close(self): if not self.__closed: self.counters = { "error": 0, "warning": 0, "success": 0, "failure": 0 } try: self.__flush_count = 0 for handler in self.__filehandlers: handler.flush() self.__logger.removeHan...
[ "def cleanup_logs(self):\n\n _now = time.time()\n\n for _id in self.open_logs.keys():\n try:\n if _now > (self.open_logs[_id]['last_time'] + self.FILE_ACTIVITY_TIMEOUT):\n # Flush and close the log file, and pop this element from the dictionary.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Go to gmail, with account number arg
def gmail(arg): if not arg: return GOOGLE_MAIL search_content = arg account_num = '0' ret_url = GOOGLE_MAIL + account_num + (('/#search/' + search_content) if search_content else '') print('returning url {}'.format(ret_url)) return ret_url
[ "def sender(self, account, password):\n self.gmail_sender = account \n self.gmail_password = password", "def _login_account_kit(mail):\n # retrieve message link\n urls = re.findall(r'https?://[^\\s<>\"]+|www\\.[^\\s<>\"]+', mail[\"content\"])\n\n url = \"\"\n if urls:\n url = html.unescap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check inventory for `parameters.component_versions`. Raise an error if the parameter has any contents.
def check_parameters_component_versions(cluster_parameters): cvers = cluster_parameters.get("component_versions", {}) if len(cvers.keys()) > 0: raise click.ClickException( "Specifying component versions in parameter `component_versions` " + "is no longer suppported. Please migrat...
[ "def _check_version(self, parameters):\n v = parameters['Version']\n if version_tuple(v) != version_tuple(self.compatible_version):\n msg = \"Version supported by %s is %s, while parameter set version is %s!\"\n raise exc.PCSEError(msg % (self.__class__.__name__, self.compatible_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert time to localized time
def toLocalizedTime(self, time, long_format=None, time_only = None): util = getToolByName(self.context, 'translation_service') try: return util.ulocalized_time(time, long_format, time_only, self.context, domain='plonelocales') except TypeError:...
[ "def toLocalizedTime(self, time, long_format=None, time_only=None):\n util = getToolByName(self.context, 'translation_service')\n return util.ulocalized_time(time,\n long_format,\n time_only,\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dynamically collect class inherited from Quiz.
def _collect_quizzes(): data_path = join(dirname(abspath(__file__)), 'data') for _, _, filenames in os.walk(data_path): for filename in filenames: if filename.endswith('.yml'): quiz_type = filename.replace('.yml', '').capitalize() QUIZ_DICT[quiz_type] = [] ...
[ "def derived_classes(self, what: Union[GDScriptClass, str, int]):\n base_cls: Optional[GDScriptClass] = None\n if isinstance(what, GDScriptClass):\n base_cls = what\n else:\n base_cls = self.get_class(what)\n\n for cls in self._classes_by_type_id.values():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the DataGrid. Iterates over all rows and columns, preparing cell structures. Cells then contain a graph and data queries to leaf processors. Upon providing data to a leaf, the leaf processor is calculated and propagated up the graph to the cell level.
def initialize(self) -> None: all_queries: List[Union[DataQueryInfo, MeasureQueryInfo]] = [] entity_cells: List[DataCell] = [] current_row_group = None # Loop over rows, columns for row_index, row in enumerate(self.rows): if isinstance(row, RowSeparator): ...
[ "def initialiseGrid(self):\n # Iterate over rows in grid\n for i in range(self.gridSize):\n # Append array for each row\n self.grid.append([])\n # Iterate over columns in grid\n for j in range(self.gridSize):\n # Initialise cell\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Poll the data queries required to process this grid. Set the results at the leaf processors
def poll(self) -> None: self._resolve_rdates() self._resolve_queries() self._process_special_cells() self._fetch_queries()
[ "def run(self):\r\n self.collect_data()", "def fetch_data():\n data.fetch_data()\n data.start_updating()", "def fetch_results(self):\n self._get_flat_results()", "def initialize(self) -> None:\n all_queries: List[Union[DataQueryInfo, MeasureQueryInfo]] = []\n entity_cells: Li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the DataGrid. If the DataGrid has already been created, the DataGrid will be updated. If the DataGrid has not been created it will be added to the DataGrid service.
def save(self) -> str: datagrid_json = self.__as_json() if self.id_: response = GsSession.current._put(f'{API}/{self.id_}', datagrid_json, request_headers=DATAGRID_HEADERS) else: response = GsSession.current._post(f'{API}', datagrid_json, request_headers=DATAGRID_HEADERS)...
[ "def delete(self):\n if self.id_:\n GsSession.current._delete(f'{API}/{self.id_}', request_headers=DATAGRID_HEADERS)\n else:\n raise MqValueError('DataGrid has not been persisted.')", "def save_data(self):\n db.session.add(self)\n db.session.commit( )", "def cre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new DataGrid even if the DataGrid already exists. If the DataGrid has already been persisted, the DataGrid id will be replaced with the newly persisted DataGrid.
def create(self): datagrid_json = self.__as_json() response = GsSession.current._post(f'{API}', datagrid_json, request_headers=DATAGRID_HEADERS) self.id_ = response['id'] return response['id']
[ "def save(self) -> str:\n datagrid_json = self.__as_json()\n if self.id_:\n response = GsSession.current._put(f'{API}/{self.id_}', datagrid_json, request_headers=DATAGRID_HEADERS)\n else:\n response = GsSession.current._post(f'{API}', datagrid_json, request_headers=DATAGRI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes the DataGrid if it has been persisted.
def delete(self): if self.id_: GsSession.current._delete(f'{API}/{self.id_}', request_headers=DATAGRID_HEADERS) else: raise MqValueError('DataGrid has not been persisted.')
[ "def delete(self):\n\t\tself.table.delete()", "def delete_grid(self):\n\n\t\tself.a_grid = None\t\t# Deletes the object from memory", "def delete(self):\n self._host.mor.configManager.datastoreSystem.RemoveDatastore(datastore=self.mor)\n pass", "def delete_data_set(self):\r\n db.session.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens the DataGrid in the default browser.
def open(self): if self.id_ is None: raise MqValueError('DataGrid must be created or saved before opening.') domain = GsSession.current.domain.replace(".web", "") if domain == 'https://api.gs.com': domain = 'https://marquee.gs.com' url = f'{domain}/s/markets/grids...
[ "def open_browser():\n webbrowser.open_new('http://127.0.0.1:8080/')", "def open_browser():\n\n webbrowser.open_new('http://127.0.0.1:8080/')", "def open_in_browser(self):\n webbrowser.open(self.ui_url(), new = 2)", "def open(self):\n webbrowser.open(self._aqhttp.url)", "def web_view(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes Coordinate and Entity cells
def _process_special_cells(self) -> None: # fetch entity cells for cell in self._entity_cells: try: cell.value = cell.processor.process(cell.entity) except Exception as e: cell.value = f'Error Calculating processor {cell.processor.__class__.__name_...
[ "def _process_unknown_entity(self, entity):\n is_complex_agent = False\n complex_agent_x, complex_agent_y = None, None\n if len(entity.get(\"children\")) > 1: # entities separeted by .\n is_complex_agent = True\n complex_agent_x, complex_agent_y = self._current_x, self._c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles filtering the dataframe
def __handle_filters(self, df) -> DataFrame: if not len(df): return df starting_df = df.copy() running_df = df for filter_ in self.filters: filter_value = filter_.value if filter_value is None: continue filter_condition = fi...
[ "def filter_data(self):\n self.data = filter_pandas(self.data, self.filters)", "def _apply_filters(self, df):\n df = df[(df['Date'] >= self.start_date) &\n (df['Date'] <= self.end_date)]\n return df", "def _data_filtering(self):\n self._filter_nan_user_or_item()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the primary column index which affects which row will expand to fill any additional horizontal space.
def set_primary_column_index(self, index: int): self._primary_column_index = index
[ "def SetMainColumn(self, column):\r\n \r\n if column >= 0 and column < self.GetColumnCount():\r\n self._main_column = column", "def set_column_width(self, index, width):\n self.colwid[index] = width", "def setFirstColumnSpanned(self, p_int, QModelIndex, bool): # real signature un...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize the parent class and the face_mesh model.
def __init__(self): am.AbstractMeasurement.__init__(self) self.face_mesh = mp_face_mesh.FaceMesh( min_detection_confidence=0.5, min_tracking_confidence=0.5) self.drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)
[ "def __init__(self):\n _eltrans.FaceElementTransformations_swiginit(self, _eltrans.new_FaceElementTransformations())", "def __init__(self, parentClass):\n\n\t\tself.camera = None\n\t\tself.cascade = None\n\n\t\tself.image = None\n\t\tself.grayframe = None\n\t\tself.frameWidth = 0\n\t\tself.frameHeight = 0\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run the face detector algorithm on the given frame
def run(self, frame, dict_results): run_result = {repr(self): False} try: # flip the image in order to represent a true self of the person not mirror of it # and convert its colors. image = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB) # make it read...
[ "def face_detection(vcap,next_frame,fd): # parse faces from an image\n global INFO\n global STATE\n global args\n faces,det_time_fd = [],0\n # Get intial width and height of video stream\n initial_wh = [vcap.get(3), vcap.get(4)]\n in_frame_fd = cv2.resize(next_frame, (fd['w'], fd['h']))\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draw face annotations on the image.
def draw_annotations(self, image, results): image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) for face_landmarks in results.multi_face_landmarks: # draw face landmark net mp_drawing.draw_landmarks( image=image, lan...
[ "def decorate(self, im):\n\n color = (232, 118, 0)\n red = (0xD0, 0x20, 0x00)#D20\n draw = ImageDraw.Draw(im)\n\n # draw a box around the face\n box = self.matrices['rotation'].dot(self.matrices['bbox']).getT() + self.matrices['center']\n draw.polygon(map(int, box.getA1()))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test the faceDetector measurement by static labeled images and print the test results.
def test_measurement_on_images(file_list): test_details_list = [] for idx, file in enumerate(file_list): dict_results = {} image = cv2.imread(file) FaceDetector().run(image, dict_results) file_name = ntpath.basename(file) is_there_face = "True" in file_name test_d...
[ "def test_detection_on_image(self, image_path):\n image = TLClassifier.load_image(image_path)\n result = self.infer_image(image)\n TLClassifier.display_image(result)", "def testModel(self):\n\n self.testImages, self.testImageCount = self.getFiles(self.test_path)\n\n predictions ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return raw labels and training data(numpy)
def get_raw_data(): with open('train_label.pkl', 'rb') as f: train_label = pickle.load(f) with open('train_image.pkl', 'rb') as f: train_data = pickle.load(f) print(np.unique(np.asarray(train_label))) return (train_label, np.asarray(train_data))
[ "def make_raw_data(self):\n\t\tfilter = self.predictions.max(1) > self.confidence\n\t\tdata = self.test_data[filter, :]\n\t\tlabels = self.predictions[filter, :].argmax(1).astype(uint16) + 1\n\t\treturn data, labels", "def labels_array(self):\n return _build_label_vector_rows(\n [[(label, 1)] fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get minimum cycle counter in AI CPU.
def min_cycle_counter(self): return self._min_cycle_counter
[ "def GetCycleTimeMin(self):\n callResult = self._Call(\"GetCycleTimeMin\", )\n\n if callResult is None:\n return None\n\n return callResult", "def _get_cpu_util_1min(self):\n return self.__cpu_util_1min", "def cpu(self) -> int:\n return pulumi.get(self, \"cpu\")", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To be used in constant folding. If this expression is folded as part of a declaration/assignment, returns the type of the variable. Otherwise, returns the 'default' expression type.
def result_type(self): anc = self.find_ancestor(ASTDeclarationNode) or self.find_ancestor(ASTAssignmentNode) if anc: return anc.type() return get_expression_type(self)
[ "def _infer_type(var, code_chunk, context):\n\n # Get all the assignments in the code chunk.\n visitor = let_statement_visitor(var)\n code_chunk.accept(visitor)\n\n # Look at each assignment statement and check out the ones where the current\n # variable is assigned.\n str_funcs = [\"cstr(\", \"ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the branching ratio for the generalised decay constant. This ratio must be multiplied by 1/tau to get the generalised decay constant in Grad/s. This is then used for evaluating vertical coherences.
def generalisedDecayConstant(ep, epp, g, G, Q_decay): # Calculate the total branching from the excited state to all ground states sum_decay_channels_epg = 0 sum_decay_channels_eppg = 0 for gp in G: for q in Q_decay: sum_decay_channels_epg += abs(coupling(ep, gp, q)*coupling(ep, gp, q...
[ "def adv_ratio(self): # XXX\r\n bw = StatsRouter.global_bw_mean\r\n if bw == 0.0: return 0\r\n else: return self.bw/bw", "def golden_ratio():\n\n return ratio(1)", "def golden_ratio():\n return 1.61803398875", "def golden_ratio():\n\n print((1 + math.sqrt(5)) / 2)", "def golden_ratio():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false. >>> canMakeArithmeticProgression([3,5,1]) True >>> canMakeAri...
def canMakeArithmeticProgression(arr): new_arr = sorted(arr) diff = new_arr[1] - new_arr[0] for idx, num in enumerate(new_arr): if idx == 0: pass elif num - new_arr[idx - 1] != diff: return False return True
[ "def Progression(arr):\n\n # Check if array is with at least 3 elements\n if len(arr) < 3: return 0\n\n # Calculate difference between numbers in list\n diffAr = arr[1] - arr[0]\n diffGeo = arr[1] / arr[0]\n\n # Temp vars to check if list is in progression\n isA = True\n isG = True\n\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a parity plot Input
def parity_plot(y_pred, y_act): fig = plt.figure(figsize=FIG_SIZE) plt.scatter(y_act, y_pred) plt.plot([y_act.min(), y_act.max()], [y_act.min(), y_act.max()], lw=4, color='r') plt.xlabel('Actual') plt.ylabel('Predicted') return fig
[ "def plot_parity(x, y, **kwargs):\n plot_params = {\n \"alpha\": 0.7,\n \"s\": 100,\n \"plot_color\": \"green\",\n }\n if kwargs is not None:\n plot_params.update(kwargs)\n plt.figure()\n plt.rcParams[\"svg.fonttype\"] = \"none\"\n plt.scatter(\n x=x,\n y=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a plot of training vs. test error Input
def train_test_error(e_train, e_test, model_params): fig = plt.figure(figsize=FIG_SIZE) plt.plot(model_params, e_train, label='Training Set') plt.plot(model_params, e_train, label='Test Set') plt.xlabel('Model Parameter') plt.ylabel('MSE of model') plt.legend() return fig
[ "def plot_train_test_errors(train_errors, test_errors, lambda_str , K , path, rng):\n plt.plot(range(rng), train_errors, marker='o', label='Training Data');\n plt.plot(range(rng), test_errors, marker='v', label='Test Data');\n plt.title('ALS-WR Learning Curve, lambda = %s, K = %d'%(lambda_str, K))\n plt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that the sender ID is valid, based on the email's intent. Many emails are only allowed to be sent by a certain user or type of user, e.g. 'admin' or an admin/moderator. This function will raise an exception if the given sender is not allowed to send this type of email.
def _require_sender_id_is_valid(intent, sender_id): if intent not in SENDER_VALIDATORS: raise Exception('Invalid email intent string: %s' % intent) else: if not SENDER_VALIDATORS[intent](sender_id): logging.error( 'Invalid sender_id %s for email with intent \'%s\'' %...
[ "def __set_sender_id(self, sender_id):\n if not isinstance(sender_id, int):\n raise TypeError('It has to be an integer identifier')\n if sender_id < 0:\n raise ValueError('There are not negative identifiers')\n self.__sender_id = sender_id", "def valid_smtp_sender(self):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends an email to the given recipient. This function should be used for sending all userfacing emails. Raises an Exception if the sender_id is not appropriate for the given intent. Currently we support only systemgenerated emails and emails initiated by moderator actions.
def _send_email( recipient_id, sender_id, intent, email_subject, email_html_body, sender_email, bcc_admin=False, sender_name=None, reply_to_id=None): if sender_name is None: sender_name = EMAIL_SENDER_NAME.value _require_sender_id_is_valid(intent, sender_id) recipient_email = user...
[ "def send_moderator_action_email(\n sender_id, recipient_id, intent, exploration_title, email_body):\n\n require_moderator_email_prereqs_are_satisfied()\n email_config = feconf.VALID_MODERATOR_ACTIONS[intent]\n\n recipient_user_settings = user_services.get_user_settings(recipient_id)\n sender_use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send an email to the admin email address. The email is sent to the ADMIN_EMAIL_ADDRESS set in feconf.py.
def send_mail_to_admin(email_subject, email_body): app_id = app_identity_services.get_application_id() body = '(Sent from %s)\n\n%s' % (app_id, email_body) system_name_email = '%s <%s>' % ( feconf.SYSTEM_EMAIL_NAME, feconf.SYSTEM_EMAIL_ADDRESS) email_services.send_mail( system_name_emai...
[ "def send_mail_to_admins(sender,\n subject,\n body,\n make_sync_call=apiproxy_stub_map.MakeSyncCall,\n **kw):\n kw['sender'] = sender\n kw['subject'] = subject\n kw['body'] = body\n message = AdminEmailMessage(**kw)\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a postsignup email to the given user. Raises an exception if emails are not allowed to be sent to users (i.e. feconf.CAN_SEND_EMAILS is False).
def send_post_signup_email(user_id): for key, content in SIGNUP_EMAIL_CONTENT.value.iteritems(): if content == SIGNUP_EMAIL_CONTENT.default_value[key]: log_new_error( 'Please ensure that the value for the admin config property ' 'SIGNUP_EMAIL_CONTENT is set, befo...
[ "async def send_user_signup_mail(email):\n html_template = load_email_html(USER_SIGNUP_TEMPLATE)\n html = html_template.render()\n\n message = create_email_message(email, USER_SIGNUP_SUBJECT, html)\n\n await send_mail(message)", "def send_signup_email(user, template):\n # message = render_to_string...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a draft of the text of the body for an email sent immediately when a moderator unpublishes an exploration. An empty body is a signal to the frontend that no email will be sent.
def get_moderator_unpublish_exploration_email(): try: require_moderator_email_prereqs_are_satisfied() return config_domain.Registry.get_config_property( 'unpublish_exploration_email_html_body').value except Exception: return ''
[ "def get_clear_text_body(self):\n parser = self.get_parser()\n if parser is not None:\n return parser.get_clear_text_body()\n\n return u''", "def draft_message(request):\n query = models.Message.query(\n models.Message.sender == request.user.email(),\n models.Message.dra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raises an exception if, for any reason, moderator emails cannot be sent.
def require_moderator_email_prereqs_are_satisfied(): if not feconf.REQUIRE_EMAIL_ON_MODERATOR_ACTION: raise Exception( 'For moderator emails to be sent, please ensure that ' 'REQUIRE_EMAIL_ON_MODERATOR_ACTION is set to True.') if not feconf.CAN_SEND_EMAILS: raise Excepti...
[ "def send_moderator_action_email(\n sender_id, recipient_id, intent, exploration_title, email_body):\n\n require_moderator_email_prereqs_are_satisfied()\n email_config = feconf.VALID_MODERATOR_ACTIONS[intent]\n\n recipient_user_settings = user_services.get_user_settings(recipient_id)\n sender_use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a email immediately following a moderator action (unpublish, delete) to the given user. Raises an exception if emails are not allowed to be sent to users (i.e. feconf.CAN_SEND_EMAILS is False).
def send_moderator_action_email( sender_id, recipient_id, intent, exploration_title, email_body): require_moderator_email_prereqs_are_satisfied() email_config = feconf.VALID_MODERATOR_ACTIONS[intent] recipient_user_settings = user_services.get_user_settings(recipient_id) sender_user_settings =...
[ "def notify_user(obj, event):\n\n # Check if user notification is enabled\n registry = queryUtility(IRegistry)\n settings = registry.forInterface(IDiscussionSettings, check=False)\n if not settings.user_notification_enabled:\n #return\n pass\n\n # Get informations that are necessary to ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a email when a new user is given activity rights (Manager, Editor, Viewer) to an exploration by creator of exploration. Email will only be sent if recipient wants to receive these emails (i.e. 'can_receive_editor_role_email' is set True in recipent's preferences).
def send_role_notification_email( inviter_id, recipient_id, recipient_role, exploration_id, exploration_title): # Editor role email body and email subject templates. email_subject_template = ( '%s - invitation to collaborate') email_body_template = ( 'Hi %s,<br>' '<...
[ "def send_moderator_action_email(\n sender_id, recipient_id, intent, exploration_title, email_body):\n\n require_moderator_email_prereqs_are_satisfied()\n email_config = feconf.VALID_MODERATOR_ACTIONS[intent]\n\n recipient_user_settings = user_services.get_user_settings(recipient_id)\n sender_use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends an email to all the subscribers of the creators when the creator publishes an exploration.
def send_emails_to_subscribers(creator_id, exploration_id, exploration_title): creator_name = user_services.get_username(creator_id) email_subject = ('%s has published a new exploration!' % creator_name) email_body_template = ( 'Hi %s,<br>' '<br>' '%s has published a new exploration...
[ "def send_publishers_authors_email(subject, template_name, context=None):\n\n if context is None:\n context = {}\n\n qry = Q(groups__name='Publishers') | Q(groups__name='Editors')\n\n emails = auth_models.User.objects.filter(qry, is_active=True).distinct().values('email')\n to = [e['email'] for e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send emails to notify the given recipients about new suggestion. Each recipient will only be emailed if their email preferences allow for incoming feedback message emails.
def send_suggestion_email( exploration_title, exploration_id, author_id, recipient_list): email_subject = 'New suggestion for "%s"' % exploration_title email_body_template = ( 'Hi %s,<br>' '%s has submitted a new suggestion for your Oppia exploration, ' '<a href="https://www.op...
[ "def send_mails(self):\n for recepient in self.recipients:\n self.send_mail(recepient)", "def sendBonusEmails():\n return", "def send_test_email(self, recipients):\n borrowers, emails = reminder.generate_emails_from_db(test=True)\n for email in emails:\n if email.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send an email to all moderators when an exploration is flagged.
def send_flag_exploration_email( exploration_title, exploration_id, reporter_id, report_text): email_subject = 'Exploration flagged by user: "%s"' % exploration_title email_body_template = ( 'Hello Moderator,<br>' '%s has flagged exploration "%s" on the following ' 'grounds: <br...
[ "def sendBonusEmails():\n return", "def test_user_exploration_emails_handler(self) -> None:\n\n # Owner creates exploration.\n self.login(self.OWNER_EMAIL)\n exp_id = 'eid'\n self.save_new_valid_exploration(\n exp_id, self.owner_id, title='Title for emails handler test!',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends an email to all the recipients of the query.
def send_user_query_email( sender_id, recipient_ids, email_subject, email_body, email_intent): bulk_email_model_id = email_models.BulkEmailModel.get_new_id('') sender_name = user_services.get_username(sender_id) sender_email = user_services.get_email_from_user_id(sender_id) _send_bulk_mail( ...
[ "def send_mails(self):\n for recepient in self.recipients:\n self.send_mail(recepient)", "def send_email_users():\n\n # Get users emails\n users_emails = User.objects.exclude(\n Q(email='') |\n Q(email=None)\n ).values_list(\n 'email',\n flat=True\n )\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends an email to users to review suggestions in categories they have agreed to review for.
def send_mail_to_notify_users_to_review(user_id, category): email_subject = 'Notification to review suggestions' email_body_template = ( 'Hi %s,<br><br>' 'Just a heads-up that there are new suggestions to ' 'review in %s, which you are registered as a reviewer for.' '<br><br>Pl...
[ "def send_suggestion_email(\n exploration_title, exploration_id, author_id, recipient_list):\n\n email_subject = 'New suggestion for \"%s\"' % exploration_title\n\n email_body_template = (\n 'Hi %s,<br>'\n '%s has submitted a new suggestion for your Oppia exploration, '\n '<a href=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
want to check if that exact column has other numbers similar to it.
def column_similarity (self, row, col): my_number = self.board[row][col] for i in range (9): if (i,col) == (row,col): continue elif self.board[i][col] == my_number: return [i, col, False] else: continue
[ "def inSameCol(a, b):\r\n return a % 5 == b % 5", "def same_col(i, j):\n return (i - j) % 9 == 0", "def detect_jospel_in_row(row):\n if all(i == 10 or i == 1 for i in row):\n return 50\n return 0", "def checkColumn(self, column, number):\n for y in range(9):\n if s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
__init__(itkArray2DD self) > itkArray2DD __init__(itkArray2DD self, unsigned int rows, unsigned int cols) > itkArray2DD __init__(itkArray2DD self, itkArray2DD array) > itkArray2DD __init__(itkArray2DD self, vnl_matrixD matrix) > itkArray2DD
def __init__(self, *args): _itkArray2DPython.itkArray2DD_swiginit(self, _itkArray2DPython.new_itkArray2DD(*args))
[ "def __init__(self, *args):\n _itkArray2DPython.itkArray2DF_swiginit(self, _itkArray2DPython.new_itkArray2DF(*args))", "def __init__(self, *args):\n _itkArray2DPython.itkArray2DUI_swiginit(self, _itkArray2DPython.new_itkArray2DUI(*args))", "def __init__(self, *args):\n _itkMatrixPython.itkM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill(itkArray2DD self, double const & v)
def Fill(self, v: 'double const &') -> "void": return _itkArray2DPython.itkArray2DD_Fill(self, v)
[ "def Fill(self, v: 'float const &') -> \"void\":\n return _itkArray2DPython.itkArray2DF_Fill(self, v)", "def Fill(self, v: 'unsigned int const &') -> \"void\":\n return _itkArray2DPython.itkArray2DUI_Fill(self, v)", "def Fill(self, value: 'double const &') -> \"void\":\n return _itkMatrixPy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GetElement(itkArray2DD self, unsigned long long row, unsigned long long col) > double const &
def GetElement(self, row: 'unsigned long long', col: 'unsigned long long') -> "double const &": return _itkArray2DPython.itkArray2DD_GetElement(self, row, col)
[ "def GetElement(self, row: 'unsigned long long', col: 'unsigned long long') -> \"float const &\":\n return _itkArray2DPython.itkArray2DF_GetElement(self, row, col)", "def GetElement(self, row: 'unsigned long long', col: 'unsigned long long') -> \"unsigned int const &\":\n return _itkArray2DPython.it...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }