anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
def on_mouse_press(self, x, y, button, modifiers): menu: Menu = self.get_menu_for_display() menu_click_x, menu_click_y = self.get_menu_click(menu, x, y) if button == arcade.MOUSE_BUTTON_LEFT: if menu: menu.button_list.check_mouse_press_for_buttons( ...
Called when the user presses a mouse button.
def reffile(self): return os.path.join(self.__folder, self.__name + '.ref')
Returns complete path to reference file.
def __init__(self, trainer, logger_dir, experiment_name): if not os.path.isdir(logger_dir): raise IOError("{} is not a valid directory".format(logger_dir)) super().__init__(trainer) experiment_dir = os.path.join(logger_dir, experiment_name) os.mkdir(experiment_dir) s...
Initializes the Tensorboard writer
def get_data(file_name): csv_file = open(file_name, 'rb') train_content = csv.reader(csv_file) # ignore header train_content.next() # preprocessing functions for each column index # Several preprocessing can be defined for each column. # A new variable is associated to EACH preprocessing f...
Get the data from the dataset and apply preprocessing to extract hours.
def render(self, mode: str = 'human', steps_per_sec: int = 2, debug_text: Optional[str] = None): if mode not in BombermanEnv.metadata['render.modes']: raise ValueError('Invalid render mode') self.renderer.render(mode, steps_per_sec, debug_text)
Renders or prints the step.
def expand_paths(__file__, paths_with_globs): if isinstance(paths_with_globs, str): return expand_path(__file__, paths_with_globs) else: expanded_globs = [ expand_path(__file__, path) for path in paths_with_globs ] # Flatten return list(itertools.chain.from_it...
Returns full paths for a series relative paths with globs
def envs(self) -> Optional[Sequence['outputs.CSIPowerStoreSpecDriverSideCarsEnvs']]: return pulumi.get(self, "envs")
Envs is the set of environment variables for the container
def compute_min_refills(distance: int, tank: int, stops: List[int]): location: int = 0 n_stops = 0 last_stop = 0 max_drive = location + tank while max_drive < distance: counter = 0 # Handle the case that stops are depleted before we reach distance if len(stops) == 0: ...
Calculate the min number of refills to reach 'distance'. You start with a full tank.
def _find_unused_static_warnings(filename, lines, ast_list): static_declarations = { node.name: node for node in ast_list if (isinstance(node, ast.VariableDeclaration) and 'static' in node.type.modifiers) } def find_variables_use(body): for child in body: ...
Warn about unused static variables.
def test_code009(self, *test_code_args, **test_code_kwargs): print("This is test_code009 from TestDefinition #", self.ID, ", test case #", self.test_case_ID, sep='')
Test case code number 009.
def common(): full_song = "" albums = simple_album_list() for album in albums: songs = simple_songs_list(album) for song in songs: full_song += str(song_lyrics(song)) split_lyrics = full_song.lower().split() counter = collections.Counter(split_lyrics) most_wo...
This function makes list of the top 50 commonest words of all songs
def assertNoRepeatGuids(context, posts): guids = [p['guid'] for p in posts] context.assertTrue(len(set(guids)) == len(posts), "Some guids repeated")
Takes response.data and confirms no repeated guids (No repeated posts)
def apply_style(self, app): darkPalette = QPalette() # base darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Button, QColor(53, 53, 53)) darkPalette.setColor(QPalette.Light, QColor(180, 180, 180)) darkPalette.setColor(QPalet...
Apply Dark Theme to the Qt application instance.
def main(): browser = initialize() process_directory(browser, "data") browser.close()
Run the main functionality of this script.
def parse_pbobject(source, pb_class): if isinstance(source, str): return open_pbobject(source, pb_class) elif isinstance(source, bytes): pb_object = pb_class() pb_object.ParseFromString(source) return pb_object else: logging.error(f'cannot parse type {type(source)}')
Like open_pboject but source can be a path or a bytestring
def init_timeparams(options): params = OrderedDict() # for time prediction ''' W_t = np.zeros(options['dim_proj']) params['W_t'] = W_t.astype(config.floatX) b_t = np.zeros(1) params['b_t'] = b_t.astype(config.floatX) ''' W_t = init_params_weight(options['dim_proj'], 1) params['W_...
Initializes values of shared variables.
def __duplicate_m2o_fields(self, duplicate): fields = set() for f in self._meta.concrete_fields: if f.many_to_one: if any( [ f.name in self._clone_m2o_or_o2m_fields, self._clone_excluded_m2o_or_o2m_fields ...
Duplicate many to one fields.
def init(starting_position, steering_noise, distance_noise, sonar_noise, measurement_noise, speed, turning_speed, gps_delay, execution_cpu_time_limit): raise NotImplementedError()
starting_position (x,y) tuple representing current_position
async def on_building_construction_started(self, unit: Unit):
Override this in your bot class. This function is called when a building construction has started.
def rec_freq(markers): keys = list(markers.keys()) rf_pairs = {} for i in range(len(markers)): for j in range(i + 1, len(markers)): m1 = markers[keys[i]][0] m2 = markers[keys[j]][0] tot_len = 0 score = 0 if len(m1) != len(m2): ...
Calculates recombination frequency between all combinations of two markers.
async def link(self, ctx): if not is_linked(ctx.author.id): token = str(uuid.uuid4()) valid_until = int((datetime.utcnow() + timedelta(days=1)).timestamp()) add_token(ctx.author.display_name, ctx.author.id, token, valid_until, str(ctx.author.avatar_url)) web_base_...
Link a spotify account to the bot.
def run_animation(self, clip_name, fragment, zoom=True, pad=3, interval=100): preprocessor = self.process_data(clip_name) period_person_division = preprocessor.period_person_division running_person_identifiers = preprocessor.get_running_person_identifiers() running_fragments = preproce...
Complete pipeline to process and plot data.
def _evalContext(self): def xor(*args): return sum(args) == 1 def neg(result): return not result context = { 'xor': xor, 'neg': neg } return context
Supported functions for the user in boolean equations.
def getUserName(self, response): sel = response.selector blackTr = sel.xpath(u"//table[contains(@class,'black_table')]/tr[position()>1]//p[contains(text(),'真实姓名')]/a/@href").extract() url = 'http://www.ppdai.com' urls = [url+i for i in blackTr] redis_key = 'ppai_blacklist_redis_s...
get user name from xtml
def __init__(self, **kwargs): kwc=kwargs.copy() AbstractComplexParameterType.__init__(self, value_class='ArrayValue', **kwc) self._gen_template_attrs()
kwargs Additional keyword arguments are copied and the copy is passed up to AbstractComplexParameterType; see documentation for that class for details
def get_all_emails_it(auth, user_id, folder_id='AllItems', pages_limit=None, pages_size=50, **kwargs): i = 0 args_dict = dict(kwargs, top=pages_size, skip=pages_size * i) curr_emails = get_emails(auth, user_id, folder_id, **args_dict) while len(curr_emails) != 0: yield curr_emails ...
iterator which goes through all the pages to find all the emails
def get_controller(equipment, accessmethod, logfile=None): path = _CONTROLLERMAP[accessmethod] constructor = module.get_object(path) return constructor(equipment, logfile)
Return controller instance that is based on the equipment role.
def getServiceIdsForDate(self, dt, exclude0000=True): dayDict = {1:"monday", 2:"tuesday", 3:"wednesday", 4:"thursday", 5:"friday", 6:"saturday", 7:"sunday"} sqlQuery = "select service_id from calendar" \ + " where {} = 1".format(dayDict[dt.isoweekday()]) \ + " and...
Return list of service_ids that match a given datetime
def xd_element(name): try: name = name[:2] except: pass try: covalence_radius[name] except: name = name[0] return name
Return the element of an atom as defined in it's label.
def test_edit_profile(self): LOGGER.debug("Test GET /rango/edit/ for anon user") anon_edit_response = self.client.get('/rango/edit/') # redirected to login page self.assertEquals(302, anon_edit_response.status_code) self.assertRedirects(anon_edit_response, "http://testse...
Test to see if profile for user1 can be edited anon and logged in
def _get_bios_hash_password(self, bios_password): request_headers = {} if bios_password: bios_password_hash = hashlib.sha256((bios_password.encode()). hexdigest().upper()) request_headers['X-HPRESTFULAPI-AuthToken'] = bios_password_...
Get the hashed BIOS password.
def collect_attachments(self, paths_or_urls: Iterable[str]) -> List[Tuple[str, str, str, bytes]]: attachments = [] same_content = [] # type: List[bytes] for src in paths_or_urls: try: content = self.load_file(src) except ImageNotFound as err: ...
Collect attachment contents from paths or urls.
def isfloat(value): try: float(value) return True except ValueError: return False
Returns True if value can be converted to float, otherwise returns False.\n
def parser_weight(cls, data_dict): # get user's answer context = {} actual_weight = data_dict.get("actual_weight") goal_weight = data_dict.get("weight_goal") # if not valid # create an error message if float(goal_weight) >= float(actual_weight): text ...
check if the user's answer is valid
def backward(self,distance): assert (type(distance) in [int, float]), "parameter distance:%s is not a valid number" % `distance` self._turtle.backward(distance)
Moves the turtle backward by the given amount.
def runtime_error(self, error: 'LoxRuntimeError'): output = f'{error.get_message()}{os.linesep}[line {error.token.line}]' print(output, file=sys.stderr) self.had_runtime_error = False
report a runtime error
def linearFit(title, threadCounts, bestTimes, independentVar, unit): outputHtml("<h1>" + title + "</h1>") results = {} impls = sorted(list(bestTimes.keys()), key=cmp_to_key(compareFn)) outputHtml('<table border="1">') if independentVar[-1] == "s": independentVar = independentVar[:-1] out...
Print info on a linear fit
def cosine_decay_with_warmup(global_step, learning_rate_base, total_steps, warmup_learning_rate=0.0, warmup_steps=0, hold_base_rate_steps=0): if total_steps < warmup_steps...
Cosine decay schedule with warm up period.
def start(self, wait_for_port=False): for c in self.openstack_endpoints.values(): c.compute = self.compute c.manage = self.manage c.server_thread = threading.Thread(target=c._start_flask, args=()) c.server_thread.daemon = True c.server_thread.name = c....
Start all connected OpenStack endpoints that are connected to this API endpoint.
async def no_sleep_coro(): pass
Creates a coroutine that does nothing for when no sleep is needed.
def process_time_string(timestr): timestr = timestr.strip() toks = timestr.split('+') timeslices = [] for t in toks: tm = t.strip() mobj = re.search('\\*', tm) if mobj == None: timeslices += [int(tm)] else: tms = tm.split('*') timeslice...
This function processes the timestring from PSMC and converts this to list of time slice lengths
def main(*args): # # Use argparse to handle parsing the command line arguments. # https://docs.python.org/3/library/argparse.html # parser = argparse.ArgumentParser(description='Animate an epidemic') parser.add_argument('--size', metavar='N', type=int, default=50, help=...
Command line entry point. $ python runsim.py show animation on screen $ python runsim.py file=video.mp4 save animation to video $ python runsim.py plot show plot on screen $ python runsim.py plot file=plot.pdf save plot to pdf
def handle(self, message: Message) -> None: self.handled_message = message envelope = Envelope( to=message.counterparty, sender=self.context.agent_address, protocol_id=TwoPartyNegotiationMessage.protocol_id, message=self.encoded_message_2_in_bytes, ...
Implement the reaction to a message.
def entrench_word(self, cloud, paradigms, informativity, categorization, unique_base): # Entrench within the WordForm's own cloud. Iterate over positions in # the WordForm (up to three Segments). for pos, seg in enumerate(self.segments): if pos < 3: ...
Entrench at the level of the WordForm.
def putsnxslice(self,whichsol_,first_,last_,snx_): _snx_minlength = ((last_) - (first_)) if ((last_) - (first_)) > 0 and snx_ is not None and len(snx_) != ((last_) - (first_)): raise ValueError("Array argument snx is not long enough: Is %d, expected %d" % (len(snx_),((last_) - (first_)))) if snx_ is N...
Sets a slice of the snx vector for a solution. putsnxslice(self,whichsol_,first_,last_,snx_)
def message(): if request.method == 'POST': db.log_msg(request.form['text'], request.cookies.get('username')) return db.get_all_messages()
Route for posting messages or getting the prerendered html
def forward_backward(self, data_batch): total_feature, total_label = self.forward(data_batch, is_train=True) self.backward_all(total_feature, total_label)
A convenient function that calls both ``forward`` and ``backward``.
def view(): # retrieve child and dorm parents records from database children = Child.query.filter_by().all() parents = Parent.query.filter_by().all() return render_template('view.html', children=children, parents=parents)
Render the website's add page.
def main(sys_argv: List[str] = None, should_setup_logging: bool = True) -> int: if sys_argv is None: sys_argv = sys.argv[1:] args = parse_args(sys_argv) if args is not None and args.command == 'gui': gui_args = [arg for arg in sys_argv if arg != 'gui'] import stm32pio.gui.app as g...
Entry point to the CLI edition of application. Since this is a highestorder wrapper, it can be used to
def isLastPage(page_num, count_of_combos, per_page): if count_of_combos <= (page_num * per_page): return True return False
Return True if this is the last page in the pagination
def flow(self, batch_size=32, output='both', crops=0): while True: for dataset in self.input_sets: X = self.training_set['input/'+dataset] y = self.training_set['target/'+dataset] y_seg = self.training_set['seg_map/'+dataset] for i in ...
Generate outputs from a noncompact TrainingSet to use with Keras' 'fit_generator' function. If 'n_crops' is nonzero, the Iterator crops n_crops 20x20 regions from each image before feeding them.
def __init__(self, ego_name: str, ego_id: int = None, last_time: int = 0, min_pub_date: int = None): self.ego_name = ego_name self.publications = {} self.min_pub_date = min_pub_date super(CoauthorshipNamedEgoNetwork, self).__init__(ego_id, last_time)
Create a new CoauthorshipEgoNetwork by specifying the id and the name of the ego.
def registration_allowed(self, request): return getattr(settings, 'REGISTRATION_OPEN', True)
Indicate whether account registration is currently permitted, based on the value of the setting ``REGISTRATION_OPEN``. This
def like( self, other: Any, escape: Optional[str] = None ) -> ColumnOperators: return self.operate(like_op, other, escape=escape)
r"""Implement the ``like`` operator.
def to_m3u_track(record: Dict[str, str]) -> str: location = normalize(unquote(record.get("Location"))) # m3u duration in seconds, not ms duration = int(record.get("Total Time")) // 1000 name = normalize(unquote(record.get("Name"))) artist = normalize(unquote( record.get("Artist") or ...
Converts a single track record into m3u format. Need the normalization to fix the way Apple handles e.g. combining diacriticals.
def load(extended=False): _fetch_large() if extended: return _load(cache_experiment_extended, _parse_experiment) else: return _load(cache_experiment, _parse_experiment)
Load the EEG data, which is a particular split of the first trial of subject 337 in the large training data.
def load_vectors(vec_file, info_file, buckets): vectors = np.load(vec_file) with open(info_file, 'r') as f: info = json.load(f) if len(info['sequence_id_list']) != len(info['instance_id_list']): raise ValueError('Invalid info file: len(info[''sequence_id_list'']) should be equal to len(info...
load data into buckets.
def save_msg(self, msg: TrafficSigns): if msg.sub_messages: tf = self.get_transformation( "sim_world", msg.header.frame_id, msg.sub_messages[0].header.stamp, timeout=rospy.Duration(0.1), ) if tf is not None: ...
Add a message to the signs.
def same_type(one, two): return isinstance(one, type(two))
Check if two things have the same type.
def nfvi_cold_migrate_confirm_instance(instance_uuid, callback, context=None): if context is None: cmd_id = _compute_plugin.invoke_plugin_expediate( 'cold_migrate_confirm_instance', instance_uuid, context, callback=callback) else: cmd_id = _compute_plugin.invoke_plugin( ...
Cold migrate confirm an instance
def init_db(conn: Connection) -> None: logger.info(f"{Fore.YELLOW}Initializing database ...{Style.RESET_ALL}") # Create specified schema if not exists if not conn.dialect.has_schema(conn, schema_name): logger.info(f"{Fore.YELLOW}Schema {schema_name} does not exist, creating it ...{Style.RESET_ALL}...
Configures the target schema in which the tweets data will be stored, creates the schema and the table if not existing yet
def getInfo(self): doc = minidom.parse(urllib.urlopen(serverString + "/rest/asset/" + self.id)) self._getInfoFromNode(doc.getElementsByTagName("asset")[0])
Get name, description, tags, 10 latest comments, type, parent, rating, creation date and author name/id
def _build_infinite_size_dataloader(dataloader): iterator = dataloader.__iter__() while True: try: yield iterator.__next__() except StopIteration: iterator = dataloader.__iter__()
Build a looped dataloader with infinite size.
def lab_to_xyz(image: tf.Tensor) -> tf.Tensor: l, a, b = tf.unstack(image, axis=-1) var_y = (l + 16) / 116 var_x = a / 500 + var_y var_z = var_y - b / 200 var_x = tf.where(tf.pow(var_x, 3) > 0.008856, tf.pow(var_x, 3), (var_x - 16 / 116) / 7.787) var_y = tf.where(tf.pow(var...
Convert an image from LAB color space to XYZ color space
def calc_bus_value(self, bus): b = bus.comps.loc[self] comp_val = self.bus_func(b) expr = self.calc_bus_expr(bus) if b['base'] == 'component': return comp_val * b['char'].evaluate(expr) else: return comp_val / b['char'].evaluate(expr)
r""" Return the busses' value of the component's energy transfer.
def fusion_api_edit_server_profile_template(self, body, uri, api=None, headers=None): return self.profile_template.update(body, uri, api, headers)
Updates a Server Profile Template. [Arguments]
def monome(c,d): P = [0]*(d+1) P[d] = c return P
Construit un monome d'un degre donne et de coefficient donne
def _syncDataWithParent(self): parent = self.parent() if parent is None: data, range_ = None, None else: data = parent.getData(copy=False) range_ = parent.getDataRange() self._updateData(data, range_)
Synchronize this instance data with that of its parent
def get_losses(self): if self.loss is not None: return [self.loss] else: return []
Get losses of last computation if existing
def plug_vifs(self, instance, network_info): raise NotImplementedError()
Plug VIFs into networks.
def convert_sparse_to_igraph(indices, matrix): # sources, targets = matrix.nonzero() # weights = matrix[sources, targets] # weights = np.array(weights)[0] # print(dir(louvain)) # ig = igraph.Graph(zip(sources, targets), directed=True, # edge_attrs={'weight': weights}) # return...
Convert an adjacency graph in scipy sparse matrix format into an iGraph format.
def get(self, namespace_name, repository_name, username): roles = model.get_repo_roles(username, namespace_name, repository_name) if not roles: raise NotFound return {"permissions": [r.to_dict() for r in roles]}
Get the fetch the permission for the specified user.
def _getShaderRefs(self): warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2) return getShaderNodes(self)
(Deprecated) Return a vector of all shader references in this material element.
def test_init(self): # the self.assertEqual() checks fofr an expected result # We are checking if the name and description of our new object is what we actually put self.assertEqual(self.new_contact.first_name, "James") self.assertEqual(self.new_contact.last_name, "Muriuki") self...
has to be called test_init. This is to test if the object is initialized properly.
def get_nodes(self): try: for node in Linode.search(status=Linode.STATUS_RUNNING): self.add_node(node) except chube_api.linode_api.ApiError, e: print "Looks like Linode's API is down:" print print e sys.exit(1)
Makes an Linode API call to get the list of nodes.
def test_normals(self, faces, point): space = self.Space(faces=faces) cube_normals = gs.array( [ [0.0, 0.0, 2.0], [0.0, 0.0, 2.0], [0.0, 2.0, 0.0], [0.0, 2.0, 0.0], [2.0, 0.0, 0.0], [2.0, 0.0, 0.0...
Test normals. We test this on a space whose initializing point is a cube, and we test the function on a cube with sides of length 2 centered at the origin. The cube is meshed with 12 triangles (2 triangles per face.) Recall that the magnitude of each normal vector is equal to the area of the face it is normal to.
def execute(self, i: dict) -> None: # execute instruction for instruction processor if i["recipient"] == "proc": if self.suffixes_condition[i["suf"]](): if i["type"] == "proc_alu": # TODO: cmpi_ fix i["func"](self.regs[i["dest"]], self....
Executes given parsed instruction
def dump(self, camel_case: bool = False) -> Dict[str, Any]: dumped = { "id": self.id, "external_id": self.external_id, "is_string": self.is_string, "is_step": self.is_step, "unit": self.unit, "datapoints": [dp.dump(camel_case=camel_case) fo...
Dump the datapoints into a json serializable Python data type.
def subsample_training_set(self, k, seed=None): if seed is not None: rng_state = th.random.get_rng_state() with th.random.fork_rng(): th.manual_seed(seed) self._subsample_training_set(k) if any(th.random.get_rng_state() != rng_state): ...
Subsample the training data (for low resource experiments)
def get_portfolio_value(prices, allocs, start_val): normed = prices/prices.iloc[0] alloced = np.multiply(allocs, normed) pos_vals = alloced * start_val port_val = pos_vals.sum(axis=1) return port_val
Given a starting value and prices of stocks in portfolio with allocations return the portfolio value over time.
def getlenbarvarj(self,j_): lenbarvarj_ = ctypes.c_int64() res = __library__.MSK_XX_getlenbarvarj(self.__nativep,j_,ctypes.byref(lenbarvarj_)) if res != 0: _,msg = self.__getlasterror(res) raise Error(rescode(res),msg) lenbarvarj_ = lenbarvarj_.value _lenbarvarj_return_value = lenbarvarj...
Obtains the length of one semidefinite variable. getlenbarvarj(self,j_)
def trigger_delete(cls, instance): es_client.delete(instance.blog.index_name(), 'blog_page_index', instance.id)
Delete the index from Elastic Search
def compute(self): self.find_n() # call hotspot field plots for scenario in self.scenarios: fields_dict = {} ancestor_files = [] for filename in io.get_all_ancestor_files(self.cfg, pattern='hotspot_*.nc'):...
Collect datasets and call the plotting functions.
def loglikeobs(self, params, *args, **kwargs): raise NotImplementedError # pragma: no cover
Loglikelihood of model evaluated pointwise
def configuration_options_object_processor(configuration_options): option_names = [option.name for option in configuration_options.configuration_options] for option_name in option_names: if option_names.count(option_name) > 1: raise WashError(f'Configuration option with the name {option_name...
Validates if all ConfigurationOption names are unique in the ConfigurationOptions instance.
def extract_phrase(self, src_text, tgt_text, alignment, max_phrase_len=0): def extract_from_range(tgt_start, tgt_end, src_start, src_end, max_phrase_len): """Extract a set of possible phrase given the source, language ranges. """ # print("rages", tgt_start, tgt_end, src_star...
Extract all phrases from word alignment.
def __init__(self, policy: TypePolicy, byte_offset: int, byte_size: int, bin: TypeBinName): self._children= ( byte_offset, byte_size, _GenericExpr(_ExprOp._AS_EXP_BIT_FLAGS, 0, {_Keys.VALUE_KEY: policy['bit_write_flags']} if policy is not None and 'bit_write_flags' in...
Create an expression that performs a bit_remove operation.
def update_freshclam(module, freshclam_binary): rc_code, out, err = module.run_command("%s" % (freshclam_binary)) return rc_code, out, err
Run freshclam to update ClamAV signatures
def compute_fog_faded_color(self, color: Color, dz: float) -> Color: fade_amount = math.exp(-(dz * self._fog_factor)**2) return mix_colors(UPPER_SKY_COLOR, color, fade_amount)
Fade a color depending on how far from the camera it is.
def sum_over_all_but_batch_and_last_n( tensor: torch.Tensor, n_dims: int ) -> torch.Tensor: if tensor.dim() == n_dims + 1: return tensor else: dims = list(range(1, tensor.dim() - n_dims)) return tensor.sum(dim=dims)
r""" Calculates the sum over all dimensions, except the first (batch dimension), and excluding the last n_dims. This function will ignore the first dimension and it will not aggregate over the last n_dims dimensions.
def test_sqs_log_handler_extra_json_data(self): try: extra = { "test": "test logging", "num": 1, 5: "9", "float": 1.75, "nested": {"more": "data"} } self.logger.info("test info message with proper...
Fails if log handler does not output expected log message with extras
def get_connection(self, params): return Redis(connection_pool=self.get_or_create_connection_pool(params))
Given a now preformated params, return a new connection. The default implementation uses a cached pools for create new connection.
def get_clever_key(self): key = self.bot_data_file["apiKeys"]["cleverbot"] if self.check_empty_key(key): return key else: print("ERROR GETTING THE CLEVERBOT KEY (get yours from https://www.cleverbot.com/api/)- ABORTING") quit(1)
Function that return the api key for the cleverbot api.
def detect_objects(self, image, threshold): self.set_input_tensor(image) self.interpreter.invoke() # Get all output details boxes = self.get_output_tensor(0) classes = self.get_output_tensor(1) scores = self.get_output_tensor(2) count = int(self.get_output_tensor...
Returns a list of detection results, each a dictionary of object info.
def close(self) -> None: self.simulator.close()
Clean up the environment after the user has finished using it. It terminates the Python Jiminy engine.
def click_vendor_price_lists_search_button(self): search_button_element = self.wait().until(EC.element_to_be_clickable(self.search_button_locator), 'search button not found before specified time') self.script_executor_click(search_button_element) self.wait_for_ajax_spinner_load(300)
Implementing click vendor price lists search button functionality
def attach_display(self, display): self.extra_displays.append(display) self.addDockWidget(Qt.RightDockWidgetArea, display) #self.display_attached.emit(display)
Attach an extra display to the control. Those displays are updated whenever a step occurs.
def ang2xy(self, theta, phi=None, lonlat=False, direct=False): pass
From angular direction to position in the projection plane (%s).
def add_blogpost(manuscript, subject, url): line_number = 0 with open(manuscript, "r") as file: lines = file.readlines() for line in lines: if ("## ブロマガ全集" in line): lines.insert(line_number + 2, f"- [{subject}]({url})\n") with open(manuscript, "w") as file: ...
Add blogpost to manuscript
def list_aspects(request, pk): category = get_object_or_404(GradeCategory, pk=pk) aspects = GradeCategoryAspect.objects.filter(Category=category) ts = get_timeslot() return render(request, "results/list_aspects.html", { "aspects": aspects, 'ts': ts, 'cat': category, })
List all aspects of a given grade category in the current timeslot