anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Getter method for action, mapped from YANG variable /input/mapping_record/action (enumeration)
def _get_action(self): return self.__action
The number of full days since last checkin. We consider the current day to start from 5AM local time. Note that this can be more than 24 hours ago!
def days_since_last_checkin(self): # TODO use local timezone checkin_date = (self.last_checkin - datetime.timedelta(hours=5)).date() today = datetime.date.today() return (today - checkin_date).days
Create a clone of the sentinel.
def clone(self) -> "set_default": return type(self)(self.value)
Create a fragment used to display the XBlock to a student. `context` is a dictionary used to configure the display (unused) Returns a `Fragment` object specifying the HTML, CSS, and JavaScript to display.
def student_view(self, context=None): # pylint: disable=W0613 # Load the HTML fragment from within the package and fill in the template html_str = pkg_resources.resource_string(__name__, "static/html/thumbs.html").decode('utf-8') frag = Fragment...
Uses average damage to determine time (ticks) to level up attack or strength Enemy has 1 def and 0 def bonus Weapon is best available scimitar
def level_time_average(start_levels, attack_style, attack_bonus, strength_bonus): ticks_per_attack = 4 # Scimitar attack speed max_hit, accuracy = get_max_hit_and_accuracy( start_levels, attack_style, attack_bonus, strength_bonus) if attack_style == Attack_Style.ATTACK: start_exp = osrs...
Run spark job that will associate vendor's users (loaded from REST API) with our users (loaded from MySQL)
def run(sc, logger): start = time.time() # Spark SQL Context sqlContext = sql.context.SQLContext(sc) # 1) Practices - Small table so no need to partition it, could even broadcast across all executors # Spark SQL JDBC Options: https://spark.apache.org/docs/latest/sql-data-sources-jdbc.html prac...
Returns an OAuth2 authorization token or None in case of errors. This is the flow for nonweb clients.
def get_token(client_id, client_secret, username, password): try: if oauth2db.check_client(client_id, client_secret): if oauth2db.check_user(username, password): token, refresh = oauth2db.generate_token(client_id, username) res = { "token": token } excep...
Determine if the transaction(t) belongs to trade(tr) without altering the tr
def tranBelong(tr, lst, t): if tr.isReal(): cp = Trade() cp.state = tr.state cp.addTrans(tr.tranCol+lst, False) else: cp = tr return cp.belong(t)
ingest from a particular sequence
def sequence_ingest(self,sequence): data=self.data counter=0 for item in data[sequence]: datestring=item['specimenDate'] date=fetchdate(datestring) row,created=DailyCases.objects.get_or_create(specimenDate=date,areacode=item['areaCode']) row.areaname=item['areaName'] row.dailyLabConfirmedCases=...
This function tests for all NaN values
def test_NaNall(self): Rectangle.reset_objects() with self.assertRaises(TypeError) as e: r1 = Square( float('nan'), float('nan'), float('nan'), float('nan')) self.assertEqual(str(e.exception), 'width must be an integer')
The entry endpoint of our API.
def api_root(request, format=None): return Response({ 'users': reverse('user-list', request=request), 'groups': reverse('group-list', request=request), 'pools': reverse('pool-list', request=request), })
Given data about a Bundle returned by any blockstore REST API, convert it to a Bundle instance.
def _bundle_from_response(data): return Bundle( uuid=UUID(data['uuid']), title=data['title'], description=data['description'], slug=data['slug'], # drafts: Convert from a dict of URLs to a dict of UUIDs: drafts={draft_name: UUID(url.split('/')[-1]) for (draft_name, ur...
>>> validate_n_digits_range(1920, 2002)("2002") True >>> validate_n_digits_range(1920, 2002)("2003") False
def validate_n_digits_range(min_val: int, max_val: int, n: int = 4) -> bool: def func(s: str): return validate_n_digits(n)(s) and min_val <= int(s) <= max_val return func
Secures handlers with auth token taken from ndb
def token_required(func): def func_wrapper(self, *args, **kwargs): auth_token = self.request.headers.get('X-Auth-Token', self.request.get('token', '')) namespace = self.request.route_kwargs.get('namespace', '') try: token = base64.url...
function which change cells
def change(self, num): if self.manhattan(self[0], self[num]) != 1: raise RuntimeError( "Numbers {} {} in positions {} {} can't change".format(0, num, self[0], self[num])) z_i, z_j = self[0] n_i, n_j = self[num] self.pos_to_num[(z_i, z_j)] = num self....
Specify whether the Secret or its key must be defined
def optional(self) -> Optional[bool]: return pulumi.get(self, "optional")
Extract a set of ngrams from a list of integers. create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)]
def create_ngram_set(self, input_list, ngram_value=2): return set(zip(*[input_list[i:] for i in range(ngram_value)]))
Extracts MFCCs from music dataset and saves them into a json file.
def preprocess_dataset(dataset_path, SAMPLES_TO_CONSIDER: int, num_mfcc = 13, n_fft = 2048, hop_length = 512): data = { 'mapping': [], 'labels': [], 'MFCCs': [], 'files': [] } # loop through all sub-dirs total_samples = 0 valid_samples = 0 for i, (di...
Confidence interval for differences between the two samples.
def non_param_paired_ci(sample1, sample2, alpha): n = len(sample1) N = norm.ppf(1 - alpha/2) diff_sample = sorted(list(map(operator.sub, sample2, sample1))) averages = sorted([(s1+s2)/2 for i, s1 in enumerate(diff_sample) for _, s2 in enumerate(diff_sample[i:])]...
! Brief Gets the binary and source files from the Github Release server [in] `tag_name` Git tag of the current release [in] `config` confi metadata set in main.py `List[ReleaseFile]` List of release files `Dict[str, SourceFile]` Dictionary of source files Sends an `HTTP GET` request to github using their REST API to re...
def get_release_files(tag_name, config) -> Tuple[List[ReleaseFile], Dict[str, SourceFile]]: @retry_multi(5) # retry at most 5 times def execute_request(path): """! @brief Performs a GET request with the given path. To be used with Github's REST API. @returns If successful, returns a .JS...
.mfk play Begin the game ||| [+/] Edit the mfk user list ||| marry fuck kill Give the verdict ||| score Retrieves the score of a user
def mfk(inp, db=None): db_init(db) inp = inp.lower() m_regex = re.compile(r"marry\s([a-zA-Z0-9_]+\s|[a-zA-Z0-9_]+)").finditer(inp) f_regex = re.compile(r"fuck\s([a-zA-Z0-9_]+\s|[a-zA-Z0-9_]+)").finditer(inp) k_regex = re.compile(r"kill\s([a-zA-Z0-9_]+|[a-zA-Z0-9_]+\s)").finditer(inp) if inp...
Initialize the dancling links matrix with a given number of columns
def __init__(self, numcols): # Start by making a root cell # This isn't part of the matrix, but it gives an entry point to the matrix # root.right is the first column header, root.left is the last # root.up and root.down just wrap around to itself root = Column("root") se...
Part 3 of Pressure
def get_pressurexlsb(self): byte_list = self.i2c.readfrom_mem( self.device_address, self.REGISTER_PRESSUREXLSB, 1, addrsize=8 ) val = 0 val = val << 8 | byte_list[0] return val
It gets its default key from settings.
def test_decrypt_key_default(self, settings): settings.CHITON_ENCRYPTION_KEY = b'0' * 32 encrypted = encrypt('message') assert decrypt(encrypted) == 'message' settings.CHITON_ENCRYPTION_KEY = b'1' * 32 with pytest.raises(EncryptionError): decrypt(encrypted)
Calculates total circumferences of a rectangle
def rectangle_circumference(a,b): return (2*(a+b))
emulate post request with get handler, we don't need the data
def do_POST(self): self.do_GET()
Truncates forest to maximum number of trees.
def truncate(self): self.population = self.population[:self.max_number_trees]
Read a prn file.
def read_prn(file_name): with open(file_name) as f: f = MyIter(f) try: assert next(f).strip() == 'prn:13|' assert next(f).strip() == 'subtype = MT2500' assert next(f).strip() == 'Doc={MT2500:14|' assert next(f).strip() == 'Film={12.1|' fi...
Create LeaderModel and send it as a PDF to the browser
def get_leader_model_pdf(currentEmpl, employees): lm = LeaderModel() employee_actions = {} legend = [] colors = {} errors = {'noactions': []} # numbered_actions = {} for empl in employees: if not currentEmpl.hasAccessTo(empl): raise PermissionDenied() actions ...
Given a normal feature matrix, creates a transpose feature matrix, a list of discrete features, and a list of nonempty features for each id. If the dataset is dense, this uses a Numpy matrix to save on space. Otherwise, it uses a listofdicts structure.
def __init__(self,db): self._numFeatures = len(db.keys) self._numEntries = len(db.entries) numMissing = 0 if isinstance(db.entries[0],dict): #already sparse database given as input self.featureMatrix = None self.featureDicts = [{} for i in range(self._...
Pause writing callback from transport.
def pause_writing(self): self._stream.pause_writing()
Returns parent of node at n; None if there isn't a parent
def parent(self, n): return None if n == 0 else (n - 1) // 2
Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure.
def _verify_cas1(ticket, service): params = {'ticket': ticket, 'service': service} url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' + urlencode(params)) page = urlopen(url) try: verified = page.readline().strip() if verified == 'yes': return page.readline(...
Test explicit overrides for the leading time dimension
def test_dimension_size_override(self, nt=100): i, j, k = dimify('i j k') a = TimeData(name='a', dimensions=(i, j, k)) one = symbol(name='one', dimensions=(i, j, k), value=1.) op = Operator(Eq(a.forward, a + one)) # Test dimension override via the buffered dimenions a.da...
Inplace reformulation of a QCQP to a COP toconic(self)
def toconic(self): res = __library__.MSK_XX_toconic(self.__nativep) if res != 0: _,msg = self.__getlasterror(res) raise Error(rescode(res),msg)
r""" Samples a 3d function f over specified intervals and returns three 2d arrays (X, Y, Z) suitable for plotting with matlab (matplotlib) syntax. See examples\mplot3d.py. f is a function of two variables, such as x2 + y2. x_args and y_args are intervals given in the form (var, min, max, n)
def sample3d(f, x_args, y_args): x, x_min, x_max, x_n = None, None, None, None y, y_min, y_max, y_n = None, None, None, None try: f = sympify(f) except SympifyError: raise ValueError("f could not be interpreted as a SymPy function") try: x, x_min, x_max, x_n = x_args ...
Creates a new git repo on the server (do not include the .git ending in git_repo_name)
def create_prod_git_repo(git_repo_name): with cd(git_dir): run("git init --bare %s.git && cd %s.git && git config http.receivepack true" % (git_repo_name,git_repo_name))
Returns the number of frames in the trajectory in universe u, using teq as equilibration time and tsample as sampling time
def traj_nslice (u,teq,tsample) : # get the number of frames in the slice (http://stackoverflow.com/a/7223557) traj_slice = u.trajectory[teq::tsample] return sum(1 for _ in traj_slice)
Returns the projection of the BinaryStateSequences using DAG functionality
def find_approx(self, gamma): if self.jumps != []: # first we divide the jumps of the BSS into subarrays in each of which the subsequent jumps are closer to each other than \gamma jump_seq_list = identify_jump_subseq(self.jumps, gamma) # jumps will store all jumps of the proj...
Convert from camera_frame to world_frame
def cam_to_world(cam_point, world_to_cam): # cam_point = np.array([cam_pose[0], cam_pose[1], cam_pose[2]]) obj_vector = np.concatenate((cam_point, np.ones(1))).reshape((4, 1)) world_point = np.dot(world_to_cam, obj_vector) world_point = [p[0] for p in world_point] return world_point[0:3]
Precautions You can call the [CreateDBInstance](~~61763~~) operation to restore a database for an ApsaraDB for MongoDB instance. For more information, see [Restore one or more databases of an ApsaraDB for MongoDB instance](~~112274~~).
def describe_backup_dbs( self, request: dds_20151201_models.DescribeBackupDBsRequest, ) -> dds_20151201_models.DescribeBackupDBsResponse: runtime = util_models.RuntimeOptions() return self.describe_backup_dbs_with_options(request, runtime)
Run a single epoch
def eval_model(device, model, sampler, loss_compute, logit_modifier_fxn, token_sampler, print_every, max_len, user_items_df, max_name_len=15, ingr_map=None, base_save_dir='', pad_ingr=None, ppx_only=False, **tensor_kwargs): start = datetime.now() results_dicts = [] # Extract ...
Optionally add the commitment commitment to the list of 'used', and optionally remove the available external commitment whose key value is the utxo in external_to_remove, persist updated entries to disk.
def update_commitments(commitment=None, external_to_remove=None, external_to_add=None): c = {} if os.path.isfile(PODLE_COMMIT_FILE): with open(PODLE_COMMIT_FILE, "rb") as f: try: c = json.loads(f.read()) except ValueError: pr...
Looks up rawdata id iraw and unpacks the job output tarballs from all jobs that completed successfully into a new directory named iraw under the pwd. If iraw is not known, alternatively one can supply the run number and sequence number of the raw data input file.
def unpack(run=0, seqno=0, iraw=0): if iraw == 0 and run == 0: print("Usage: osgprod_bind.unpack(iraw=<iraw>)") print(" or: osgprod_bind.unpack(run=<run>, seqno=<seqno>)") return 0 if iraw: with db_connection() as conn: with conn.cursor() as curs: curs.execute("""SEL...
player names and bid / trick / score headers
def init_column_headers(self): col_headers = {1: "bid", 2: "tricks", 3: "score"} for player in range(1, 5): ent_player_name = tk.Entry(self.master, font='courier 10 bold', fg='blue', borderwidth=2, relief="groove") ent_player_name.grid(...
Run the entire NBA_bet project.
def run_all(): db = DBInterface() year = Config.get_property("league_year") session = Session(bind=db.engine) scraper.scrape_all(db, session, year) session.commit() bets.predict_all(db, session) session.commit() session.close()
Finds the intersection of two lines given in Hesse normal form. Returns closest integer pixel locations.
def intersection(line1, line2): rho1, theta1 = line1 rho2, theta2 = line2 A = np.array([ [np.cos(theta1), np.sin(theta1)], [np.cos(theta2), np.sin(theta2)] ]) b = np.array([[rho1], [rho2]]) x0, y0 = np.linalg.solve(A, b) x0, y0 = int(np.round(x0)), int(np.round(y0)) retur...
(Personalization Only) The flag to enable statistics of Bing Search.
def event_hub_connection_string(self) -> Optional[str]: return pulumi.get(self, "event_hub_connection_string")
Ouput log of actions taken on method
def replay(method: Callable) -> None: counter_key = method.__qualname__ i_keys = method.__qualname__ + ':inputs' o_keys = method.__qualname__ + ':outputs' this = method.__self__ counter = this.get_str(counter_key) history = list(zip(this.get_list(i_keys), this.get_list(o_...
This funtion is to get the dataframe of yield to maturity and discount rate value.
def get_ytm_discount_data(self): ytm=Bootstrapping.get_ytm_dict(self) data = pd.DataFrame() for i in ytm.keys(): data.loc[i / 2, 'Yield to maturity'] = ytm[i] data.loc[i / 2, 'discount_rate'] = Bootstrapping.P_Tn(self,ytm[i], i) return data
Actually invoke the underlying function (but only if it hasn't been invoked already).
def start(self) -> None: cb = self._callback if cb is not None: self._callback = None propagate(from_=ensure_future(cb()), to=self._future)
Returns Json list of all Packages
def get_rest_list(request): if request.method == "GET": rest_list = Package.objects.order_by('-location') serializer = PackageSerializer(rest_list, many=True) return JsonResponse(serializer.data, safe=False)
Set the logger to log info in terminal and file `log_path`. In general, it is useful to have a logger so that every output to the terminal is saved in a permanent file. Here we save it to `model_dir/train.log`.
def set_logger(save=False, log_path=None): logger = logging.getLogger() logger.setLevel(logging.INFO) if not logger.handlers: if save: # Logging to a file file_handler = logging.FileHandler(log_path) file_handler.setFormatter(logging.Formatter('%(asctime)s:%(leve...
Method creates new population by choosing mi best individuals from children and current population
def choose_mi_best(self, R): population = np.empty([self.P.shape[0] + R.shape[0], 2*self.d + 1]) i = 0 for individual in np.vstack([self.P, R]): population[i, 0] = -self.J(individual[0:self.d], self.nCEC) population[i, 1:] = individual i = i+1 sorted_...
Calculate the inner product of the two patterns as a vecter.
def inner_product(pattern_one, pattern_two): return np.sum(np.multiply(pattern_one, pattern_two))
Return the list of full paths for pictures and movies in source directory
def list_of_medias(args, sourcedir, recursive): files = list_of_files(sourcedir, recursive) return [_ for _ in files if is_media_within_dates(_, args.dates)]
Conduct classification and calculate metrics
def classify(self, verbose=True, print_scores=False): if verbose: print("%s: Training model ..." % self.clf_name) self.clf.fit(self.X_train, self.y_train) if verbose: print("%s: Calculating probablities ... " % self.clf_name) y_proba = self.clf.predict_proba(self...
Identify distinct MPTCP Connections that reached Successful handshake Look for Ack packets with MPTCP option Header For each MPTCP connection report Receiver's token value which acts as the connectionID
def mptcp_connections(self, pkts): count = 0 #MPTCP_Capable = 0x0 #MPTCP_CapableACK ---> successful handshake print "======================================================================" print "Successful Handshake --- Look for Ack packets with MPTCP option Header" print """Token = connectionID = SHA1(key...
Returns a dict of predictions.
def _logits_to_predictions(self, logits): key = prediction_key.PredictionKey.SCORES with ops.name_scope(None, "predictions", (logits,)): if self.logits_dimension == 1: logits = array_ops.squeeze(logits, squeeze_dims=(1,), name=key) return {key: logits}
Creates a new subgroup of the outcome group with the same title and description as the source group, then creates links in that new subgroup to the same outcomes that are linked in the source group. Recurses on the subgroups of the source group, importing them each in turn into the new subgroup. Allows you to copy orga...
def import_outcome_group_global(request_ctx, id, source_outcome_group_id, **request_kwargs): path = '/v1/global/outcome_groups/{id}/import' payload = { 'source_outcome_group_id' : source_outcome_group_id, } url = request_ctx.base_api_url + path.format(id=id) response = client.post(request_c...
Getter method for weight, mapped from YANG variable /input/LocatorRecord/weight (uint8)
def _get_weight(self): return self.__weight
First Python implementation method of the Levenshtein distance between strings
def levenshtein(s1, s2): if len(s1) < len(s2): return levenshtein(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = pr...
Compute the gradient of the loglikelihood function for part f.
def find_mle_by_grad_descent(initial_sensor_loc, obj_loc, distance, lr=0.001, num_iters = 1000): sensor_loc = initial_sensor_loc # Your code: finish the gradient descent return sensor_loc
Saves the config file
def save_config_file(self): with open(self.config_file_name, 'w',encoding='utf-8') as outfile: json.dump(self._config, outfile,indent=2)
Delete a setting in the central setting file
def DeleteSetting(appname, section, key): settings = _OptionsDB(appname) settings.delete(section, key)
Read file returns read file as string
def rSeqFile(FilePath): f=open(FilePath, 'r') #check if file open if f.mode == 'r': return(f.read())
Method to remove the stop words used in get_left_right_lists() This method does not work for Catalan language.
def remove_stop_words(tokens, language): if not remove_stop_words_activated or language.__eq__("Catalan"): return tokens output = [] stop = stopwords.words(language.lower()) for token in tokens: if token not in stop: output.append(token) return output
Returns the number of sequences >= bound with len() <= max_len accepted by this NFA.
def num_accepts_ge(self, max_len: int, bound: Sequence[Text] = ()) -> int: _, num_accepted_eq, num_accepted_gt = self.num_accepts(max_len, bound) return num_accepted_eq + num_accepted_gt
Should return Python datetime object.
def test_06_dt_to_milliseconds_str(self): dt = datetime.datetime.utcnow() ts = utils.dt_to_milliseconds_str(dt) self.assertIsInstance(ts, str)
A heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial.
def nullHeuristic(state, problem=None): return 0
Rearrange Array Elements so as to form two number such that their sum is maximum.
def rearrange_digits(input_list): ## Corner cases: if len(input_list) == 0: return [0, 0] elif len(input_list) == 1: return [input_list[0], 0] # Sort an array using merge-sort sorted_list = merge_sort(input_list) # Create two empty array and pop largest number from an sorted_li...
Supports an additional argument ``jsonp_callback``. If specified, the JSON serialized data string will be wrapped in parenthesis and prefixed by the value of ``jsonp_callback``.
def __init__(self, *args, **kwargs): self.jsonp_callback = kwargs.pop('jsonp_callback', None) super(JsonResponse, self).__init__(*args, **kwargs)
Plots an image and the projections (sums) of it on the x, y axes.
def plot_image_and_proj(image, title="", **kwargs): fig = plt.figure() gs = gridspec.GridSpec(3, 2, width_ratios=[3, 1], height_ratios=[0.2, 3, 1]) ax0 = plt.subplot(gs[1,0]) plt.title(title) ims = plt.imshow(image, aspect="auto", **kwargs) ax2 = plt.subplot(gs[2,0], sharex=ax0, ) plt....
Print a message to the standard output, in case show_info is enabled.
def info(self, message): if self.show_info: print(message)
Find coordinates of a single run time, output and space dimensions.
def _getCoordsFromRun(self, run_dict, bold=False): run_dict = copy.deepcopy(run_dict) run_dict = self._filterDictionaryBold(run_dict, bold=bold) timeDictKey = "" if "t" in run_dict: timeDictKey = "t" else: for k in run_dict: if k.startswith...
def readtask(self,filename_): if isinstance(filename_,unicode): filename_ = filename_.encode("utf-8",errors="replace") res = __library__.MSK_XX_readtask(self.__nativep,filename_) if res != 0: _,msg = self.__getlasterror(res) raise Error(rescode(res),msg)
Load task data from a file. readtask(self,filename_)
def insert(self, dataset: List[Read]) -> bool: node_to_insert = Node(self.k, self.num_buckets, self.fp_size, self.bucket_size, self.max_iter) node_to_insert.populate_dataset_info(dataset) self.aggregate_size += node_to_insert.get_size() if self.root is None: self.root = node...
Creates a new node from this read and adds it into the tree
def test_from_knx_wrong_parameter2(self): with self.assertRaises(ConversionError): DPTValue1Ucount().from_knx("0x23")
Test parsing of DPTValue1Ucount with wrong value (array containing string).
def _ready_to_decrypt(self, shares: Dict[GuardianId, DecryptionShare]) -> bool: # If all guardian shares are represented including if necessary # the missing guardians reconstructed shares, the decryption can be made return len(shares) == self._context.number_of_guardians
Shares are ready to decrypt.
def server_closed_connection(self): print("Game Over!") if self._winner: print("Player {} wins!".format(self._winner)) else: print("Draw!")
Print out the end status of the game when the server closes the connection.
def lights(id, all, connect, info, action, bri): try: bridge = phue.Bridge(BRIDGE_IP) except Exception: click.secho( "Press the bridge buttom and call the connect again", fg='red') if connect: # If the app is not registered and the button is not pressed, # press ...
Actions to control hue lights
def _BoolOp(self, t): self.write("(") s = " %s " % self.boolops[t.op.__class__] interleave(lambda: self.write(s), self.dispatch, t.values) self.write(")")
Translate to logical and/or operators in C
def delete_outcome_group_courses(request_ctx, course_id, id, **request_kwargs): path = '/v1/courses/{course_id}/outcome_groups/{id}' url = request_ctx.base_api_url + path.format(course_id=course_id, id=id) response = client.delete(request_ctx, url, **request_kwargs) return response
Deleting an outcome group deletes descendant outcome groups and outcome links. The linked outcomes themselves are only deleted if all links to the outcome were deleted. Aligned outcomes cannot be deleted; as such, if all remaining links to an aligned outcome are included in this group's descendants, the group deletion ...
def train(args): log_header('Training network') train_retriever(args)
Run the training procedure
def server_hostname(self): result = c_char_p(self.lib.iperf_get_test_server_hostname(self._test)).value if result: self._server_hostname = result.decode('utf-8') else: self._server_hostname = None return self._server_hostname
The server hostname to connect to. Accepts DNS entries or IP addresses
def put(self, key, value): hi = self.hash_index(key) if self.storage[hi]: current = self.storage[hi] while current.next and current.key != key: current = current.next if current.key == key: current.value = value else: ...
Store the value with the given key. Hash collisions should be handled with Linked List Chaining. Implement this.
def aslist(something): return something if isinstance(something, list) else [something]
If something is not a list already make it one, otherwise simply return something
def create_wall_shape(self): self.shape_walls = arcade.ShapeElementList() self.shape_walls.center_x = 0 self.shape_walls.center_y = 0 self.shape_walls.angle = 0 point_list = [] color_list = [] # create the walls into a single shape walls = self.g...
Instead of rendering each wall block, we create a single shape which can be drawn in a single call, rather than a call for each wall block
def handle_port_config_change(sel, asic_context, stop_event, port_mapping, logger, port_change_event_handler): if not stop_event.is_set(): (state, _) = sel.select(SELECT_TIMEOUT_MSECS) if state == swsscommon.Select.TIMEOUT: return if state != swsscommon.Select.OBJECT: ...
Select CONFIG_DB PORT table changes, once there is a port configuration add/remove, notify observers
def confusion_matrix(predicted, gt): tp = [k for k in predicted if predicted[k] and gt[k]] tn = [k for k in predicted if not predicted[k] and not gt[k]] fp = [k for k in predicted if predicted[k] and not gt[k]] fn = [k for k in predicted if not predicted [k] and gt[k]] return tp, tn, fp, fn
Takes dictionaries of predicted and ground truth and returns confusion matrix
def _get_btc_gbp_15min(self) -> None: self._get_eur_gbp_last_daily() self.btc_gbp_15min = self.btc_eur_15min * self.eur_gbp_last_day
Calculate the 15min delayed BTC market price in GBP.
def test_documentation_popxl_adv_get_write(self): filename = "tensor_get_write_adv.py" self.run_python(filename, file_dir=working_dir, working_dir=working_dir)
Test the popxl advanced getting / writing tensor data example that shows exactly when devicehost transfers occur
def str_to_unicode(text, encoding='utf-8'): if isinstance(text, str): return text.decode(encoding) elif isinstance(text, unicode): return text else: raise TypeError('str_to_unicode must receive a str or unicode object, got %s' % type(text).__name__)
convert string to unicode
def _fetch_current_remote_metadata(conn): content = _get(conn, REMOTE_METADATA_FILE) metadata = json.loads(content) if content else {} return metadata
Fetches the metadata remote file REMOTE_METADATA_FILE and returns the metadata dict equivalent.
def close_window(self, button_msgs): if self.messages_window is not None: self.messages_window.destroy() self.messages_window = None button_msgs.config(command=lambda: self.new_window_messages(button_msgs))
closing the second Tk object
def kludge_gvars(mangled): # Loop in reverse looking for '+-', but don't run off the end for idx in range(len(mangled) - 1)[::-1]: if mangled[idx + 1] == '+-': reunited = ' '.join(mangled[idx:idx + 3]) # Throw away the used elements... for _ in...
Occasionally, gvars get rendered to strings as, e.g., 4e06 + 1 instead of 0.000006(1.0). This makes a complete mess of trying to parse the a list of gvar which has been turned into a string, e.g., '[1(2) 1 + 2 0.003(2)]', since the usual str.split() separates '1 + 2' > ['1','+','2']. This function is a kludge which wor...
def txt_file_reader(path): return open(path, encoding=cfg.ENCODING)
Opens a text file
def get_board(self): return self._board
get_board returns copy of the game's _board object
def parse_command(self, command): split_list = command.split() command = local[split_list[0]] if 'python' in split_list[0]: self.logger.debug(self.venv_pip) command = self.venv_python if split_list[0] == 'pip' or split_list[0] == 'pip3': self.logger.d...
generate plumbum command given an incoming string
def selectfont(self, char): charcode = ord(char) for font in fontchecksequence: for fontrange in fontmapping[font]: if charcode in xrange(fontrange[0], fontrange[1]): return font return "Helvetica" # fallback, if no thirdparty font is installed
Select font according to the input character