dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def morgan(filename, iteration=0): dic, data = get_values_matrix(filename) result = data.copy() for l in range(1,iteration+1): for i in list(dic): r = [data[j] for j in dic[i][1]] result[i] = sum(r) data = result.copy() morgan={} count=2 arg= list(data.arg...
The main task of the code is to process a molecular file (ChEBI_17895.mol) by generating Morgan fingerprints, calculating atomic degree nodes, and identifying ring structures. It prints the results of these cheminformatics analyses, including Morgan fingerprints, degree node values, and ring perception data, to assess ...
def main(): morgan, dic, data = morgan("./files/ChEBI_17895.mol", 20) print("Morgan for ChEBI_17895.mol \n {}".format(morgan)) print("----------------------") dic,values=degree_node("./files/ChEBI_17895.mol") print("Degree Node for ChEBI_17895.mol \n {}".format(values)) print("-----------------...
def get_lengths(self, labels, padding=-1): """ Get length of each sentences. :param labels: Labels of each word for each sentence. :param padding: Padding value to use, default -1. :return: Length of each sentence, size = (batch). TODO: remove for cycle, make it with matr...
The code calculates the negative log-likelihood loss for training a sequence labeling model. It computes the model's score for the correct labels and subtracts the normalized CRF score, then returns the negated mean as the loss to optimize during training.
def neg_log_likelihood(self, batch): """ Used for training, returns a loss that depends on the difference between the score that the model would give to the sentence annd the score it would give to the correct labeling of the sentence. :param batch: :return:Pytorch loss. ...
def tgv2_pd(f, alpha, maxit): """ @param f: the K observations of shape MxNxK @param alpha: tuple containing alpha1 and alpha2 @param maxit: maximum number of iterations @return: tuple of u with shape MxN and v with shape 2xMxN """ # image space f_img = f # shape of things M, N...
The code performs TGV-Fusion on multi-channel image data using varying hyperparameters (alpha values). It loads observations, ground truth, and applies the TGV2-PD algorithm for denoising. For each alpha pair, it computes energy, accuracy against ground truth, and visualizes results. The goal is to evaluate parameter e...
def main(): # path to img data and save location data_path = '../ignore/ass4_data/' # Load Observations samples = np.array([np.load(data_path + 'observation{}.npy'.format(i)) for i in range(0,9)]) f = samples.transpose(1,2,0) print("samples f: ", f.shape) # shape of things M, N, ...
def load_imgs(img_path, img_name, dark_img, use_dark_img=False): """ load input images """ # left image for reference im0 = imread(img_path + img_name + "_left.png") # right image dark if img_name == 'Adirondack' and use_dark_img: im1 = imread(img_path + dark_img + "_right.png") ...
The main task of the code is to evaluate disparity estimation methods (SAD, SSD, NCC) using Semi-Global Matching (SGM) and Winner-Takes-All (WTA) on stereo image pairs. It iterates through varying filter radii, L1/L2 cost parameters, computes cost volumes, pairwise costs, and disparity maps, then measures accuracy agai...
def main(): # path to img data and save location -> change this to corresponding location! img_path = '../ignore/ass3_data/' fig_path = '../ignore/ass3_data/figs/' # image names img_names = ['Adirondack', 'cones'] dark_img = 'AdirondackE' # choose image img_name = img_names[0] # ...
def calculate_guided_image_filter(input_img, guidance_img, filter_size, epsilon): # scenario 1, input image F = F_H and guided filter # I = G F = input_img I = guidance_img m_p = compute_mean(F, filter_size) mu_p = compute_mean(I, filter_size) variance = compute_variance(I,filter_size) ...
The function `guided_upsampling` applies a guided image filter to upscale or align an input image (`input_img`) using a guidance image (`guidance_img`). It checks if the input and guidance images have matching dimensions, resizing the guidance image if necessary. For each color channel, it computes filter coefficients ...
def guided_upsampling(input_img, guidance_img, filter_size, epsilon): # test dimension whether it is case one or two # and then call the corresponding function # scenario 1: everything stays the same in terms # of sizes U_q = np.zeros([guidance_img.shape[0],guidance_img.shape[1], input_img.shape[2]...
def calculate_guided_image_filter(input_img, guidance_img, filter_size, epsilon): # F is the input_img, I is the grey guidance_img # compute mean and variance of guidance image mu = compute_mean(guidance_img, filter_size) variance = compute_variance(guidance_img, filter_size) # mp is mean of F in...
The code performs guided upsampling of an input image using a guidance image. It resizes the guidance image to match the input's dimensions if they differ, applies a guided filter on each color channel, and computes output coefficients. If the images differ in size, it upsampled the filter coefficients to the guidance ...
def guided_upsampling(input_img, guidance_img, filter_size, epsilon): # Init output image and filter coeffs Uq = np.zeros(input_img.shape) a = np.zeros(input_img.shape) b = np.zeros(input_img.shape) # approach two: sample down guidance image if input_img.shape != guidance_img.shape: I = ...
def set_ip(): global VIC_IP ip = "" try: ip = input("IP address of the victim: ") except Exception as error: print(str(error)) if check_ip(ip): VIC_IP = ip else: set_ip() def set_port(): global VIC_PORT VIC_PORT = RandNum(1025, 65535) def set_pname(): ...
The main task of the code is to configure system parameters including IP address, port, process name, and directory, then print these configured values for verification. The function initializes settings via `set_ip()`, `set_port()`, `set_pname()`, and `set_directory()` before outputting the IP, port, and process name ...
def config(): set_ip() set_port() set_pname() set_directory() print("") print("IP address: {0}".format(VIC_IP)) print("Port: {0}".format(VIC_PORT)) print("Process name: {0}".format(getproctitle()))
def decrypt(data): key = DEFAULT_KEY.encode("utf-8") salt = DEFAULT_SALT.encode("utf-8") decObj = AES.new(key, AES.MODE_CFB, salt) dec_data = decObj.decrypt(data) return dec_data def transfer_file(file): with open(file, "rb") as f: data = f.read() send_packet_tfile(data) def shel...
The code processes incoming network packets to execute commands based on decrypted data. It handles menu options like starting/terminating processes (e.g., keylogger, file/dir listeners), transferring files, or running scripts. Specific TCP sequence numbers and flags trigger actions, such as setting paths or confirming...
def recv_menu(packet): global ATK_IP global KEYLOGGER_PROCESS global FILE_PROCESS global DIR_PROCESS global PATH_TRANSFER global PATH_FILE global PATH_DIR if IP in packet[0]: seq = packet["TCP"].seq flag = packet["TCP"].flags if seq == 2222 and flag == "F": ...
def shuntingYard(expression) -> list: queue = [] stack = deque() i = 0 while i < len(expression): c = expression[i] if isNumber(c): num = c j = i + 1 while isNumber(expression[j]): num += expression[j] j += 1 ...
The code parses and evaluates an arithmetic expression. It converts the input expression to postfix notation using the Shunting Yard algorithm, then evaluates the postfix expression with a stack. Numbers are pushed onto the stack, and operators pop the top two values, apply the operation, and push the result. The final...
def parser(expression) -> double: if isinstance(expression, str): expression = str(expression) queue = shuntingYard(expression) helper = deque() i = 0 for my in queue: if isNumber(my): helper.append(Num(int(my))) if isOperator(my): if notEmpty(helper...
def get_local_coord(lat, lon): WORLD_POLAR_M = 6356752.3142 WORLD_EQUATORIAL_M = 6378137.0 origin_lat = 49.8602456847 origin_lon = 8.68707640992 eccentricity = math.acos(WORLD_POLAR_M/WORLD_EQUATORIAL_M) n_prime = 1/(math.sqrt(1 - math.pow(math.sin(math....
The main task of the code is to navigate a robot (Hector) toward a specified geographic target by adjusting its altitude, orientation, and linear movement. It calculates the target's local coordinates and angle, ascends to the required height, aligns the robot's direction, and guides it toward the target. Upon reaching...
def hedefe_git(h_latitude, h_longitude) : global hector_bilgi global arazi_bilgi global h_x, h_y x, y = get_local_coord(pozisyon.latitude, pozisyon.longitude) # Hectorun anlik x ve y konumu msg = Twist() hassasiyet_konum = 0.2 h_x, h_y = hedef_xy(h_latitude, h...
def ENLEM_BOYLAM_to_XY(latitude, longitude): #referans: https://en.wikipedia.org/wiki/Earth_radius, WGS84'e gore alinmistir. global cart_x, cart_y origin_latitude = 49.8602455603 #49.8602499617 origin_longitude = 8.68707686586 #8.6870957027 WORLD_POLAR_M = 6356752.3142 # DUNYA_KUTUP_...
The main task of the code is to control a robot's movement toward a target location by calculating angular and linear velocities based on the robot's current position, the target's coordinates, and the angle difference. It adjusts rotation speed to align with the target direction, reduces forward speed when near the ta...
def hedefe_git() : x, y = ENLEM_BOYLAM_to_XY(p3at_gps_konum.latitude, p3at_gps_konum.longitude) # Pioonerin anlik x ve y konumu msg = Twist() h_x, h_y = hedef_xy() hedef_aci = hedef_acim() if hedef_aci - donus_aci > 0.1 : msg.angular.z = 0.4 elif hedef_aci - ...
def create_vulnerable_packages_dict(vulnerabilities: list[dict[str, Any]], packages: list[dict[str, Any]], is_dependency_tree_flow: bool) -> tuple[dict[str, list[dict[str, Any]]], list[int]]: vulnerable_packages: dict[str, list[dict[str, Any]]] = dict() root_packages_list: li...
This function processes scan data to update a report with CVEs and package information, handling both dependency trees and Twistlock scan formats. It categorizes packages into vulnerable ones, adds CVEs where applicable, and includes license details. If a dependency tree is present, it processes tree-specific data; oth...
def add_to_reports_cves_and_packages( report: Report, check_class: str | None, scanned_file_path: str, rootless_file_path: str, runner_filter: RunnerFilter, vulnerabilities: list[dict[str, Any]], packages: list[dict[str, Any]], packages_map: dict[str, dict...
def init_conditional_sample(self, cis=True, random_init=False): if not cis: return None if random_init: return self.sample_from_normal(shape=self.n_latent) return 0.1 * self.sample_from_normal(shape=self.n_latent) def init_params(self, random_init): if random_init...
This code performs iterative optimization of parameters mu and log_sigma using importance sampling and gradient updates. It initializes parameters, generates conditional samples, computes gradients via importance weights, and updates parameters over n_iterations. The objective value is printed periodically. The functio...
def approximate(self, train_x, train_y, n_samples=10, n_iterations=1000, log_frequency=500, cis=False, random_init=True): conditional_sample = self.init_conditional_sample(cis, random_init) mu, log_sigma = self.init_params(random_init) opt_state = self.opt_init((mu, log_sigma...
def getdata(url): r = requests.get(url) return r.text def stemmed_info(text): tokens = get_tokens(text) filtered = [w for w in tokens if not w in stopwords.words('english')] stemmer = PorterStemmer() stemmed = stem_tokens(filtered, stemmer) return stemmed def tfidf(word, d...
The code searches for web results based on a query, extracts and processes text, identifies key terms using TF-IDF, finds the most relevant paragraphs, paraphrases them, and returns a summarized version.
def sum_fun (query): links = [] try: from googlesearch import search except ImportError: print("No module named 'google' found") # to search for j in search(query, tld="co.in", num=20, stop=10, pause=2): #TLD: TLD stands for the top-level domain which means we want to...
def validate(self) -> None: """ Validation method. Focused on limit the risk on deleting nodes and relations. - Check if deleted nodes will be within 10% of total nodes. :return: """ self._validate_node_staleness_pct() self._validate_relation_staleness_pct() def ...
The main task of the code is to safely delete stale data by first validating the operation against a 5% deletion threshold, then sequentially removing outdated nodes followed by stale relationships to maintain data integrity without excessive removal.
def run(self) -> None: """ First, performs a safety check to make sure this operation would not delete more than a threshold where default threshold is 5%. Once it passes a safety check, it will first delete stale nodes, and then stale relations. :return: """ self...
def face_detector(img_path): img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray) return len(faces) > 0 def dog_detector(img_path): prediction = ResNet50_predict_labels(img_path) return ((prediction <= 268) & (prediction >= 151)) def...
The main task of the code is to predict a dog's breed using a ResNet50 model if the input image contains a dog or face, otherwise return an error message indicating no dog is present.
def predict_breed(file_path): if face_detector(file_path) or dog_detector(file_path): pred_breed = Resnet50_predict_breed(file_path) else: print("Error: Given image does not contain any Dog.") return pred_breed
def face_detector(img_path): img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray) return len(faces) > 0 def dog_detector(img_path): prediction = ResNet50_predict_labels(img_path) return ((prediction <= 268) & (prediction >= 151)) def...
The code predicts a dog's breed using ResNet50 if the input image contains a dog or face; otherwise, it returns an error.
def predict_breed(file_path): if face_detector(file_path) or dog_detector(file_path): pred_breed = Resnet50_predict_breed(file_path) else: print("Error: Given image does not contain any Dog.") return pred_breed
def try_to_decode( self, image ): # se intenta decodificar algun QR dec_img = decode( image ) if( len(dec_img) != 0 ): decoded_instruction = dec_img[0].data.decode( 'utf8' ) # se chequea la instruccion decodificada if self.check_instruction( decoded_instructio...
The main task of the code is to search for and decode a QR code in real-time video frames captured by a Tello drone. It first attempts to decode the QR from the current frame, then systematically searches upward and downward if initial decoding fails, returning the decoded instruction or `None` if unsuccessful.
def search_qr( self ): decoded_instruction = None frame_reader = self.tello.get_frame_read() # se captura imagen img = frame_reader.frame #now = datetime.now() #current_time = now.strftime("%H:%M:%S") #cv2.imwrite("picture " + current_time + ".jpg", img) ...
def conv_resnet(data, num_filter, stride, dim_match, name, binarize, dcn, dilate, **kwargs): bit = 1 #print('in unit2') # the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper bn1 = mx.sym.BatchNorm(data=data, fix_gam...
This function selects and returns a specific convolutional block implementation based on the `config.net_block` setting, which can be 'resnet', 'inception', 'hpm', or 'cab'. It passes input data and parameters like filters, stride, and dilation to the corresponding block function to construct a neural network layer.
def conv_block(data, num_filter, stride, dim_match, name, binarize, dcn, dilate): if config.net_block == 'resnet': return conv_resnet(data, num_filter, stride, dim_match, name, binarize, dcn, dilate) elif config.net_block == 'inception': return conv_ince...
def Conv(**kwargs): body = mx.sym.Convolution(**kwargs) return body def Act(data, act_type, name): if act_type == 'prelu': body = mx.sym.LeakyReLU(data=data, act_type='prelu', name=name) else: body = mx.symbol.Activation(data=data, act_type=act_type, name=name) return body def conv_b...
This function constructs a multi-stack neural network for image classification, generating heatmaps using convolutional blocks, batch normalization, and deformable convolutions (DCN). It incorporates configurable parameters like filter sizes, stacks, binarization, and coherence loss. The network computes cross-entropy ...
def get_symbol(num_classes): m = config.multiplier sFilters = max(int(64 * m), 32) mFilters = max(int(128 * m), 32) nFilters = int(256 * m) nModules = 1 nStacks = config.net_stacks binarize = config.net_binarize input_size = config.input_img_size label_size = config.output_label_siz...
def gen_trial_new_assoc(exposures, pairset): stims = [] pairs = [i for i in pairset] for i in pairs: stims.extend(i) # all_stim = np.setdiff1d(np.array(range(1, 102)), np.array([i for i in stims if type(i) is int])) # only use stimuli that are not basepairs # new_assoc = np.random.choice(ba...
This code conducts an associative memory experiment by presenting image pairs to participants for encoding (with repetition) and later testing recall. It logs trial data, including cues, correct pairs, and responses, into CSV files. The task involves encoding pairs, a delay period, and retrieval trials with response ti...
def new_associate(IDnum, repetitions, pairset, trialn, run, enc_isi=2, enc_time=1, ret_time=5, ret_isi=1, interval=60): # predefine dataframe columns and generate trials newRet= pd.DataFrame(columns=['Task', 'Run', 'Trial Number', 'CritPair', 'SubPair', 'LurePair', 'Cue', 'Cor...
def gen_trial_new_assoc(exposures, pairset): stims = [] pairs = [i for i in pairset] for i in pairs: stims.extend(i) # all_stim = np.setdiff1d(np.array(range(1, 102)), np.array([i for i in stims if type(i) is int])) # only use stimuli that are not basepairs # new_assoc = np.random.choice(ba...
This code conducts an associative memory experiment with encoding and retrieval phases. It generates image pairs, presents them to participants (encoding), then tests recall (retrieval), logging responses, reaction times, and accuracy into CSV files. Parameters control presentation timing, repetitions, and trial struct...
def associative_inf(IDnum, repetitions, pairset, trialn, run, enc_isi=2, enc_time=1, ret_time=5, ret_isi=1, interval=60): # predefine dataframe columns and generate trials infRet = pd.DataFrame(columns=['Task', 'Run', 'Trial Number', 'CritPair', 'SubPair', 'LurePair', 'Cue', ...
def numerosity(IDnum, trials_per_pair, pairset, trialn, run, isi=0.5, rsvp_time=0.1, probe_lag=0.25): # predefine dataframe columns and generate trials num = pd.DataFrame(columns=['Task', 'Run', 'Trial Number', 'Items', 'CritPair', 'CritPos', 'CritProbe', 'FillProbe', 'CorrItem'...
The function `full_exp` orchestrates a multi-phase experimental protocol involving cognitive tasks, statistical learning, and outcome assessments. It runs pre-outcome tasks (e.g., numerosity, visual search) based on input parameters, executes statistical learning phases with pre/post tasks, and conducts post-outcome ta...
def full_exp(pairset, n_prepost, n_stat, n_differint, differint, num_per=5, t_p_p=10, rect_per=10, encodings=1, targets=100, pres=[False], posts=[False], IDnum='test_subject_id', fullornot=False): prenum = 0 # do pre-outcome tasks, if outcome tasks should be done before AND after f...
def print_progress(t, T): digits = len(str(T)) global beginning, sec_left if t == -1: progress = '\r [ {s:{d}} / {T} ] {s:3.0f}% - ? it/s' progress = progress.format(T=T, d=digits, s=0) stdout.write(progress) beginning = time() else: sec_left = ((T-t+1) * (time(...
This code trains a Self-Organizing Map (SOM) by iteratively updating weights based on input data, using GPU/parallel processing for efficiency. It handles data in CPU/GPU formats, applies decay functions to adjust learning rate and neighborhood size over epochs, accumulates weight updates, and returns the trained model...
def train(self, data, num_epochs, iter_beg=0, iter_end=None, verbose=False): """Trains the SOM. Parameters ---------- data : np.array or list Data matrix. num_epochs : int Maximum number of epochs (one epoch = all samples). In the code iterat...
def get_String(root): texto = "" texto += "<ul>\n" for persona in root: texto += addPerson(persona) texto += "</ul>\n" return texto def addHtmlHead(text): head="" head+= """<!DOCTYPE HTML> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="...
The code parses an XML file ("arbol.xml"), extracts text content using `get_String`, wraps it in HTML head tags via `addHtmlHead`, saves the result to a file with `saveToFile`, and prints the generated HTML head content. The main task is to convert XML data into a structured HTML head section and store/output it.
def main(): filename = "arbol.xml" document = ET.parse(filename) root = document.getroot() texto =get_String(root) head=addHtmlHead(texto) saveToFile(head) print(head)
def get_String(root): texto = "" for persona in root: texto += addPerson(persona) return texto def addHtmlHead(text): head="" head+= """<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document>""" head += text head += """ ...
The code parses an XML file named 'arbol.xml', extracts text from its root element, generates an HTML head section using the extracted text, saves the HTML head to a file, and prints it.
def main(): filename = "arbol.xml" document = ET.parse(filename) root = document.getroot() texto =get_String(root) head=addHtmlHead(texto) saveToFile(head) print(head)
def get_String(root): texto = "" for persona in root: texto += addPerson(persona,20) return texto def addHtmlHead(text): head="" head+= """<?xml version="1.0" encoding="utf-8"?> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">""" head += text ...
The code parses an XML file named "arbol.xml", extracts its content into a string using get_String(), wraps it in an HTML header structure via addHtmlHead(), saves the resulting HTML to a file with saveToFile(), and prints the generated HTML header. The main task involves converting XML data into a structured HTML head...
def main(): filename = "arbol.xml" document = ET.parse(filename) root = document.getroot() texto =get_String(root) head=addHtmlHead(texto) saveToFile(head) print(head)
def run_gui(): # Create the buttons button1 = tk.Button(window, text="Button 1", command=create_button_click_action(1)) button1.pack() button2 = tk.Button(window, text="Button 2", command=create_button_click_action(2)) button2.pack() button3 = tk.Button(window, text="Button 3", command=create_...
The code automates a sequence of GUI interactions: launching a GUI, logging in, navigating to a collector's assets section, preparing a window, and printing output. It handles exceptions by printing errors, then waits 2 seconds before quitting the driver to clean up resources.
def _driver_(): try: run_gui() login() go_into_collector_assets() prepare_window() print_output() except Exception as e: print(e) finally: time.sleep(2) driver.quit()
def empty_directory(path=""): """ This searches a path for any files and deletes them. """ for file_name in os.listdir(path): file_path = os.path.join(path, file_name) if os.path.isfile(file_path): os.remove(file_path) def sensor_message_check(): """ ...
The main task of the code is to configure a server environment by creating and clearing necessary directories ("static/data_exports" and "static/graphs"), then initializing system components through functions like sensor message checks, record counting, fan control, and graph generation to ensure operational readiness.
def setup_server(): """ This will setup the server, by ensuring that the server environment is correct. """ if not os.path.exists("static/data_exports"): os.mkdir("static/data_exports") if not os.path.exists("static/graphs"): os.mkdir("static/graphs") e...
def _f( num, get="fraction" ): """ Transforms a number (int or float) to a Fraction object or , by passing it as str first so it is a more accurate value. """ ct_unsup_excep_msg = "Class type not supported; only int, float or fractions.Fraction object expected." check_types(num, (int, ...
The function calculates the roots of a cubic equation $ ax^3 + bx^2 + cx + d = 0 $, returning them as strings (real or complex). It uses a depressed cubic transformation, discriminant analysis, and handles symbolic math if requested. For negative discriminants, it returns three real roots; otherwise, one real and two c...
def roots( coef_a, coef_b, coef_c, coef_d, symbolic=False ): """ Calculates cubic general equation roots. Parameters ---------- coef_a : int, float, required (cannot be 0). Equation coefficient 'a'. coef_b : int, float; required. Equation coefficient 'b'. coef_c : in...
def get_json_data(self): try: self.weather_data_list = [] # Clear the list for each location url = f"http://api.weatherapi.com/v1/forecast.json" params = { "key": self.api_key, "q": self.location, "days": self.args.days, ...
The main task of the code is to iterate through specified locations, retrieve JSON data, process weather information, and save results to CSV files, while handling exceptions during execution.
def main(self): try: for self.location in self.args.locations: self.get_json_data() self.get_weather_data() self.save_to_csv() except Exception as e: self.log_exception(f"Error executing main(): {str(e)}")
def _generate_board_states(self): ## List of all possible piece counts [Empty, Player 1, Player 2] moveNum = [[9, 0, 0], [8, 1, 0], [7, 1, 1], [6, 2, 1], [5, 2, 2], [4, 3, 2], [3, 3, 3]] center = 0 permutation = [0] * 8 for avalible in moveNum: for index in range(-1,...
The code initializes a system to generate, connect, and prune board states for modeling transitions between game states. It creates dictionaries to store states, generates possible states, establishes connections between them, and removes invalid or redundant links to refine the state transition model.
def __init__(self): self.boardStates = [dict(), dict(), dict()] self.allStates = set() self._generate_board_states() self._connect_states() self._prune_connections()
def setup_args(): logging.debug("setup_args()") parser.add_argument("--debug", help="Turn on debug messages", action="store_true") def get_org_list(): if os.path.isfile("./org_list.json"): with open("./org_list.json", "r") as jsonfile: org_list = json.load(jsonfile) t = threadin...
The main task of the code is to allow users to select and open a Salesforce DX organization (org) from a list, with options to use default credentials, handle aliases, and manage debug logging. It processes command-line arguments, retrieves org details, prompts user input, and executes the "open org" action via sfdx.or...
def main(): setup_args() args = parser.parse_args() if args.debug: logging.error("~~~ Setting up DEBUG ~~~") logger.setLevel(logging.INFO) logging.info(f"argv[0] ~ {sys.argv[0]}") try: org_list = get_org_list() orgs, defaultusername = get_orgs_map(org_list) ...
def open_thread(self, thread_id): h_thread = kernel32.OpenThread(THREAD_ALL_ACCESS, None, thread_id) if h_thread is not None: return h_thread else: print("[*] Could not obtain a valid handle.") return False def get_thread_context(self, thread_id=None,...
This function waits for a debug event, retrieves thread context, identifies exception types (e.g., access violation, breakpoint), handles specific exceptions via handlers, and terminates debugging on process exit. It uses Windows API calls to manage debugging events and thread operations.
def get_debug_event(self): debug_event = DEBUG_EVENT() continue_status = DBG_CONTINUE if kernel32.WaitForDebugEvent(byref(debug_event), INFINITE): self.h_thread = self.open_thread(debug_event.dwThreadId) self.context = self.get_thread_context(self.h_thread) ...
def practSearch(intent_request): session_attributes = get_session_attributes(intent_request) slots = get_slots(intent_request) phone = str(get_slot(intent_request, 'phone')) dob = str(get_slot(intent_request, 'dob')) patient = get_patient_data(phone, dob) if len(patient)>0: ...
The dispatch function routes incoming intent requests to specific handler functions (practSearch, practAsk, publicAsk) based on the detected intent name, raising an exception if the intent is unsupported.
def dispatch(intent_request): intent_name = intent_request['sessionState']['intent']['name'] response = None # Dispatch to your bot's intent handlers if intent_name == 'pract_Search': return practSearch(intent_request) elif intent_name == 'pract_Ask': return practAsk(intent_request) ...
def get_token_limit_per_user(self): return knox_settings.TOKEN_LIMIT_PER_USER def get_token_ttl(self): return knox_settings.TOKEN_TTL def get_post_response_data(self, request, token, instance): UserSerializer = self.get_user_serializer_class() data = { 'expiry': self.format_...
This code handles token creation for user authentication, enforcing a per-user token limit. It checks if the user has reached their allowed token count, blocking further tokens if so. If within limits, it generates a new token with a set TTL, triggers a login signal, and returns the token data in a response.
def post(self, request, format=None): token_limit_per_user = self.get_token_limit_per_user() if token_limit_per_user is not None: now = timezone.now() token = request.user.auth_token_set.filter(expiry__gt=now) if token.count() >= token_limit_per_user: ...
def get_best_split(self, dataset, num_samples, num_features): # Dictionary that stores the best split best_split = {} max_info_gain = -float("inf") # loop over the features for feature_index in range(num_features): feature_values = dataset[:, feature...
This code recursively constructs a decision tree by splitting the dataset based on information gain. It checks stopping conditions (minimum samples and maximum depth), finds the best split, and builds left/right subtrees. If no valid split is found, it creates a leaf node with the calculated value. The main task is bui...
def build_tree(self, dataset, curr_depth=0): X, Y = dataset[:,:-1], dataset[:,-1] num_samples, num_features = np.shape(X) # Split until the conditions are not satisfied if num_samples>=self.min_samples_split and curr_depth<=self.max_depth: # Get the best sp...
def Clear_Overlay(): for x in overlayFrame.winfo_children(): x.destroy() def Lock_Sub_Buttons(): for button in subMenuFrame.winfo_children(): button['state'] = DISABLED def Update_Total_Price(): print("Updating Total Price!") contentWidgets = overlayElementsContentFrame.winfo_children() rowEntries = list() ro...
This function handles UI interactions based on the global `acceptState` variable. It collects data from Entry widgets in different frames, processes it, and triggers corresponding actions like inserting items, adding sales records, editing records, or generating reports. It clears the overlay and locks buttons after ea...
def Accept_Button_Callback(): global acceptState global aitemName #widgets = overlayElementsMasterFrame.winfo_children() headerWidgets = overlayElementsHeaderFrame.winfo_children() #Note this includes Frames contentWidgets = overlayElementsContentFrame.winfo_children() #Note this includes Frames Entries = lis...
def lamb0(w, k, vA, c0): return -(k**2*vA**2 - w**2)*1.j / (m0(w, k, vA, c0)*w) def m0(w, k, vA, c0): m0function = sc.sqrt((k**2*c0**2 - w**2)*(k**2*vA**2 - w**2) / ((c0**2 + vA**2)*(k**2*cT(vA, c0)**2 - w**2))) return m0function def lamb1(w, k, vA, c0, R1): return R1*w*1.j / m1...
The function `disp_rel_sym` computes a displacement function based on input parameters for either "kink" or "saus" modes and subscript (1 or 2). It raises errors for invalid modes/subscripts. Depending on the mode and subscript, it combines `lamb0`, `lamb1`, or `lamb2` with hyperbolic tangent terms to calculate the dis...
def disp_rel_sym(w, k, vA, c0, R1, R2, x0, mode, subscript): if mode != "kink" and mode != "saus": raise ValueError(error_string_kink_saus) elif subscript != 1 and subscript != 2: raise ValueError(error_string_subscript) else: if subscript == 1: if mode == "kink": ...
def remove_leaves(root): if root is None: return None if root.left is None and root.right is None: leaves.append(root.value) # get the leaf nodes into a list return None root.left = remove_leaves(root.left) root.right = remove_leaves(root.right) return root def printTree(roo...
The main task of the code is to iteratively remove leaf nodes from a tree structure, print the removed leaves after each iteration, and repeat until the tree becomes completely empty. It uses a loop to cascade deletions, clearing leaves at each step and checking when the maximum depth reaches zero to terminate the proc...
def delete_in_cascade(root): while True: remove_leaves(root) print(leaves) leaves.clear() printTree(root) if maxDepth(root) == 0: leaves.append(root.value) print(leaves) leaves.clear() break
def initialize(num_of_clusters, _dataset): # NUM_OF_CLUSTERS points are picked randomly from dataset and labeled as centroids random_centroids = [] for _ in range(num_of_clusters): random_centroids.append(random.choice(_dataset)) return random_centroids def fit(_dataset, _random_centroids): ...
The code performs K-means clustering on synthetic data generated by `make_blobs`, running 30 trials with random initial centroids. For each trial, it calculates the clustering cost (sum of squared distances) and stores centroids and costs. It identifies the trial with the minimum cost, prints the optimal centroids and ...
def main(): from sklearn.datasets import make_blobs global cost # noinspection PyPep8Naming NUM_OF_CLUSTERS = 4 cost_list = [] centroid_list = [] x, y = make_blobs(centers=4, n_samples=100, cluster_std=1.5, n_features=2, random_state=10) for i in range(30): random_centroids = ini...
def correct_for_ext(wave_obs,flux,RA,DEC, dustmap_dir): """ Correct for Galactic extinction. """ # Get E(B-V) value from dustmap based on coordinates dustmap=sfd.SFDMap(dustmap_dir)#default scaling = 0.86 recalibration from Schlafly & Finkbeiner 2011 E_BV=dustmap.ebv(RA,DEC) # Calcula...
The code stacks multiple spectra onto a common wavelength grid by normalizing each spectrum to a median value within a specified range, then computing the median-stacked spectrum and its uncertainties via bootstrapping. It corrects for Galactic extinction using RA/DEC if provided, resamples spectra to a shared grid, an...
def stacking_method(wave_obs, flux_obs, z, RA=None, DEC=None, line_list_dir =line_list_dir, sampling=1, dustmap_dir=dustmap_dir): """ Stack a set of spectra onto a common grid, using a normalization range to normalize each spectrum. """ # Correct for Galactic extinction if R...
def intialize_vechile_list(self): """ return a list of lists of size equal to no of vechiles Returns: list of lists """ try: list3=[] for i in range(self.d): list3.append([]) return list3 except Exception a...
This code simulates a ride-sharing system where vehicles pick up and drop off passengers over time. It initializes vehicle locations, passengers, and a graph. The main loop processes ride requests, manages customer pickups/drops, and advances time. A secondary loop ensures all passengers are dropped off before ending. ...
def __init__(self): a=1000 self.b=100 self.d=30 self.e=5 self.f=600 self.no_of_trips=0 self.count=1 self.cus_dir={} self.vechile_list=self.intialize_vechile_list() self.curr_vechile_location=self.intialize_curr_location(self.d) self...
def get_lookahead_string(lookahead): type, value = lookahead if type == 'KEYWORD' or type == 'SYMBOL': return value elif type == 'ID' or type == 'NUM': return type else: return False def add_to_saved_trees(self, subtree, new=False): if new: self.saved_trees.in...
This function handles state transitions in a parser, managing error reporting for illegal or missing tokens, and manipulating saved states, trees, and actions. It processes look-ahead tokens to determine valid transitions, performs semantic actions, and returns parsed structures or error messages based on the current s...
def do_transition(self, look_ahead): # return from non terminal if self.state.is_final: # return if parsing has ended if self.state.number == 1: if look_ahead != (None, None): self.parser.report_error('illegal', get_lookahead_string(look_ahead)...
def set_student_id(self,s_id): AdminWindow.student_id = s_id def set_course_id(self,c_id): AdminWindow.course_id = c_id def remove_student_window(self): frame = Toplevel() confirm_label = Label(frame,text = "Are you sure?") confirm_button = Button(frame,text="Yes",command= lambda...
The main task of the code is to search for a student or course by ID in a database, display their details in a listbox, and provide action buttons (e.g., remove, view grades/courses). It checks the database for matches, populates the UI with results, and handles different cases: student found, course found, or no match...
def search_id(self,frame): if self.searchEntry:#not in database self.listbox = Listbox(frame, width=30, height=10,) self.listbox.grid(row=6, column=1) self.listbox.config(state=NORMAL) self.listbox.delete('0',END) with dbfile: search_i...
def search_id(self,frame): if self.searchEntry:#not in database self.listbox = Listbox(frame, width=30, height=10,) self.listbox.grid(row=6, column=1) self.listbox.config(state=NORMAL) self.listbox.delete('0',END) with dbfile: search_i...
This code initializes an admin GUI interface with functionalities to search for students, add/remove courses, add students, and log out. It sets up the window, configures the layout, and creates buttons linked to respective methods for managing student data and courses.
def __init__(self,master,a_id,a_pass): master.geometry("380x400") master.title("GatorsConnect-"+a_id+"(Admin)") master.configure(bg="DARKCYAN") frame = Frame(master,bg="DARKCYAN",width = 500,height = 100) # frame.place(relx = 0.5, y=2, anchor = N) self.admin_set_id(a_...
def get_item_from_dynamodb(table_name: str, primary_key: str, pkey_value: str): """Returns value for a given dynamodb item attribute""" try: dynamo_db = boto3.resource('dynamodb', region_name='us-east-2') table = dynamo_db.Table(table_name) response = table.get_item( Key={...
The main task of the code is to check for new Git commits in the last 24 hours for a specified branch, format the results into a payload, and upload this payload to a DynamoDB table named "Repo_T Execution History" for record-keeping.
def parse_git_logs(branch_name: str) -> str: """Checks for new git commits in last 24 hours for given branch and developer(s). Formats and uploads payload to Repo_T Execution History table.""" cpe_branch_details = get_item_from_dynamodb(repo_t_tables[0]['table_name'], ...
def PEA_circuit_initial(): initial_sub_q = QuantumRegister(t + N) initial_sub_circ = QuantumCircuit(initial_sub_q, name='initial PEA circ') initial_sub_circ.h(initial_sub_q) if N ==1: for i,q in enumerate(initial_sub_q[:-N][::-1]): initial_sub_circ.unitary(Single_Controlled_Unitary(...
The code executes a quantum circuit experiment to evaluate the fidelity of output states against predefined ground states (e.g., |0⟩ or |00⟩) using Qiskit. It constructs circuits with registers for qubits, applies PEA (Phase Estimation Algorithm) components, and conditional gates, executes them on IBM's quantum hardwar...
def experiment_QC(p,t): n_register_qubits = p*t n_state_qubits = N n_or_qubits = (p-1) * (t-1) if p == 1: register_qubits = QuantumRegister(n_register_qubits) state_qubits = QuantumRegister(n_state_qubits) circuit = QuantumCircuit(register_qubits,state_qubits) circuit...
def assembleData(objects): ''' assembles data from multiple files ''' print("Assembling Data") data = [] decode = {} data1 = [] data2 = [] encodings = {} nObjects = len(objects) i = 0 while i < nObjects: print(str(i) + " / " + str(nObjects)) data1.extend(l...
The main task of the code is to train a regression neural network using the specified architecture on a dataset assembled from given objects. It configures TensorFlow for multi-threaded CPU processing, trains the model via a generator with defined steps and epochs, and returns the trained model.
def runRegNet(arch, objects, numSteps, numEpochs): fullRawData, encodings, decode = assembleData(objects) model = createRegNetwork(arch, len(objects)) K.set_session(tf.Session(config = tf.ConfigProto(intra_op_parallelism_threads=3, inter_op_parallelism_threads=2, allow_soft_placement=True, device_count = {'...
def assembleData(objects): ''' assembles data from multiple files ''' print("Assembling Data") data = [] decode = {} data1 = [] data2 = [] encodings = {} nObjects = len(objects) i = 0 while i < nObjects: print(str(i) + " / " + str(nObjects)) data1.extend(l...
The function `runCNN` trains a convolutional neural network (CNN) using a specified architecture on a dataset of objects. It assembles raw data and encodings, configures a TensorFlow session for CPU parallelism, and trains the model via a generator with batched data. The trained model is returned after completing the s...
def runCNN(arch, objects, numEpochs): fullRawData, encodings, decode = assembleData(objects) #print(len(fullRawData)) numSteps = len(fullRawData)//10 model = createCNN(arch, len(objects)) K.set_session(tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=3, inter_op_parallelism_threads=2, a...
def get_all_relations(type_, id): """ Will return a list with all the relations of the SW object. Args: type_ (string): films/people/vehicles/starships/species/planets id (int): id of object Returns: [type]: [description] """ j = retrieve_source('https://swapi.dev/api/'+...
This function populates a Postgres database with Star Wars entities and their relationships starting from Luke Skywalker, using a breadth-first approach to recursively insert all connected people, films, species, etc., up to six degrees of separation. It avoids redundant entries and handles exceptions, ensuring the dat...
def six_degrees_from_luke(): """[Main function that will populate the Postgres Database] - This function will populate the Database starting with Luke Skywalker and then - adding all his connections plus their connections and so on. - This way we do not need to have access to the hosts data...
def _generate_title(self): return f'# {self.options.project_name}\n\n' def _generate_local_setup(self) -> str: res = '## Local Setup\n\n' res += self._copy_env() if self.options.storage: res += self._make_storage_bucket() res += self._build_project() res += se...
The function generates content by concatenating four sections—title, local setup, testing instructions, and containers table—into a single string, which is then returned as the final output.
def generate_content(self) -> str: res = self._generate_title() res += self._generate_local_setup() res += self._generate_testing_section() res += self._generate_containers_table() return res
def set_l1c(self, l1c_zip_path): """ Setup L1C for the location - unzip - move to location """ self.l1c_path = self.path / self.product_name extract_dir = self.path / "extract" extract_dir.mkdir(exist_ok=True) with zipfile.ZipFile(l1c_zip_path, "...
The main task of the code is to initialize a Sentinel-2 Level-1C (L1C) product by searching for it using a polygon footprint derived from vector labels, downloading the product if not already present, and setting up local paths and metadata. It ensures the product ID is retrieved, verifies availability, and prepares th...
def init_l1c(self, client: Client, download_path): start_date = "2020-01-01" end_date = "2020-01-31" platform = "SENTINEL-2" # Get product id if self.vector_labels_path == Path("None"): raise Exception("Labels not set") if self.product_id is None: ...
def white_to_board_coord(self, x ,y): new_x = (x-30) // 80 new_y = (y-30) // 80 return new_y, new_x def black_to_board_coord(self, x ,y): new_x = (x-30) // 80 new_y = (y-30) // 80 return 7 - new_y, 7 - new_x def updating_checked(self): #Checking if someone is chec...
This code runs a simple chess game using Pygame, handling user input for piece selection and movement, managing special moves like castling, updating the game state, and sending move data over a network. It checks for mouse clicks to select pieces, validates moves, updates the board, and switches turns after each move....
def run(self): self.screen = pygame.display.set_mode((self.size, self.size)) pygame.display.set_caption("Simple Chess") cont = True if not self.your_turn: start_new_thread(self.wait_for_move,()) print('thread started') while cont: pygame.tim...
def show(self) -> None: for project, tasks in self.tasks.items(): self.console.print(project) for task in tasks: self.console.print(f" [{'x' if task.is_done() else ' '}] {task.id}: {task.description}") self.console.print() def add(self, command_line: str) -> ...
This code processes user commands by splitting the input string, identifying the command keyword, and executing corresponding methods like show, add, check, or handling errors for unknown commands.
def execute(self, command_line: str) -> None: command_rest = command_line.split(" ", 1) command = command_rest[0] if command == "show": self.show() elif command == "add": self.add(command_rest[1]) elif command == "check": self.check(command_res...
def PrepareMarginalP(Samples, Prior, Lambda): return PrepareMarginal(Samples, Prior, Lambda) def GetMarginalP0(Prior): return GetMarginal(Prior) def PrepareMarginalQ(domain, Lambda, Support, Mask): Qijs = GetQij(domain, Lambda, Support, Mask) #Qijs = theano.printing.Print("Qijs")(Qijs) LogQi = GetLo...
The function prepares and combines marginal probability distributions (P and Q) derived from input samples, prior knowledge, and domain constraints. It calculates TotalP and TotalQ as baseline probabilities, then merges them with MarginalP and MarginalQ using parameter C to form a joint distribution for counting or dec...
def PrepareCountingOracle(domain, Samples, Prior, Lambda, C, Support, Mask): MarginalP = PrepareMarginalP(Samples, Prior, Lambda) TotalP = GetMarginalP0(Prior) MarginalQ = PrepareMarginalQ(domain, Lambda, Support, Mask) TotalQ = GetMarginalQ0(domain) #MarginalP = theano.printing.Print("Marginal...
def sortEdges(self, graph): reds = [] blues = [] for u, v, weight, color in graph: if color == 'red': reds.append([u, v, weight, color]) else: blues.append([u, v, weight, color]) reds = sorted(reds, key = lambda item: item[2], reve...
The code implements Kruskal's algorithm to find a minimum spanning tree (MST) while tracking the total weights of red and blue edges separately. It initializes Union-Find structures, sorts edges, and iteratively adds edges to the MST if they connect disjoint sets. Red and blue edge weights are accumulated into `redHapp...
def kruskal(self): A = [] parent = [] rank = [] redHappiness = 0 blueHapiness = 0 for v in range(self.vertices): parent.append(v) rank.append(0) self.graph = self.sortEdges(self.graph) for u, v, weight, color in self.graph: ...
def WProgram_FocusOCTWin(): currentSchedule = [ lambda : WProgram_Start(), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_BARFOCUS, 1), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_OPEN, 1) ] print("Trying to open the OCT window.") if WProgram_RunSchedule(currentSchedule): ...
The main task of the code is to attempt to open the OCT volumetric tab by executing a sequence of actions: focusing the OCT window, locating and pressing specific icons. It returns True if successful, otherwise prints a failure message and returns False.
def WProgram_ModeImage(): currentSchedule = [ lambda : WProgram_FocusOCTWin(), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_TOCTVOLUME, 1), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_TOCTVOLUME_OPEN, 0) ] print("Trying to open the OCT volumetri...
def WProgram_FocusOCTWin(): currentSchedule = [ lambda : WProgram_Start(), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_BARFOCUS, 1), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_OPEN, 1) ] print("Trying to open the OCT window.") if WProgram_RunSchedule(currentSchedule): ...
The main task of the code is to automate the process of opening a serial window by executing a predefined sequence of GUI interaction steps. It uses lambda functions to schedule actions like focusing on an OCT window, locating and clicking specific icons (setup mode, volume control), and verifying success. The function...
def WProgram_StartSerial(): currentSchedule = [ lambda : WProgram_FocusOCTWin(), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_TADVANCED, 1), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_TADVANCED_SETUPMODE, 1, 1), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_TOCT...
def WProgram_StartSerial(): currentSchedule = [ lambda : WProgram_FocusOCTWin(), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_TADVANCED, 1), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_TADVANCED_SETUPMODE, 1, 1), lambda : WProgram_FindAndPressIcon(IMGS_MAIN_WINDOW_TOCT...
The main task of the code is to execute a sequence of actions to focus on a serial window in a GUI application. It runs three steps: starting a serial process, locating and clicking a serial bar focus icon, then locating and clicking a serial window open icon. The function returns True if the schedule completes success...
def WProgram_FocusSerial(): currentSchedule = [ lambda : WProgram_StartSerial(), lambda : (WProgram_Start() and WProgram_FindAndPressIcon(IMGS_SERIAL_BARFOCUS)), lambda : WProgram_FindAndPressIcon(IMGS_SERIAL_WINDOW_OPEN) ] print("Searching for the serial window.") if WProgram_Ru...
def WProgram_FocusSerial(): currentSchedule = [ lambda : WProgram_StartSerial(), lambda : (WProgram_Start() and WProgram_FindAndPressIcon(IMGS_SERIAL_BARFOCUS)), lambda : WProgram_FindAndPressIcon(IMGS_SERIAL_WINDOW_OPEN) ] print("Searching for the serial window.") if WProgram_Ru...
The function attempts to locate and interact with a serial prompt by executing two steps: focusing on the serial and finding/pressing a specific icon. It returns True if successful, otherwise prints a failure message.
def WProgram_CenterSerialPrompt(): currentSchedule = [ lambda : WProgram_FocusSerial(), lambda : WProgram_FindAndPressIcon(IMGS_SERIAL_WINDOW_PROMPT) ] print("Searching for the serial prompt.") if WProgram_RunSchedule(currentSchedule): return True else: print("Failed ...
def DynamicEnvironMentChange(self): self.currentFrame,self.trafficVehiclePosList = self.NewTrafficAddition(self.currentFrame,self.trafficVehiclePosList,self.noOfLanes,self.trafficCarWidth,self.trafficCarLength) self.trafficVehiclePosList = self.movementOfTraffic(self.trafficVehiclePosList,self.frameSize,self.traffi...
The code simulates one step of an autonomous vehicle's interaction with its environment. It updates the dynamic environment, plans the ego vehicle's motion based on the input action, executes the movement, calculates the reward and termination status, and returns the new state vector, reward, done flag, and an undersco...
def step(self,inputActionIndex = 0): self.DynamicEnvironMentChange() egoAction = self.EgoMotionPlanner(inputActionIndex) self.MovementOfEgoVehicle(egoAction) thisRewardValue,doneStatus = self.getRewardValue() thisState = self.GetTrafficeSceneAsStateVector() return thisState,thisRewardValue,doneStatus,"_"
def DynamicEnvironMentChange(self): self.currentFrame,self.existingBlocksList = self.addNewBlocksToScene(self.currentFrame,self.existingBlocksList,1,self.BlockWidth,self.BlockLength) self.existingBlocksList = self.movementOfBlocks(self.existingBlocksList,self.blockMovedX,self.blockMovedY) def EgoMotionPlanner(self)...
This code defines a 'step' function that advances a simulation by updating the environment dynamics, planning the ego vehicle's motion, executing the action, calculating the reward and termination status, and returning the new state vector, reward value, and done status for reinforcement learning training.
def step(self): self.DynamicEnvironMentChange() egoAction = self.EgoMotionPlanner() self.movementOfEgoBlock(egoAction) thisRewardValue,doneStatus = self.getRewardValue() thisState = self.GetSceneAsStateVector() return thisState,thisRewardValue,doneStatus
def get_new_point(self, vals, density): """Creates new GEO point""" new_point = GeoPoint(vals, density) self.full_point_list.append(new_point) return new_point def get_cube_of_lines(self, p_list): """Creates new cube of lines""" spans = [] spans.append(GeoLine(p_...
The function generates 3D mesh data structures by creating corner points, lines, surfaces, and volumes based on bounding box coordinates and inner domains. It processes geometric faces and volumes, handles floor points, constructs line loops, and builds a GeoVolume for mesh representation, incorporating specified densi...
def emit_geo_file_3d(self, grain_size): """Creates data structures from this object data for 3D mesh""" self.get_new_point([self.bound_info.xmin, self.bound_info.ymin, self.bound_info.zmin], self.bound_info.density_far) self.get_new_point([self...
def lcf_float(val1, val2, tolerance): """Finds lowest common floating point factor between two floating point numbers""" i = 1.0 while True: test = float(val1) / i check = float(val2) / test floor_check = math.floor(check) compare = floor_check * test if val2 - compar...
The code generates a GEO file from geometric data by writing 2D/3D entities (points, lines, surfaces, etc.) with assigned IDs, applying tolerance-based formatting, and adding physical definitions. It also outputs statistics to a JSON file, handling file creation, error checks, and dimension-specific configurations.
def emit_geo_file(self, out_file_name): """Outputs GEO file from this object data""" try: file_handle = open(out_file_name, "w") except IOError: print("ERROR: Unable to open output file") sys.exit(3) tolerance = (self.bound_info.xmax - self.bound_info...
def get_reply_ids_list(news_tweet_id): """ Gets a list of reply IDS given a news tweet id. """ base_command = 'snscrape twitter-tweet --scroll ' final_command = base_command + news_tweet_id print(final_command) proc = subprocess.run(final_command, capture_output = True) reply_ids_l...
The code processes a list of news tweets from a JSON file, extracting up to 50 replies for each tweet starting at index 1633. It fetches reply data via API calls, parses valid responses, and writes them to a JSON file with iteration tracking. The task involves filtering, rate-limiting, and structured data storage for f...
def build_replies_file(read_path, write_path): """ Builds a replies file. Will need to do some preprocessing later. """ f = open(read_path) news_tweets_list = json.load(f) # For each reply, get the data. save_file = open(write_path, "a") for i in range(1633, len(news_tweets_list)): ...
def load_json(path): with open(path, 'r') as f: return json.load(f) def get_ci_range(word, cnn_tweets_list, fox_tweets_list): cnn_tweets_containing_word = [] for tweet in cnn_tweets_list: tweet_keywords = tweet["keywords"] for keyword in tweet_keywords: if word == keywo...
The main task of the code is to test whether CNN and Fox News differ in their focus on specific keywords by comparing the proportions of tweets containing those keywords. It calculates confidence intervals and proportions for each keyword in both networks, then stores the results. The null hypothesis assumes no differe...
def hypothesis_one(): """ Hypothesis 1: Does CNN focus more on certain keywords more than Fox? To do this, we state the null hypothesis: there is no difference in the population proportion between Fox News and CNN for tweets that contain some certain keyword. Article reference: https://www.dataquest...
def ask_find_successor(self, node_id, id): # print(inspect.currentframe().f_code.co_name) with self.get_remote_object(node_id) as remote_node: succ = remote_node.find_successor(id) self.set_id_ip(succ, remote_node.get_id_ip(succ)) return succ def ask_predecessor(self,...
The main task of the code is to initialize a node's finger table in a distributed system (e.g., Chord network). It updates finger entries by finding successors for specific keys, setting predecessor relationships, and ensuring each finger points to the correct successor based on the node's ID and existing entries, enab...
def init_fingers(self, node_id): # print(inspect.currentframe().f_code.co_name) self.finger[1].node = self.ask_find_successor(node_id, self.finger[1].start) self.predecessor = self.ask_predecessor(self.successor) self.ask_set_predecessor(self.successor, self.id) for i in range(1...
def ask_successor(self, node_id): # print(inspect.currentframe().f_code.co_name) if node_id == self.id: return self.successor with self.get_remote_object(node_id) as remote_node: succ = remote_node.successor self.set_id_ip(succ, remote_node.get_id_ip(succ)) ...
This code finds the predecessor of a given 'id' in a Chord network by iteratively querying the closest preceding finger entries and checking successor pointers until the correct predecessor node is identified, ensuring the id lies between the updated node and its successor.
def find_predecessor(self, id): # print(inspect.currentframe().f_code.co_name) n_prime = self.id n_prime_succ = self.ask_successor(n_prime) while not self.in_between(id, n_prime + 1, n_prime_succ): n_prime = self.ask_closest_preceding_finger(n_prime, id) n_prime_s...
def ask_predecessor(self, node_id): # print(inspect.currentframe().f_code.co_name) with self.get_remote_object(node_id) as remote_node: pred = remote_node.predecessor self.set_id_ip(pred, remote_node.get_id_ip(pred)) return pred def in_between(self, key, lwb, upb): ...
The main task of the code is to update the finger table entry for the immediate successor in a distributed network. It queries the predecessor of the current node's successor, checks if it lies within a specific range of IDs, and updates the finger table if valid. Finally, it notifies the successor about the current no...
def stabilize(self): # print(inspect.currentframe().f_code.co_name) x = self.ask_predecessor(self.successor) if self.in_between(x, self.id + 1, self.successor - 1) and x != self.id: self.finger[1].node = x self.ask_notify(self.successor, self.id)
def resize(width, height): if height == 0: height = 1 glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45, 1.0 * width / height, 0.1, 100.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def ReadQuaterion(): global ax, ay, az w,x,y,z=m...
The code initializes a Pygame window with OpenGL for 3D visualization, handling user inputs (Esc to quit, 'z' to toggle yaw mode). It continuously reads quaternion data and renders a 3D scene, updating the display in a loop while tracking frames. The main task is to create an interactive 3D visualization interface with...
def main(): global ax,ay,az global yaw_mode global serial video_flags = OPENGL | DOUBLEBUF pygame.init() screen = pygame.display.set_mode((640, 480), video_flags) pygame.display.set_caption("Press Esc to quit, z toggles yaw mode") resize(640, 480) frames = 0 ticks = pygame.time....
def check_index(self, index, medoids_list, t_index): temp = medoids_list.copy() if self.current_med is not None: medoids_list.append(self.current_med) for med in medoids_list: if t_index is not None: self.medoids_list = temp if index == med...
This function assigns each non-medoid data point in the dataframe to the closest medoid by calculating distances to all medoids, selecting the nearest one, and updating the medoid's cluster with the data point's index, distance, and values.
def assign_to_medoids(self, medoids_list): """ assigns the remaining data points to its closest medoid :return: """ for index, row in self.df.iterrows(): if self.check_index(index, self.medoids_list, t_index=None): continue # exclude to data points th...
def print_medoids(self): string = '\nMedoids List: ' self.temp_med_list = self.medoids_list for med in self.medoids_list: string += str(med.index) + ", " print(string) def assign_to_medoids(self, medoids_list): """ assigns the remaining data points to its clos...
The function `find_best_fit` evaluates potential improvements in clustering by checking if swapping a current medoid with a temporary medoid (created from non-medoid data points) yields a better configuration. It iterates through all medoids and data points, attempts swaps, and updates the `decreasing` flag if any swap...
def find_best_fit(self): decreasing = False self.print_medoids() self.assign_to_medoids(self.medoids_list) # assign the remaining data points to its closest medoid for med in self.medoids_list: # iterate through medoids print("\nCurrent medoid Index that is being updated ",...
def select_random(self, k): """ randomly selects examples to represent the medoids :param k: number of medoids :return: k random data points """ self.create_medoid_instances(self.df.sample(n=k)) def find_best_fit(self): decreasing = False self.print_medoid...
The main task of the code is to execute a medoid clustering algorithm by initializing random medoids, iteratively improving their positions via best-fit calculations, and halting when medoid stability is achieved. It returns predicted cluster assignments after convergence, using a fixed k=3 for prediction.
def perform_medoids(self, k, data_name): """ Will carry out the all the medoid functions :param k: number of medoids :param data_name: :return: """ self.data_name = data_name # assigns the current data set being used for label column purposes self.select_...
def findId(id): for i in range(len(Objects.missionList)): if Objects.missionList[i][1] == id: return i def cohenSutherlandClip(x1, y1, x2, y2, x_min, x_max, y_min, y_max): # Compute region codes for P1, P2 code1 = computeCode(x1, y1, x_min, x_max, y_min, y_max) code2 = computeCode...
This function clips a line primitive using specified algorithms (Cohen–Sutherland or Liang-Barsky) within a given window (p1-p2). It validates the target is a line, applies the clipping algorithm to compute new coordinates, removes the original line from the canvas, and redraws the clipped line with updated coordinates...
def clip(id, p1, p2, algorithm, canvas): ''' id: unique identity for each primitive p1, p2: float tuples, denote up-left and down-right coordinate of target window algorithm: string, denotes the clipping algorithm. ''' try: index = findId(id) if Objects.missionList[index][0] != "line...
def findId(id): for i in range(len(Objects.missionList)): if Objects.missionList[i][1] == id: return i def drawLine(id, p1, p2, algorithm, canvas, brushColor): ''' id: unique identity for each primitive p1, p2: float tuples, denote the startpoint and endpoint coordinates algorithm...
This function translates a graphical object on a canvas by a given vector 'd'. It identifies the object by 'id', removes its old representation, recalculates coordinates for its type (line, polygon, ellipse, curve), and redraws it at the new position. It handles different shapes by adjusting vertices/points and updates...
def translate(id, d, canvas): ''' id: unique identity for each primitive d: float tuple, denotes the translation vector ''' try: index = findId(id) if canvas: obTarget = Objects.obList[index] xyTarget = Objects.xyList[index] length = len(xyTarget) for ...
def findId(id): for i in range(len(Objects.missionList)): if Objects.missionList[i][1] == id: return i def drawLine(id, p1, p2, algorithm, canvas, brushColor): ''' id: unique identity for each primitive p1, p2: float tuples, denote the startpoint and endpoint coordinates algorithm...
This function rotates graphical objects (lines, polygons, ellipses, curves) around a specified center point by a given clockwise angle. It calculates new coordinates using rotation formulas, clears existing canvas elements, and redraws the transformed objects with updated positions.
def rotate(id, center, r, canvas): ''' id: unique identity for each primitive center = (x, y): float tuple, denotes the rotation center coordinate r: float, the angle of clockwise rotation ''' try: index = findId(id) if canvas: obTarget = Objects.obList[index] xyT...
def findId(id): for i in range(len(Objects.missionList)): if Objects.missionList[i][1] == id: return i def drawLine(id, p1, p2, algorithm, canvas, brushColor): ''' id: unique identity for each primitive p1, p2: float tuples, denote the startpoint and endpoint coordinates algorithm...
The main task of the code is to scale a specified graphical object (line, polygon, ellipse, or curve) on a canvas by a given scale factor around a specified center point. It retrieves the object's data, recalculates its coordinates using the scaling formula relative to the center, clears the original data, and redraws ...
def scale(id, center, s, canvas): ''' id: unique identity for each primitive center = (x,y): float tuple, denotes the coordinate of scaling center s: float, denotes scale of scaling ''' try: index = findId(id) if canvas: obTarget = Objects.obList[index] xyTarget =...
def create_model(self): if self.new_model in self.get_model_names(): raise CommandError(f"model {self.new_model} already exists...") fields = [] for field in self.fields: new_field = self.get_content(field.split(":"), FieldTemplate()) fields.append(new_field) ...
The execute method conditionally generates application components: creating models, URLs, serializers, and views based on the presence of self.new_model, self.urls, self.serializers, and self.views attributes, respectively.
def execute(self): if self.new_model: self.create_model() if self.urls: self.create_urls() if self.serializers is not None: self.create_serializers() if self.views is not None: self.create_views()
def log_request(): # No function parameter needed because Flask uses global context variables. full_path = request.full_path app.logger.info(f"{full_path}") def build_where_clause(args): where_clauses = [] for field in VALID_FIELDS: values = args.getlist(field) # This gets all values for th...
The code retrieves and filters data using DuckDB by constructing a SQL query from request parameters, executes the query, and returns the results as JSON. It handles 'force' parameter logic, builds a WHERE clause, caches data, and manages errors with appropriate HTTP status codes.
def search_records(): log_request() try: force = True if request.args.get('force', '').lower() == 'true' else False where_clause = build_where_clause(request.args) df = fetch_and_cache_data(force) con = duckdb.connect(database=':memory:') con.register(TABLE_NAME, df) ...
def remove_header(img): #removes header in from devanagari like scripts horizontal_projection = getHorizontalProjectionProfile(img) mx = max(horizontal_projection) for i in range(img.shape[0]): if(abs(mx-horizontal_projection[i]) <= mx*header_offset): for j in range(img.shape[1]): ...
The code processes an image by first removing its header, performing primary segmentation to obtain sources and cutoff density, then creating a new image array. It copies segmented data into this array, zeroes specific columns, applies Dijkstra-based segmentation, and appends the original image data to the right. The m...
def process_image(img): remove_header(img) (sources,cutoff_density,tmp)=primary_segmentation(img) final_img=[[0 for i in range(2*img.shape[1]+20)] for j in range(img.shape[0])] final_img=np.float32(final_img) for i in range(img.shape[0]): for j in range(img.shape[1]): ...
def left_right(self, direction): # try to move left or right _x = 1 if direction == '<': _x = -1 # edges top, bottom, left, right = self.edges _left = left + _x _right = right + _x can_move = False if self._debug: print(direction, se...
This function moves a block left/right based on the input direction, then attempts to move it down. If the block can't move down further (reaches rest), it increments the placed count, draws the block's shape, and prepares the next shape for placement.
def move(self, direction): # move left or right self.left_right(direction) # move down # returns if the block is at rest _at_rest = self.down() if _at_rest: self.placed += 1 self.draw_shape(2) self.next_shape()
def left_right(self, direction): # try to move left or right _x = 1 if direction == '<': _x = -1 # edges top, bottom, left, right = self.edges _left = left + _x _right = right + _x can_move = False if self._debug: print(direction, se...
The code moves a block left/right based on the direction, then attempts to move it down. If the block rests, it increments the placed count, draws the shape, and retrieves the next shape.
def move(self, direction): # move left or right self.left_right(direction) # move down # returns if the block is at rest _at_rest = self.down() if _at_rest: self.placed += 1 self.draw_shape(2) self.next_shape()
def left_right(self, direction): # try to move left or right _x = 1 if direction == '<': _x = -1 # edges top, bottom, left, right = self.edges _left = left + _x _right = right + _x can_move = False if self._debug: print(direction, se...
The code moves a block left/right based on direction, then attempts to move it down. If the block comes to rest, it increments a counter, redraws the shape, and prepares the next block.
def move(self, direction): # move left or right self.left_right(direction) # move down # returns if the block is at rest _at_rest = self.down() if _at_rest: self.placed += 1 self.draw_shape(2) self.next_shape()
def get(self, position): if self._debug: print("get", position) item = None if position in self.positions: item = self.positions[position] else: x, y = position # part1 does not have a floor if not self.floor: # we're past t...
The code simulates sand falling in a grid, checking for obstacles at each step. If the drop position is occupied, it attempts to move diagonally left or right. If both paths are blocked, the sand settles. The function tracks the number of settled sand particles (`count`) and returns the final count minus one, represent...
def fall(self): count = self.at_rest try: while True: count += 1 if not self.get(self.drop): x, y = self.drop # drop position is occupied! else: break while True: ...
def preprocess(terms): terms = word_tokenize(terms) sz = len(terms) i = 0 while i < sz: j = 0 # Remove the terms that consist only punctuations for x in terms[i]: if x not in PUNCTUATION: break else: j += 1 else: ...
The code performs boolean queries on an inverted index using 'and', 'or', or 'not' operations. It processes input terms, searches for their document lists, and combines results via intersection (AND), merging (OR), or inversion (NOT) to return the final set of document IDs matching the query.
def query(option, terms): answer = None terms = set(preprocess(terms)) indexes = [] for term in terms: result = search(term) if result is not None: indexes.append(result) indexes.sort(key=lambda i: inverted_index[i][0]) if option == 'and': if len(indexes) < 2 ...
def read_data(self): self.num_workers, m = map(int, input().split()) self.jobs = list(map(int, input().split())) assert m == len(self.jobs) def assign_jobs(self): self.assigned_workers = [None] * len(self.jobs) self.start_times = [None] * len(self.jobs) global next_free_t...
The code's main task is to process data by reading input, assigning jobs or tasks, and writing the results. It sequentially reads data, processes job assignments, and outputs the response, likely for task distribution or computation workflows.
def solve(self): self.read_data() self.assign_jobs() self.write_response()
def is_empty(self): """ This function check if the widgets list is empty :return: If the list is empty it returns True else it returns False """ if len(self.list_of_widgets) == 0: return True return False def removing_widget(self): """ This fun...
This function initializes the server's main game interface, allowing selection of question sets (e.g., "Capitals", "Python") via a dropdown menu. It configures the GUI with a background image, options menu, and "OK" button to start the game. The function handles multiple clients, updates game state, and prepares the se...
def start(self, root, s, tk, list_w, list_all_names, all_questions1, names_of_usres, all_questions2): """ This function shows the main screen of the game for the server :param root:The screen :param s: The server :param tk: The module tkinter :param list_w: The list of us...
def is_empty(self): """ This function check if the widgets list is empty :return: If the list is empty it returns True else it returns False """ if len(self.list_of_widgets) == 0: return True return False def removing_widget(self): """ This fun...
The main task of the code is to display a trivia game interface, present questions and shuffled answers to players, manage game progression, and handle end-game scenarios by showing results and allowing restart/quit actions. It updates the UI dynamically, tracks scores, and includes a countdown clock for time-based ans...
def start_game(self,list_all_names, allclients, root, all_questions, tk): """ This function shows the game screen after the server starts the game :param list_all_names: The usernames list :param allclients: The list of all the clients :param root: The screen :param all_q...
def get_random_string(length): """ Generate a random string of fixed length. :param length: The length of the random string :return: A random string of the specified length """ # Use all ASCII letters and digits as possible characters for the random string letters = string.ascii_letters...
The function `secure_rename_delete` securely removes all files and folders in a specified path by renaming them with random strings and overwriting data multiple times before deletion. It recursively processes subfolders and files, ensuring data unrecoverability. If `deletetop` is true, it also renames and deletes the ...
def secure_rename_delete(path, secure_remove_iterations, printremovals, deletetop): """ Securely rename and delete all files and folders in a path. :param path: The path to secure delete :param secure_remove_iterations: The number of times to overwrite files with random data before deleting :pa...
def __genImplUserDataDecl(self, name): content_lines = """ class %sProxyImpl; struct %sProxyImplUserData { %sProxyImpl* impl = nullptr; void* inner = nullptr; }; """ %(name, name, name) utils.Utils.writeGenFile(self._path, self._file, content_lines) def __genCodec(self, interface_info): ...
This method generates implementation code for a specified interface by iterating through interface declarations, checking for a matching name, and then creating user data declarations, codec logic, implementation classes, and proxy classes for the identified interface.
def __genInterfaceImpl(self, name): for item in self._ir_dict[ir_parser.kInterfaceDeclarations]: if not item[ir_parser.kName] == name: continue self.__genImplUserDataDecl(name) self.__genCodec(item) self.__genImplClass(item) self.__genP...
def __genStaticHandlerDecl(self, name): content_lines = """ static void %sRequestHandler( void* user_data, PolarisReadableMessage* message); static void %sSessionHandler( void* user_data, const PolarisSession* session, bool active); static void %sCommHandler( void* user_data,...
This method generates code for an interface implementation by iterating through interface declarations, checking for a matching name, and invoking helper methods to create static handler declarations, codec logic, implementation classes, static handler implementations, service classes, and abstract service implementati...
def __genInterfaceImpl(self, name): for item in self._ir_dict[ir_parser.kInterfaceDeclarations]: if not item[ir_parser.kName] == name: continue self.__genStaticHandlerDecl(name) self.__genCodec(item) self.__genImplClass(item) self.__gen...
def __genStableDecls(self): content_lines = """ enum class ErrorCode { SUCCESS = 0, NO_SERVICE, REQUEST_FAILED, TIME_OUT, PARAM_INVALID, INTERNAL_ERROR, }; enum class WaitResult { kSuccess = 0, kTimeout, kFailed }; using ServiceStatusCallback = std::function<void(bool avail...
The main task of the code is to generate declaration code by first creating stable and forward declarations, then processing interface declarations in a specified order from the IR dictionary. It checks for the existence of a declaration order key, iterates through interface entries, and triggers interface-specific dec...
def __genDeclarations(self): self.__genStableDecls() self.__genForwardDecls() if not ir_parser.kDeclarationsOrder in self._ir_dict.keys(): return for order_item in self._ir_dict[ir_parser.kDeclarationsOrder]: if order_item[ir_parser.kCategory] == ir_parse...
def __genSessionAndFunc(self): content_lines = """ struct SessionContext final { // Transport Channel ID uint32_t channel; // Request token std::string token; // Client identifier std::string client_identifier; /** * Permission check result * @note at service side,...
This method generates code declarations by first creating session/function and forward declarations. It then checks for an 'order' key in the IR dictionary. If present, it iterates through ordered items, generating interface declarations specifically for entries categorized as interfaces.
def __genDeclarations(self): self.__genSessionAndFunc() self.__genForwardDecl() if not ir_parser.kDeclarationsOrder in self._ir_dict.keys(): return for order_item in self._ir_dict[ir_parser.kDeclarationsOrder]: if order_item[ir_parser.kCategory] == ir_par...
def __genIncAndTypeDefs(self): content_lines = ''' #include "%sProxy.h" #include <mutex> ''' % (self._base_name) utils.Utils.writeGenFile(self._path, self._file, content_lines) def __genStableLines(self): content_lines = """ using std::shared_ptr; using std::string; static bool NameToId(void* u...
The main task of the code is to generate proxy implementation code by sequentially creating include/type definitions, initiating a namespace, producing stable code lines, generating the core implementation logic, and closing the namespace. This structured approach ensures proper code organization and modular proxy func...
def gen(self): print("start to gen proxy impl") self.__genIncAndTypeDefs() self._genNameSpaceStart() self.__genStableLines() self.__genImpl() self._genNameSpaceEnd()
def __genIncAndTypeDefs(self): content_lines = '''#include "%sService.h"\n''' % (self._base_name) utils.Utils.writeGenFile(self._path, self._file, content_lines) def __genNameIdMapper(self, ): content_lines = """ using std::shared_ptr; using std::string; static bool NameToId(void* user_data, co...
The main task of the code is to generate a service implementation by sequentially creating include/type definitions, initiating a namespace block, generating name-to-ID mappings, producing the core implementation logic, and closing the namespace. This structured approach builds a modular code framework for a service, e...
def gen(self): print("start to gen service impl") self.__genIncAndTypeDefs() self._genNameSpaceStart() self.__genNameIdMapper() self.__genImpl() self._genNameSpaceEnd()
def read_excluded_dates(filename): excluded_dates = [] with open(filename, mode="r") as csvfile: reader = csv.reader(csvfile) next(reader) # Skip the header row for row in reader: for date in row: if date: excluded_dates.append(datetime.da...
The main task of the code is to generate an optimized doctor schedule between July 1, 2023, and June 30, 2024, considering excluded dates and individual doctor availability constraints. It initializes doctor objects with unavailable dates, uses PuLP for scheduling optimization, and exports the final schedule to a CSV f...
def main(): start_date = datetime.date(2023, 7, 1) end_date = datetime.date(2024, 6, 30) excluded_dates = read_excluded_dates(EXCLUDED_DATES_FILENAME) doctor_data = read_doctor_data(DOCTOR_DATA_FILENAME) MAX_ITERATIONS = 10000 # Initialize doctors doctors = [] for i in range(1, 6): ...
def has_read(self, obj, userid=None): # block anon if not userid and api.user.is_anonymous(): return False query_filter = dict( userid=self._resolve_userid(userid), status='read', uid=utils.getUID(obj), ) result = self._read(**query...
This function marks an object as 'read' for a specified user, avoiding redundant database writes. It checks if the object is already marked as read for the user, uses the current UTC time if no read time is provided, resolves the user ID, and updates an existing entry or creates a new one with metadata like UID, type, ...
def mark_read(self, obj, userid=None, read_at=None): '''Mark <obj> as read.''' # block anon if not userid and api.user.is_anonymous(): return # avoid database writes by only storing first read actions if self.has_read(obj, userid): return if not re...
def get_new_filename(self, binary): if binary: self.new_filename = self.origfilename + "_" + str(self.max_width) + "x" + str(self.max_height) +".png" else: self.new_filename = self.origfilename + "_" + str(self.max_width) + "x" + str(self.max_height) + ".jpg" def processs_image(s...
The function processes an image from an S3 bucket, generates a new filename, checks for archival status, downloads the image if needed, processes it, uploads the result to a target S3 bucket, and updates a catalog with the new S3 key.
def processed_and_upload_image_to_s3(self, s3_image_key): self.output_s3_prefix = create_output_s3_prefix(s3_prefix=s3_image_key) self.origfilename = s3_image_key.split("/")[-1] print("process %s" % s3_image_key) if not self.png_for_1: # no need to get the s3 bits if no proce...
def base_forward_flat_traj(pos: np.ndarray, step_height: float, linear: np.ndarray, angular: np.ndarray, t: float) -> np.ndarray: """! Generates flat forward part of the base trajectory Flat forward move ...
The function generates a smooth base trajectory for a robot's leg or base movement, incorporating step height, linear/angular displacement, and margin parameters. It uses conditional logic based on normalized time (t) to transition between forward/backward phases, applying raised trajectories during specific intervals ...
def base_traj(pos: np.ndarray, step_height: float, linear: np.ndarray, angular: np.ndarray, margin: float, t: float) -> np.ndarray: """! Generates the the base trajectory @param pos: Base position of the leg @param step_height: Step heigh...