dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def load_image(self, im_id: str) -> Image: logger.info('Loading {}'.format(im_id)) im_cache = Path('im_cache') im_cache.mkdir(exist_ok=True) im_data_path = im_cache.joinpath('{}.data'.format(im_id)) mask_path = im_cache.joinpath('{}.mask'.format(im_id)) if im_data_path.ex...
This code trains a neural network model using specified training and validation image datasets, adjusting the learning rate over epochs. It initializes a TensorBoard logger, loads images, restores model snapshots if provided, and iterates through training epochs with validation steps. The training process includes dyna...
def train(self, logdir: Path, train_ids: List[str], valid_ids: List[str], validation: str, no_mp: bool=False, valid_only: bool=False, model_path: Path=None): self.tb_logger = tensorboard_logger.Logger(str(logdir)) self.logdir = logdir print("Length of train_ids=",len(...
def print_to_console(string): print('[' + str(get_datetime_now())[:-4] + '] ' + string) def import_bet_providers(): try: with open(bet_providers_filepath, encoding='utf8') as f: lines = [line[:-1] for line in f.readlines()] print_to_console('Imported ' + bet_providers_filepath) e...
The main task of the code is to execute the `refresh_config` function, which prints a console message indicating configuration import, then sequentially imports three configuration modules: betting providers, league coverage, and reports configuration. It concludes with an empty print statement, likely for formatting o...
def refresh_config(): print_to_console('### Importing config') import_bet_providers() import_league_coverage() import_reports_config() print('')
def populate_hotel(brand_index, hotel_index, curs, hotel_id): global email_id hotel = hotel_data.hotels[brand_index][hotel_index] employee_sins = [] type_ids = [] (name, email) = random_name_email() # general manager must be inserted first to satisfy trigger constraint curs.execute('INSER...
(The main task of the code is to populate a hotel database with sample data, including inserting hotel brands, hotel details, customer records, and room bookings. It iterates through predefined hotel brand and hotel data, inserts entries into database tables, generates random customer information, and creates room book...
def populate(conn): global email_id with conn: with conn.cursor() as curs: hotel_id = 0 for i in range(len(hotel_data.hotel_brands)): brand = hotel_data.hotel_brands[i] temp_hotels_data[i] = [None] * len(hotel_data.hotels[i]) curs....
def randomize_images(self): perm = np.random.permutation(self.n_train_images) self.train_answers = self.train_answers[perm] self.train_images = self.train_images[perm] def train_once(self): for batch_number in range(0,self.n_batches): input_array = np.take( # batch_size x n_pixels self.tra...
The main task of the code is to iteratively train a model until the percentage point change in test pass/fail rate between consecutive training passes falls below a threshold (0.1%). It repeatedly randomizes images, trains the model once, evaluates test accuracy, and tracks progress until convergence.
def train(self): percentage_points_change_threshold = .1 percentage_points_change = 1 # initialize test_pass_fail_rate_old = 0 # initialize pass_number = 0 # initialize while percentage_points_change > percentage_points_change_threshold: self.randomize_images() # not sure if we should se...
def recalibrate(self) -> int: print("Recalibrating light sensitivty of device.") self.write_bytes(RECALIBRATE) self.resistance = self.readint() print("Resistance set to", self.resistance, "Ohms.") return self.resistance def set_sample_rate(self, frequency: int) -> None: ...
The main task of the code is to perform a measurement on a device for a specified duration at a given sample rate. It initializes parameters, checks resistance, sends a start command, collects sensor data, and returns a `GestureData` object. It also logs warnings, measures actual sampling rates, and ensures measurement...
def measure(self, duration=STANDARD_DURATION, sample_rate=STANDARD_SAMPLING_RATE, log=False) -> GestureData: print("Starting measurement on device") if (self.resistance == 0): print("Warning: resistance is not set. Recalibrating.") self.recalibrate() # Set the s...
def create_port_dropdown(self): dropdown = self.create_dropdown( "Serial Port:", self.available_ports, "serial_port" ) def create_calibration_button(self): calibration_button = QPushButton("Recalibrate Sensitivty", self) calibration_button.clicked.connect(self.recalibrate) ...
The code initializes a GUI for a data collection interface by setting the window title, adding a quit action, creating a grid layout, and integrating UI elements like dropdowns, buttons, and input fields to configure parameters such as port selection, calibration, gesture types, sample rate, duration, and testing contr...
def initializeUI(self): self.setWindowTitle("Data Collection Interface") # self.setGeometry(300, 300, 800, 600) # Connecting quit function quit = QAction("Quit", self) quit.triggered.connect(self.closeEvent) # QT display w = QtWidgets.QWidget() self.setC...
def check_le(to_check, verbose): lf, crlf, mixed = 0, 0, 0 errors = 0 for codefile in to_check: try: data = read_file(codefile) if EOL_CRLF and EOL_LF in data: if verbose: print(f"{codefile} - MIXED") mixed += 1...
The main task of the code is to convert or check line endings (LF/CRLF) in files within a specified project directory. It validates input paths, discovers files, and processes them based on user-specified modes (check, LF, or CRLF). It reports the number of files processed, errors encountered, and error rate, ensuring ...
def main(args): if not os.path.exists(args.project): print("Invalid project path supplied.") sys.exit(1) if args.check: check_le(args.project, args.verbose) if not args.lf and not args.crlf and not args.check: print("Please specify a conversion mode (LF/CRLF).") sys...
def print_board(board): for row in board: print(" | ".join(row)) print("-" * 9) def find_best_move(board): best_val = -float("inf") best_move = (-1, -1) for i in range(3): for j in range(3): if board[i][j] == " ": board[i][j] = "X" mov...
This code implements a Tic-Tac-Toe game where Player X uses an AI algorithm (find_best_move) to select optimal moves, while Player O takes human input. The game alternates turns, checks for wins/draws after each move, and displays the board state. It validates inputs, handles game flow, and terminates when a player win...
def main(): board = [[" " for _ in range(3)] for _ in range(3)] current_player = "X" while True: print_board(board) if current_player == "X": row, col = find_best_move(board) print(f"Player {current_player} chooses row {row} and column {col}.") else: ...
def kill_prolog_server(self): """Kills the Prolog server process if it is still running.""" if self.prolog_proc is not None: self.logger.debug(self.implementation_id + ': Kill Prolog server') self.prolog_proc.kill() self.is_server_restart_required = True def send_resp...
The function processes a successful Prolog response by formatting variable bindings (either single values with '=' or domains with 'in') and sending them to the frontend. It iterates through result entries, checks their status, handles errors, and constructs human-readable outputs. For CLPFD variables, it extracts doma...
def handle_success_response(self, response_dict): """ Handles a success response by computing output for each term result and sending it to the frontend. The dictionary response_dict contains the key 'result'. The corresponding value contains the results of the Prolog terms read from th...
def start_prolog_server(self): """Tries to (re)start the Prolog server process with the configured arguments.""" # Check if the Prolog server is to be started with the default program arguments # Otherwise, the provided path needs to be absolute or relative to the current working directory ...
The main task of the code is to execute provided code on a Prolog server, handle potential errors or server restarts, and return appropriate responses to the frontend. It checks if the server needs restarting, sends the code for execution, processes success or error responses, and manages exceptions like interruptions ...
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): """ A request to execute code was received. The code is tried to be executed by sending it to the Prolog server. If the execution is interrupted or an exception occurs, an error response is...
def get_image(coord,i,n,mm): #saves the image using coord and i is the number of images # n=False normally.set it true when dealing with zoomed out images of well apd if len(coord)==0: return w = 606 h = 606 if n==True: w = (coord[2] - coord[0]) * 6 h = (coord[1] - coord[3])...
The code scans a wellpad area in images to detect tanks by iterating through sub-regions, using image processing to identify white pixels, adjusting detected tank coordinates based on image scaling, and compiling a list of tank coordinates after cleaning overlapping detections.
def check_equip(loc_coord,m): # to check welltank inside wellpad x1_equip = loc_coord[0] y1_equip = loc_coord[1] x2_equip = loc_coord[2] y2_equip = loc_coord[3] add_1 = 105 add_2 = 85 x1 = x1_equip x2 = x1 + add_1 tank_list = [] while x1 <= x2_equip: y1 = y1_equip ...
def get_area(rect): w = abs(rect[2]-rect[0]) h = abs(rect[1]-rect[3]) area = w * h return area def check_area_combine(num1,index,area,temp): w = 606 h = 606 img_loc = get_image([num1[0],num1[1],num1[2],num1[3]],1,False,False) c = detect(img_loc,0.60) g = True if c!=False: ...
The code processes a list of elements (likely shapes or regions) to merge overlapping or contained elements. It iterates through pairs of elements, checking for intersections or containment using helper functions. When a merge condition is met (area exceeds threshold or overlap/containment detected), it replaces the cu...
def inter_contain(temp): w = 606 h = 606 i = 0 length = len(temp) if length < 2: return temp while i <= (length - 1) and len(temp)>=2: num1 = temp[i] j = i + 1 area_1 = get_area(num1) # print(len(temp),area_1,i) # print(num1) if area_1 > 2500...
def get_image(coord,i,n,mm): #saves the image using coord and i is the number of images # n=False normally.set it true when dealing with zoomed out images of well apd if len(coord)==0: return w = 606 h = 606 if n==True: w = (coord[2] - coord[0]) * 6 h = (coord[1] - coord[3])...
The main task of the code is to detect and locate various equipment (tanks, separators, flares, etc.) within a specified wellpad area by scanning the image in steps, processing each section for object detection, converting coordinates to the original image scale, and cleaning overlapping detections. It returns lists of...
def check_equip(loc_coord,m): # to check welltank inside wellpad x1_equip = loc_coord[0] y1_equip = loc_coord[1] x2_equip = loc_coord[2] y2_equip = loc_coord[3] add_1 = 105 add_2 = 85 x1 = x1_equip x2 = x1 + add_1 tank_list = [] sep_list = [] eflare_list = [] oflare_list ...
def draw_range(cord): # draws the rectangular search space ( 4 input points from user) layer = QgsVectorLayer('Polygon?crs=EPSG:3857', 'area', 'memory' ) pr = layer.dataProvider() poly = QgsFeature() points = [QgsPointXY(cord[0], cord[1]), QgsPointXY(cord[2], cor...
The code defines a function to scan a defined 2D area (using global min/max coordinates) in blocks, detecting and drawing specific elements (e.g., well pads/tanks) by iterating over sub-regions, checking for completion, and processing detected objects with custom detection and rendering functions.
def find_well_pad_tank(points,p2): # find the coordinates between the range of points start_time = time.time() global x_min global y_min global x_max global y_max x_min = points[6] x_max = points[2] y_min = points[1] y_max = points[5] poly = draw_range(points) # print(x_m...
def package_discovery(address): empty_byte_4 = b'\x00\x00\x00\x00' empty_byte_3 = RESERVE mode = b'\x01' send_Package = empty_byte_4 + empty_byte_4 + empty_byte_3 + mode + empty_byte_4 return send_Package def find_mode(message): mode = int.from_bytes(message[11:12], byteorder='big') return m...
The main task of the code is to establish a TCP connection to a server, send discovery packets, and handle incoming messages by processing location data, broadcasting updates, and maintaining a connection list. It parses message modes, calculates distances between coordinates, updates connection entries based on proxim...
def tcp_send(self, port): # TCP USER SERVER tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.connect(('127.0.0.1', int(port))) tcp_socket.sendall(package_discovery(int(port))) # Waiting for responses while True: message = tcp_socket....
def take_input(): """ Take command from stdin. Acceptable command is 'send' """ print('> ', end='', flush=True) def find_mode(message): mode = int.from_bytes(message[11:12], byteorder='big') return mode def break_message(message): source_ip = message[:4] # Source IP address ...
This code sets up a TCP server to listen for incoming connections, process data packets (Location/Broadcast modes), calculate distances between coordinates, maintain client connections, and broadcast messages. It handles location tracking, updates connection details, and manages client interactions based on message typ...
def tcp_listen(self): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("127.0.0.1", 0)) print(server.getsockname()[1], flush=True) self.server_global = server server.listen(5) self.take_input() while True: conn, address = server...
def package_discovery(address): empty_byte_4 = b'\x00\x00\x00\x00' empty_byte_3 = RESERVE mode = b'\x01' send_Package = empty_byte_4 + empty_byte_4 + empty_byte_3 + mode + empty_byte_4 return send_Package def find_mode(message): mode = int.from_bytes(message[11:12], byteorder='big') return m...
The code establishes a TCP connection to a specified port, sends a discovery packet, and processes incoming messages. It handles 'Location' data by calculating distances between coordinates, broadcasting updates to connected clients, and maintaining a connection registry. For 'Broadcast' messages, it updates proximity ...
def tcp_send(self, port): tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.connect(('127.0.0.1', int(port))) tcp_socket.send(package_discovery(int(port))) while True: message = tcp_socket.recv(MAX_FILESIZE) if message != b'': ...
def new_udp_socket(port) -> socket: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((LOCAL_HOST, port)) return sock def _recv(self, sock, print_out=False, extend_message=""): try: raw_data, info = sock.recvfrom(RECV_SIZE) except: traceback.print_exc(...
The code simulates a UDP-based greeting exchange between a switch and an adapter. It opens a UDP socket, outputs the assigned port, instructs users to run an adapter with that port, sends test packets (OFFER and ACKNOWLEDGE) to simulate communication, and verifies the adapter's response. The task involves testing netwo...
def adapter_greeting(self, additional_message=""): # this test stimulates a switch, user execute the adapter and connect to the given port # the map of the connection: # # [A] ----------------------> [T] # ./RUSHBAdapter Switch Stimulator # ...
def get_info_file(file_path, skip=0): info = None try: while not os.path.exists(file_path): time.sleep(1) if os.path.isfile(file_path): time.sleep(3) f = open(file_path, "r") for i in range(skip): f.readline() target_por...
The main task of the code is to test a switch's greeting protocol handling by simulating an adapter that sends DISCOVERY and REQUEST packets to a local switch (192.168.1.1/24). It creates a UDP socket, transmits packets, captures responses, and validates output against a reference file. The test verifies correct switch...
def switch_greeting_adapter(self, modified_test_name="SWITCH_GREETING_ADAPTER"): # this test stimulates an adapter that sending greeting protocols to the target switch, user executes the switch # the switch has an IP address of 192.168.1.1/24 run in local mode # the map of the connection: ...
def _recv(self, sock, print_out=False, extend_message=""): try: raw_data, info = sock.recvfrom(RECV_SIZE) except: traceback.print_exc(file=sys.stderr) assert False, f"Error while receiving a message from a socket." try: mode = raw_data[11] ...
This function handles the "switch offer" process by sending a sequence of network packets to a target device. It first receives data, then transmits an OFFER packet to assign an IP, followed by an ACKNOWLEDGE to confirm the assignment, and finally a LOCATION packet to set coordinates. The process uses specific packet m...
def _switch_offer(self, sock, target, host_ip, assigned_ip, location=(0, 0), switch_name="[S] "): try: self._recv(sock, print_out=True, extend_message=switch_name) pkt, add = build_packet(source_ip=host_ip, destination_ip="0.0.0.0", offset=0x000000, mode=OFFER, misc=assigned_ip) ...
def get_info_file(file_path, skip=0): info = None try: while not os.path.exists(file_path): time.sleep(1) if os.path.isfile(file_path): time.sleep(3) f = open(file_path, "r") for i in range(skip): f.readline() target_por...
This code simulates network communication between a switch (local 2) and an adapter via UDP/TCP sockets. It initializes connections, sends discovery/request packets, and verifies responses to test switch-adapter interaction. The test checks packet exchange, IP address handling, and protocol compliance, ensuring proper ...
def switch_local2_greeting(self, modified_test_name="SWITCH_LOCAL2_GREETING"): # this test stimulates an adapter and a switch connect to the target switch (local 2), user executes the switch # the target switch has an IP address of 130.0.0.1/8 10.0.0.1/8 # the map of the connection: # ...
def adapter_greeting(self, additional_message=""): # this test stimulates a switch, user execute the adapter and connect to the given port # the map of the connection: # # [A] ----------------------> [T] # ./RUSHBAdapter Switch Stimulator # ...
This function simulates a switch communicating with an adapter by sending a query protocol packet (0x05) followed by a data packet containing "HELLO WORLD". It establishes a connection using adapter_greeting, constructs packets with specified IP addresses and modes (QUERY/DATA), sends them via a socket, and verifies co...
def adapter_receiving(self): # this test stimulates a switch, establish the protocol as same as in adapter_greeting # the switch then sends a 0x05 message to the adapter, but will make a query protocol before sending it # the map of the connection: # # [A] ------------...
def adapter_greeting(self, additional_message=""): # this test stimulates a switch, user execute the adapter and connect to the given port # the map of the connection: # # [A] ----------------------> [T] # ./RUSHBAdapter Switch Stimulator # ...
This function tests the adapter's handling of fragmented IP packets by sending a sequence of packets with different fragmentation modes (QUERY, MORE_FRAG, END_FRAG) to simulate data reassembly. It establishes a protocol connection, transmits fragmented data packets with specific offsets and payloads, and verifies the a...
def adapter_fragmentation(self): # this test stimulates a switch, establish the protocol as same as in ADAPTER_GREETING, user executes the adapter # the switch then sends 0x0a and 0x0b messages to the adapter after the query protocols # the map of the connection: # # [...
def adapter_greeting(self, additional_message=""): # this test stimulates a switch, user execute the adapter and connect to the given port # the map of the connection: # # [A] ----------------------> [T] # ./RUSHBAdapter Switch Stimulator # ...
This function tests an adapter's response to a malformed protocol scenario. It simulates a switch sending packets with incorrect query protocols, using packets with specific IPs, offsets, and modes (AVAILABLE/QUERY/DATA). The test verifies adapter behavior by sending/receiving packets and comparing output against expec...
def adapter_wrong_receive(self): # this test stimulates a switch, establish the protocol as same as in ADAPTER_GREETING, user executes the adapter # the switch then sends a 0x05 message to the adapter but the query protocol is somehow wrong # the map of the connection: # # ...
def switch_greeting_adapter(self, modified_test_name="SWITCH_GREETING_ADAPTER"): # this test stimulates an adapter that sending greeting protocols to the target switch, user executes the switch # the switch has an IP address of 192.168.1.1/24 run in local mode # the map of the connection: ...
This method simulates a switch handling multiple adapters by creating UDP sockets, sending discovery and request packets with specific IP configurations, and verifying responses. It tests the switch's behavior in local mode (IP 192.168.1.1) by interacting with two adapters, validating packet transmission and reception ...
def switch_multi_adapter(self): # this test stimulates 2 adapters connecting to the target switch, user executes the switch # the switch has an IP address of 192.168.1.1/24 run in local mode # the map of the connection: # # [A] ----------------------> [T] # ...
def new_tcp_socket(port) -> socket: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((LOCAL_HOST, port)) return sock def get_info_file(file_path, skip=0): info = None try: while not os.path.exists(file_path): time.sleep(1) if os.path.isfile(file_path): ...
The main task of the code is to simulate a network test scenario where two switches (S1 and S2) connect to a target switch (T) in global mode. It tests packet exchange (discovery, request, location) between switches via TCP sockets, verifies the target switch's behavior in propagating information, and ensures S2 does n...
def switch_global_greeting(self, modified_test_name="SWITCH_GLOBAL_GREETING"): # this test stimulates 2 switches connect to the target switch (global), user executes the switch # the target switch has an IP address of 130.0.0.1/8 in global mode # the map of the connection: # # ...
def new_tcp_socket(port) -> socket: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((LOCAL_HOST, port)) return sock def _switch_offer(self, sock, target, host_ip, assigned_ip, location=(0, 0), switch_name="[S] "): try: self._recv(sock, print_out=True, extend_message=sw...
The code simulates a network test where a switch (192.168.1.1/24) forwards messages between an adapter [A] and a target [S]. It establishes TCP/UDP connections, sends packets with varying modes (DISCOVERY, REQUEST, DATA), and verifies correct forwarding. Output is compared to a reference file using `diff` to validate s...
def switch_forward_message(self): # this test stimulates an adapter and a switch in 2 side of target switch, user executes the switch # the target switch has an IP address of 192.168.1.1/24 run in local mode # the map of the connection: # # [A] ----------------------> ...
def new_tcp_socket(port) -> socket: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((LOCAL_HOST, port)) return sock def _switch_offer(self, sock, target, host_ip, assigned_ip, location=(0, 0), switch_name="[S] "): try: self._recv(sock, print_out=True, extend_message=sw...
This code simulates a switch connecting to two sides of a target switch (192.168.1.1/24), testing its behavior when updating its neighborhood. It creates two TCP sockets, writes port configurations to a file, instructs running the switch with specific arguments, and connects to the switches, offering them predefined co...
def switch_distance_switch(self, modified_test_name="SWITCH_DISTANCE_SWITCH"): # this test stimulates 2 switch connect 2 side of the target switch, user executes the switch # the target switch has an IP address of 192.168.1.1/24 run in local mode # the map of the connection: # # ...
def switch_global_greeting(self, modified_test_name="SWITCH_GLOBAL_GREETING"): # this test stimulates 2 switches connect to the target switch (global), user executes the switch # the target switch has an IP address of 130.0.0.1/8 in global mode # the map of the connection: # # ...
The main task of the code is to simulate a network scenario where two switches ([S1] and [S2]) interact with a target switch ([T]) in a minimap configuration. It tests data transmission, path establishment, and query handling by sending packets in modes like DISTANCE, QUERY, DATA, and AVAILABLE. The test verifies corre...
def minimap_3(self): # this test stimulates 2 switches (in a minimap) connect to the target switch (global), target is the 3rd component # the target switch has an IP address of 130.0.0.1/8 in global mode # the map of the connection: # # ... -----[S1] ----------------------> [T...
def switch_distance_switch(self, modified_test_name="SWITCH_DISTANCE_SWITCH"): # this test stimulates 2 switch connect 2 side of the target switch, user executes the switch # the target switch has an IP address of 192.168.1.1/24 run in local mode # the map of the connection: # # ...
The code simulates a simple switch routing test with two switches (S1/S2), a target switch (T), and an adapter (A). It tests packet routing by sending distance-based packets between switches, initiating UDP communication from the adapter to T, and transmitting a "HELLO WORLD" message. The test verifies routing logic, d...
def switch_routing_simple(self, test_name="SWITCH_ROUTING_SIMPLE", data_destination="172.16.58.3", d1=3, d2=5): # this test stimulates 2 switches and an adapter that connecting to the target switch, user executes a switch # the target switch has an IP address of 192.168.1.1/24 run in local mode ...
def is_finished(self): return self.is_id(self.tree[self.root]) def is_tbd(self, number): return number == self.tbd def parent(index): return index // 2 def sibling(self, index): if self.is_left(index): return self.right(self.parent(index)) else: return sel...
This function determines the next match for a player in a tournament bracket. It checks if the tournament is finished, then searches the tree for the player's position. If the player's parent match is TBD, it checks the sibling node. If the sibling is also TBD, it returns 'TBD'; otherwise, it returns the sibling's ID a...
def next_match_for(self, pl_id: int): if self.is_finished(): return {'state': 'finished', 'id': -1} for index in range(self.root, len(self.tree)): if self.tree[index] == pl_id: if self.is_tbd(self.tree[self.parent(index)]): v_sibling = self.tre...
def recv_cb(enow): global dbgled global brightness_filtered global last_upload_msg_time dbgled += 1 try: #tnow = time.ticks_ms() mac, data = enow.irecv(0) info = None try: info = enow.peers_table[mac] except: print("received data from u...
This function manages network communication by listening for incoming data, selecting the optimal peer to ping based on age and hop count, updating time synchronization, and triggering resets if idle. It also handles periodic announcements and enforces timeout limits for network operations.
def handle_network(max_delay = 100): global msg_response global last_sync global last_announce global last_peer_valid rawtime = time.ticks_ms() msg_response = None while(enow.any() and time.ticks_ms() < rawtime+max_delay): recv_cb(enow) if(msg_response != None): break ...
def openImg(self, val): # browse for image path = QFileDialog.getOpenFileName( self, "Open File", "This PC", "All FIles (*);; PNG Files(*.png);; JPG Files (*.jpg)" ) img = cv2.imread(path[0]) # prompting the user to upload a bright image if self....
The main task of the code is to initialize a GUI application by loading a UI file, setting up image processing variables, connecting buttons to handle image operations (open, match, clear), and configuring color scheme analysis using pyqtgraph. It prepares a frameless window with two color visualization panels for comp...
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) ############################ #### LOAD UI FILE ############################ uic.loadUi(r'refurbished.ui', self) # # SET FRAMLESS WINDOW # flags = QtCore.Qt.WindowFlags...
def split_continuous_variable(feature, samples): feature_values = list(set(feature.value_extractor(weather_item) for weather_item in samples)) feature_values.sort() feature_values2 = feature_values.copy() feature_values2.pop(0) best_impurity = 1.0 best_split = None zipped_values = zip(feat...
This function builds a leaf node in a decision tree by evaluating continuous features to find the split with the lowest Gini impurity. It iterates through features, calculates impurity for potential splits, and selects the best feature/split combination. If the resulting impurity improves upon the previous node or no p...
def build_leaf(weather_items, previous_leaf): best_impurity = 1.0 best_split = None best_feature = None # Find feature with lowest impurity for feature in features: split_value = split_continuous_variable(feature, weather_items) # If value cannot be split, skip if split_val...
def split_continuous_variable(feature, sample_employees): feature_values = list(set(feature.value_extractor(employee) for employee in sample_employees)) feature_values.sort() feature_values2 = feature_values.copy() feature_values2.pop(0) best_impurity = 1.0 best_split = None zipped_values ...
This code determines the optimal feature and split value to create a new leaf node in a decision tree, minimizing Gini impurity. It iterates through features, evaluates splits, and returns a TreeLeaf if the new split improves upon the previous leaf's impurity. Otherwise, it returns None.
def build_leaf(sample_employees, previous_leaf): best_impurity = 1.0 best_split = None best_feature = None for feature in features: split_value = split_continuous_variable(feature, sample_employees) if split_value is None: continue impurity = gini_impurity_for_spli...
def split_continuous_variable(feature, sample_colors): feature_values = list(set(feature.value_extractor(color) for color in sample_colors)) feature_values.sort() feature_values2 = feature_values.copy() feature_values2.pop(0) best_impurity = 1.0 best_split = None zipped_values = zip(featur...
This function determines the optimal split for a decision tree leaf node by evaluating Gini impurity across features. It iterates through features, calculates impurity for potential splits, and selects the feature/split with the lowest impurity. If this split improves upon the previous leaf's impurity or no previous le...
def build_leaf(sample_colors, previous_leaf): best_impurity = 1.0 best_split = None best_feature = None for feature in features: split_value = split_continuous_variable(feature, sample_colors) if split_value is None: continue impurity = gini_impurity_for_feature(fe...
def composeData(self): words = self.getWords() result = {} for index, val in enumerate(words): for v in val['term']: p = "D" + str(val['row']) if v in result: excArray = result[v]['posisi'] if p not in excA...
The main task of the code is to compute mutual information (MI) values for each item in a dataset, based on class distributions and positional probabilities. It calculates probabilities for positive/negative classes, derives conditional probabilities for item positions, computes log-likelihood ratios, and aggregates th...
def composeMI(self): data = self.composeData() rows = self.totalRows() classes = self.getClasses() pPos = len(classes['positif']) / rows pNeg = len(classes['negatif']) / rows for item in data: p1t = len(data[item]['posisi']) / rows p1_pos =...
def load_tuple_event(files=None): data = {'train':[], 'evaluation': []} if files == None: files = glob.glob(os.path.join(data_path, '*.midi')) for data_segment in ['train', 'evaluation']: for midifile in files: events = extract_tuple_events(midifile) events = group_by...
This function converts MIDI files from a specified folder into structured 'worded data' format. It processes MIDI files, extracts note/tempo events, constructs a dictionary mapping, and saves both the dictionary and converted data as pickle files in the specified save folder.
def convert_midis_to_worded_data(midi_folder, save_folder): os.makedirs(save_folder, exist_ok=True) midis = [] for root, dirs, files in os.walk(midi_folder): for f in files: if f[-4:] == '.mid': try: note_items, tempo_items = utils.read_items(os.path....
def try_real_annotations(fn): """Tries to use the Py3.5+ annotation syntax to get the type.""" try: sig = inspect.signature(fn) except ValueError: return None all_annots = [sig.return_annotation] + [p.annotation for p in sig.parameters.values()] if all(ann is sig.empty for ann in al...
The function `get_signature` retrieves and parses function annotations or type hints from a given function `fn`. It prioritizes Python 3.5+ syntax for annotations, fallbacks to extracting type information from the function's source code if annotations are unavailable, and defaults to a generic signature if no type info...
def get_signature(fn, _n_arguments=None, _n_binders=None): # Python 3.5 adds support for the nice annotation syntax, so try that first. if PY35: sig = try_real_annotations(fn) if sig is not None: return sig type_line, source = None, None try: source = dedent(inspect....
def addHistoricBar(self,reqId,bar): for i, b in enumerate(self.historicBars[reqId]): if (b == None): self.historicBars[reqId][i] = bar break else: self.currentBars[reqId] = bar if((b!=None) and (self.lastMonthClose[reqId]==None)): self.lastMonthClose[reqId] = bar ...
The code processes bar data updates for real-time or historical trading, updating historical records and triggering monthly trend analysis when a new month starts. It checks if the current day is the first of the month, updates relevant data structures, and executes a bot logic function for trend evaluation, while main...
def on_bar_update(self, reqId, bar, realtime): global orderId newDay=0 #Historical Data to catch up if (realtime == False): #add last month close plus three older monthly closes self.addHistoricBar(reqId,bar) else: barDate = datetime.strptime(bar.date, "%Y%m%d") if (self.curr...
def search_google(query, num_results, lang): results = [] try: for url in search(query, num_results=num_results, lang=lang): try: ua = UserAgent() headers = {"User-Agent": ua.random} response = requests.get(url, headers=headers) ...
The main task of the code is to perform a Google search using user-provided query, number of results, and language, scrape the search results while handling errors, and save the extracted data (URLs, titles, descriptions, positions, and scraped content) into CSV and TXT files for storage and analysis.
def main(): query = input("Enter the search query: ") num_results = int(input("Enter the number of search results: ")) lang = input("Enter the two-letter language code (e.g., 'en' for English): ") search_results = search_google(query, num_results, lang) scraped_data = [(url, title, description, pos...
def one_spacing_list(int_value, one_1_poss): new_one_spaced = [] new_one_spaced = [(int_value ^ i) for i in one_1_poss] return new_one_spaced def two_spacing_list(int_value, two_1_poss) : new_two_spaced = [] new_two_spaced = [(int_value ^ i) for i in two_1_poss] return new_two_spaced def union_set(vertice1, verti...
The function processes a list of graphs using a modified Kruskal's algorithm approach. It iterates through each graph, generates spaced variants (new_one_spaced, new_two_spaced), checks for cluster unions, and decrements a count when successful unions occur. The count likely represents the number of clusters, reducing ...
def k_cluster_kruskal(one_1_poss, two_1_poss, graph_list_integer, count) : len_list = len(graph_list_integer) for index in range(len_list) : new_one_spaced = one_spacing_list(graph_list_integer[index], one_1_poss) new_two_spaced = two_spacing_list(graph_list_integer[index], two_1_poss) for element in new_one_...
def getTemplateIndex(self, page): """ Gets a list of the template positions with usage indicator. Arguments: page (int): The page (value between 0 and 3). Returns: The list. Raises: ValueError: if passed page is invalid Exception...
The code stores a fingerprint template from a specified character buffer into a designated position in the device's storage. It validates the input parameters (position and buffer), searches for an empty slot if positionNumber is -1, constructs a command packet, sends it, and handles responses. Errors like invalid posi...
def storeTemplate(self, positionNumber = -1, charBufferNumber = Finger.CHARBUFFER1): """ Stores a template from the specified char buffer at the given position. Arguments: positionNumber (int): The position charBufferNumber (int): The char Finger. Use `Finger.CHARBUFFER1...
def getStorageCapacity(self): """ Gets the sensor storage capacity. Returns: The storage capacity (int). Raises: Exception: if any error occurs """ return self.getSystemParameters()[2] def __rightShift(self, n, x): """ Performs a...
The `searchTemplate` method searches a fingerprint database for a match using specified characteristics. It sends a search command with parameters like buffer number, start position, and template count. It processes the response packet to return the matched template's position and accuracy score, or raises errors for i...
def searchTemplate(self, charBufferNumber = Finger.CHARBUFFER1, positionStart = 0, count = -1): """ Searches inside the database for the characteristics in char Finger. Arguments: charBufferNumber (int): The char Finger. Use `Finger.CHARBUFFER1` or `Finger.CHARBUFFER2`. ...
def getStorageCapacity(self): """ Gets the sensor storage capacity. Returns: The storage capacity (int). Raises: Exception: if any error occurs """ return self.getSystemParameters()[2] def __rightShift(self, n, x): """ Performs a...
The `loadTemplate` method loads a fingerprint template from a specified storage position into a character buffer (CHARBUFFER1/CHARBUFFER2). It validates the position and buffer number, constructs a command packet, and sends it. It then checks the response: returns `True` on success or raises exceptions for errors like ...
def loadTemplate(self, positionNumber, charBufferNumber = Finger.CHARBUFFER1): """ Loads an existing template specified by position number to specified char Finger. Arguments: positionNumber (int): The position charBufferNumber (int): The char Finger. Use `Finger.CHARBUF...
def getStorageCapacity(self): """ Gets the sensor storage capacity. Returns: The storage capacity (int). Raises: Exception: if any error occurs """ return self.getSystemParameters()[2] def __rightShift(self, n, x): """ Performs a...
The main task of the code is to delete a specified number of fingerprint templates from a database starting at a given position. It validates the position and count against the storage capacity, constructs a deletion command packet, sends it, and processes the response. It returns `True` on success, `False` for specifi...
def deleteTemplate(self, positionNumber, count = 1): """ Deletes templates from fingerprint database. Per default one. Arguments: positionNumber (int): The position count (int): The number of templates to be deleted. Returns: True if successful or Fa...
def getMaxPacketSize(self): """ Gets the maximum allowed size of a single packet. Returns: Return the max size (int). Raises: ValueError: if packet size is invalid Exception: if any error occurs """ packetMaxSizeType = self.getSystem...
This function uploads finger characteristics data to a specified buffer (CHARBUFFER1 or CHARBUFFER2), handling packetization, error checking, and verification. It validates inputs, sends upload commands, processes data packets, and confirms success by comparing uploaded data with the original.
def uploadCharacteristics(self, charBufferNumber = Finger.CHARBUFFER1, characteristicsData = [0]): """ Uploads finger characteristics to specified char Finger. Author: David Gilson <vnpqd@example.com> Arguments: charBufferNumber (int): The char Finger. Use `Fing...
def getTagIndexes(self, box=False): """Find points in the textBox widget where tags should be added""" if not box: focus = self.master.master.getFocus() else: focus = box if focus is self.rewriteBox: text = self.rewriteBox.get(1.0, "end").split("\n") ...
The method updates tags for either self.textBox or self.rewriteBox based on the 'box' parameter. It manages a change counter: if less than 2, it increments and marks tags as outdated; otherwise, it retrieves tag indexes, adds tags, updates links, resets the counter, records the current time, and marks tags as up to dat...
def updateTags(self, box=False): """Update tags for self.textBox or self.rewriteBox""" if self.changeCounter < 2: self.changeCounter += 1 self.tagsUpToDate = False else: if not box: self.getTagIndexes() self.addTags() ...
def newLine(self): """Make new lines keep the same indentation""" self.tabbed = 0 focus = self.master.master.getFocus() if focus is self.textBox: lineNum, columnNum = self.textBox.index("insert").split(".") line = self.textBox.get(str(lineNum) + ".0", str(lineNum...
This code initializes a text frame with two text areas (textBox and rewriteBox), each linked to a scrollbar for vertical scrolling. It sets up configurations for text formatting, binds keyboard events for actions like new lines, indentation, and modification tracking, and initializes variables to manage the text state,...
def __init__(self, master, root): """Initialise textFrame""" self.master = master self.root = root self.testMessage = "textFrame is initialised" self.Frame = Frame(style="TB.TFrame") self.Frame.pack(fill=BOTH, expand=1, side=TOP) self.textBox = Text(self.Frame...
def processoutput(self, data): for byte in data: if not byte: #NUL continue if self.controlsequence: if byte >= 0x40 and byte <= 0x7e: cmd = byte.to_bytes(1, byteorder='big') self.controlsequence = False ...
This function handles event processing in a Pygame loop, managing QUIT events, custom data events for capture/output, connection closure, keyboard input, and screen rendering with scaling and cursor updates. It continuously processes events, updates the display, and terminates the Pygame session upon exit.
def loop(self): while True: event = pygame.fastevent.wait() if event.type==pygame.QUIT: print("QUIT event received.") if self.endpoint: self.endpoint.close() break if event.type==self.readevent: ...
def update_csp(self, x, y, flagging): self.remaining_spaces -= 1 self.unprobed.remove(self.vboard[y][x]) if self.board.grid_actual[y][x] == 9: self.remaining_bombs -= 1 self.vboard[y][x].value = 1 elif flagging: # print("DEBUG: ALGORITHM MADE A MISTAKE...
The code determines the next move in a Minesweeper game by analyzing constraints via a CSP (Constraint Satisfaction Problem), using backtracking to solve clusters of constraints, and calculating probabilities to identify guaranteed mines/safe tiles or optimal guesses. It prioritizes queued tiles, resolves constraints, ...
def get_choice(self, details): self.details = details # If it is the first move we just return the safe space and add its constraints if self.board.first_move: self.board.first_move = False self.update_csp(self.board.start_x, self.board.start_y, False) return...
def __private_webdriver_setup() -> webdriver: try: options = Options() # Code to disable notifications pop up of Chrome Browser options.add_argument("--disable-notifications") options.add_argument("--disable-infobars") options.add_argument("--mute-aud...
This code initializes a Facebook page info scraper by setting up a web driver if not already initialized, storing the provided link, fetching CSS layouts, and extracting text and links from both old and new layout elements to gather page information.
def __init__(self, link): if not FacebookPageInfoScraper.driver: FacebookPageInfoScraper.driver = self.__private_webdriver_setup() self.background_image_followers = "https://static.xx.fbcdn.net/rsrc.php/v3/y9/r/arPWOVoq57s.png" self.background_image_likes = "https://static.xx...
def mean(u, sigma, p): X = [ [[2], [4]], [[-1], [-4]], [[-1], [2]], [[4], [0]] ] res = np.array([[0.0], [0.0]]) for x in X: res += clusterP(x, u, sigma, p) * np.array(x) res2 = 0.0 for x in X: res2 += clusterP(x, u, sigma, p) return res / re...
The code computes the normalized probability of data point x under a given cluster model (defined by u, sigma, p) relative to two alternative cluster models (u1, sigma1, p1) and (u2, sigma2, p2), using a joint probability function. It returns the ratio of the target cluster's joint probability to the sum of joint proba...
def clusterP2(x, u, sigma, p): u1 = mean([[2], [4]], [[1,0],[0,1]], 0.7) u2 = mean([[-1], [-4]], [[2,0],[0,2]], 0.3) sigma1 = var([[2], [4]], [[1,0],[0,1]], 0.7) sigma2 = var([[-1], [-4]], [[2,0],[0,2]], 0.3) p1 = newP([[2], [4]], [[1,0],[0,1]], 0.7) p2 = newP([[-1], [-4]], [[2,0],[...
def Create_Grid(): #create the grid Grid = [] #list of lists for i in range(3): row = [] #Row major for j in range(3): element = 0 row.append(element) #add a bunch of zeros to each row Grid.append(row) #add the rows to the Grid return Grid def CoinFlip(): #Flip a coin ...
The code runs a game on a grid, alternating between computer and AI turns based on a coin flip. It checks for win/tie conditions after each move, returning 1 (computer win), 2 (AI win), or 3 (tie). The loop continues until a terminal state is reached.
def Play(): Grid = Create_Grid() #create the Grid turns = 0 #variable to keep track of turns Flip = CoinFlip() #call CoinFlip() and store it into Flip if Flip == 1: #if Flip is 1, then it's the AI's turn turns += 1 #add 1 to turns to signal it's the AI's turn while True: print("\n") Pr...
def Create_Grid(): #create the grid Grid = [] #list of lists for i in range(3): row = [] #Row major for j in range(3): element = 0 row.append(element) #add a bunch of zeros to each row Grid.append(row) #add the rows to the Grid return Grid def CoinFlip(): #Flip a coin ...
The main task of the code is to simulate a turn-based game on a grid, alternating between a computer and AI player. It starts with a coin flip to determine the first turn, then repeatedly prints the grid, executes the respective player's move, checks for a win or tie, and returns the result (1 for computer win, 2 for A...
def Play(): Grid = Create_Grid() #create the Grid turns = 0 #variable to keep track of turns Flip = CoinFlip() #call CoinFlip() and store it into Flip if Flip == 1: #if Flip is 1, then it's the AI's turn turns += 1 #add 1 to turns to signal it's the AI's turn while True: print("\n") Pr...
def read_tweets_csv(filename): import csv from datetime import datetime filename_split = filename.split('/') output_file_name = filename_split[-1].split('.csv')[0] f = open(filename) csv_f = csv.reader(f) fil_split = filename.split('/') name = fil_split[len(fil_split) - 1].split('.'...
The code processes a CSV file of tweets to analyze sentiment polarity for Trump and Clinton by U.S. states. It cleans tweets, filters for relevant candidates, calculates average polarity per state, and generates maps saved as text files for visualization.
def cal_election(filename): filename_split = filename.split('/') output_file_name = filename_split[-1].split('.csv')[0] read_tweets_csv(filename) tweet_df_passive = clean_tweets(output_path+output_file_name+'.txt.') #tweet_df_passive = cleanTweets(tweet_df_passive) map_df = tweet_df_passive...
def _send_file_attachment(self, method: str, uri: str, files_names: List[str], payload: dict={}, headers: dict={}) -> dict: self._session.headers.update({ 'content-type': None }) headers = { 'content-disposition': 'form-data; name="payload_json"' } payload: dict = { 'payload_json': json.dumps(pa...
This function creates a message for a specified Discord channel, handling both regular content and file attachments. It constructs a payload with provided parameters, filters out None values, and sends the message via POST request. If files are included, it determines whether to send them as file paths (strings) or byt...
def create_message(self, channel_id, content: str=None, tts: bool=None, embeds: List[dict]=None, allowed_mentions=None, message_reference=None, components: list=None, files: Union[List[str], List[bytes]]=None, attachments: List[dict]=None, ...
def handle_cli() -> bool: """ handles command line arguments and returns flag, whether networth should be plotted. possible flags: `--plot` - plots networth history. `--help` - show usage. :return: flag indicating, if networth should be plotted. """ parser = argparse.ArgumentPa...
The main task of the code is to calculate the total portfolio value in euros by loading stock positions from a CSV, computing their current and historical values (accounting for special cases like "Bank" tickers and euro assets via exchange rates), logging results, converting totals to euros, and optionally plotting hi...
def main(): flag = handle_cli() # load positions from .csv tickers, amounts, avg_prices = load_positions() # calculate total value of all positions total_current_value = 0 total_buy_value = 0 for i in range(len(tickers)): value = 0 buy_amount = 0 ticker = ticke...
def load_config(filename="config.json"): path = Path.joinpath(Path(user_config_dir(appname)), filename) if not path.is_file(): create_config() with open(path, "r", encoding="utf-8") as file: return json.load(file) def random_username(length=10): randomSource = string.ascii_letters + string.digits username = "...
The code parses command-line arguments to interact with a temporary email service (OneSecMail). It allows retrieving specific emails by ID, viewing recent emails, generating usernames, setting domains, and opening emails in a browser. It updates configuration settings based on arguments, validates domains, and uses the...
def parse(): argparser = ArgumentParser() argparser.add_argument("id", help="id of the email received", type=int, default=None, nargs="?") argparser.add_argument("-g", "--generate", dest="username", help="generate new username or use given.", type=str, nargs="?", default=SUPPRESS) argparser.add_argument("-r", "--re...
def sample_C(self,b_size): if self.sampleC_fun: return self.sampleC_fun(b_size).to(self.device) else: C = torch.zeros(size=(b_size,self.num_data_points)).to(self.device) # locations labels = t...
The main task of the code is to train a conditional GAN (Generative Adversarial Network) with discriminator and generator models, optimizing their parameters using Adam or RMSprop. It iteratively trains the discriminator and generator over multiple epochs, tracks losses, generates synthetic data with fixed noise, evalu...
def train_loop(self,num_epochs,device,lr,d_steps, print_iterations, num_fixed_noises=10): num_anomalies = self.num_anomalies img_list = [] evaluation_list = [] fft_values = [] eval_values = [] G_losses = [] D_losses = [] iters = 0 ...
def parse_source(self): corpus = [] labels = [] with open("../dataset_pr.pkl", "rb") as file: dataset = pickle.load(file) for pattern in self.patterns: pattern_samples = dataset[pattern][:] random.seed(666) random.shuffle(pattern_samples) pattern_samples = pattern_samples[:self.negative_sampling]...
The main task of the code is to process source code data by parsing it, splitting into training/validation/test sets, training word embeddings, and generating normalized datasets for each split to prepare for machine learning tasks.
def run(self): print('parse source code...') self.parse_source() print('split data...') self.split_data() print('train word embedding...') self.dictionary_and_embedding(None, 32) print('generate normal data...') self.generate_normal_data('train') self.generate_normal_data('val') self.generate_normal...
def getValidMoves(self, board): '''Returns a list of valid moves''' validCols = [] for c in range(NUM_COLS): if self.isValidMove(board, c): validCols.append(c) return validCols def isTerminal(self, board): ''' Checks if the current board state is Game Over Returns a tuple, with [0] being the True o...
The code implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move for a player in a game. It recursively evaluates all valid moves, alternating between maximizing (AI) and minimizing (human) strategies, while pruning suboptimal branches to improve efficiency. The function returns the best ...
def minimax(self, board, depth, maxOrMin, alpha, beta, localMaxDepth): ''' Recursively finds the best move for a given board Returns the column in [0] and score of the board in [1] ''' validMoves = self.getValidMoves(board) random.shuffle(validMoves) gameOver, winner = self.isTerminal(board) if gameOver...
def minimax(self, board, depth, maxOrMin, alpha, beta, localMaxDepth): ''' Recursively finds the best move for a given board Returns the column in [0] and score of the board in [1] ''' validMoves = self.getValidMoves(board) random.shuffle(validMoves) gameOver, winner = self.isTerminal(board) if gameOver...
The code calculates the AI's optimal move using iterative deepening and minimax with alpha-beta pruning, prioritizing winning moves. It iterates through increasing search depths, breaks early if a win is detected, executes the move on the board, checks the game state, and returns the chosen move.
def playBestMove(self, board): '''Calculates and performs the best move for the AI for the given board''' # input("Press enter for the AI to perform its move.") col = input("It's the AI's turn, press enter for it to play.\t") move, score = -123, -123 # placeholders for i in range(1, MAX_DEPTH + 1): # iterativ...
def get_or_upload_log(self): """Get log from database, if not there, upload it.""" if len(self.get_django_log()) == 0: print(f"{datetime.datetime.now()} Uploading log") if self.log_path: r = self.upload_log() if self.log_url: r = se...
The code processes a log by retrieving or uploading it, validates encounter data, handles errors, updates database entries with log details like duration, players, and boss info, and returns the DpsLog object or False on failure. It also checks for log integrity, requests detailed data when needed, and updates addition...
def run(self): """Get or upload the log and add to database Returns ------- False on fail DpsLog.object on success """ print(f"{datetime.datetime.now()} Start processing: {self.log_source_view}") self.r = r = self.get_or_upload_log() if r is Fals...
def greeting_intent(intent_request): session_attributes = get_session_attributes(intent_request) message = { 'contentType': 'PlainText', 'content': "Hi! How Can I Help you?" } return elicit_intent(session_attributes, message) def dining_suggestions_intent(intent_request): ...
The code defines a `dispatch` function that routes incoming intent requests to specific handler functions based on the detected intent name. It checks the intent type (e.g., Greeting, Dining Suggestions, Thank You) and invokes the corresponding function. If the intent is unsupported, it raises an exception. This serves...
def dispatch(intent_request): intent_name = intent_request['sessionState']['intent']['name'] if intent_name == 'GreetingIntent': return greeting_intent(intent_request) elif intent_name == 'DiningSuggestionsIntent': return dining_suggestions_intent(intent_request) elif intent_name == 'T...
def load_nli_paws_dataset(file_name: str) -> Dict[str, List[List[str]]]: """ Load and prepare the STS dataset from a compressed TSV file. Args: file_name (str): The path to the compressed TSV file. Returns: Dict[str, List[List[str]]]: A dictionary containing NLI dataset splits with sen...
The function trains and evaluates a BERT-based model for natural language inference (NLI) using the PAWS dataset. It loads and tokenizes training/validation data, initializes a custom BERT architecture with pre-trained weights, sets up an AdamW optimizer, and executes a training loop with validation and testing phases ...
def train_and_evaluate(model, tokenizer, test_dataloader, num_epochs=3, batch_size=8, maxlen=128): device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") bert_path = 'weights/bert_tiny.bin' nli_dataset = load_nli_paws_dataset('data/AllNLI.tsv.gz') print('Train:', len(nli_dat...
def get_current_scores(self): scores = {} exists = {} for player in self.players: scores[player.number] = {} exists[player.number] = {} history_scores = models.Score.objects.filter(game=self.session).order_by('-created_at') count_known = 0 ...
This function calculates and updates racing scores from session data. It retrieves current scores, processes data from the 'Data' model, updates lap counts, handles sector values, and stores results in the 'Score' database. It checks for existing entries to update or insert new records, ensuring accurate tracking of ra...
def calc_socres(self): if not self.game_id > 0 or not self.session : return False # get session by game id result = self.get_current_scores() scores = result['scores'] exists = result['exists'] if FLAG_FEED_DATA : # from datas table data_from_datas = models.D...
def read_file(file_name: str) -> str: """ Opens file, reads it and returns file content Args: file_name (str): file name to open Returns: str: file contents """ try: with open(file_name) as config_file: data = config_file.read() return data ...
The main task of the code is to load and validate a configuration file, ensuring correct boat types, quantities, and positions. It reads the JSON file, checks for missing or invalid boat types, verifies boat counts match expected values, and converts boat positions to grid indexes. Errors like invalid JSON, missing/inv...
def load_configuration(self) -> None: """ load configuration file and convert human fleet address to grid indexes This method feeds self.fleet_configuration method Raises: ConfigurationException: if configuration file or data was invalid """ # read config fil...
def stalkerPile(list): return randint(0, len(list)-1) def viewGen(): finalView = viewPile(genPeopleView) finalAnswer = "" if finalView in genPosView: finalAnswer = genPosAnswer[stalkerPile(genPosAnswer)] return finalView, finalAnswer if finalView in genNegView: finalAns...
The code generates a randomized stalker character profile with attributes like appearance, goals, injuries, and interactions, using lists and the stalkerPile() function to select traits. It formats these into a narrative describing the stalker's background, experiences, and relationships in "The Zone," returning a stru...
def stalkerGen(): appearance = genAppearance[stalkerPile(genAppearance)] hairColor = genHairColor[stalkerPile(genHairColor)] hairType = genHairType[stalkerPile(genHairType)] eyeColor = genEyeColor[stalkerPile(genEyeColor)] eyeType = genEyeType[stalkerPile(genEyeType)] goal = genGoal[stalkerPile(...
def create_csr(name): key = create_private_key(name) csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"San ...
The code requests a certificate from a Certificate Authority (CA) by generating a Certificate Signing Request (CSR), sending it to a local server, and returning the issued certificate along with the private and public keys in PEM format if the request succeeds. It also verifies key pair compatibility and includes a pla...
def request_cert_from_ca(name): private_key, csr = create_csr(name) url = 'https://127.0.0.1:8090/ca/create_cert' data = {'name': name, 'csr': serialize_csr(csr)} # TODO - place symmetric encryption here on data r = requests.post(url, data, verify=False) if r.json().get('success', False) is True...
def get_words(file): sentences = "" open_file = open(path + "/" + file) # open the file reader = iter(open_file) # set read to read file for line in reader: sentences += line # add data in to full data sentences = re.sub('[0-9’!"#$%&\'()*+,-./:;<=>?@,。?★、…【】《》?“”‘’![\\]^_`{|}~]+', '', sen...
This function calculates the similarity between a given file and all other files in a database using TF-IDF vectors and Euclidean distance. It retrieves and prints the top 10 most similar files based on the computed distances.
def top_ten_retrieve(file_name): file_words = get_words(file_name) file_tfidf = get_tfidf(file_name) distance_result = {} complete = 0 # calculate the distance between all files for data in files: # read the data form the database distance = 0 data_words = get_words(data) ...
def get_table_column() -> TableColumnItem: return TableColumnItem( name=_get_random_name(), data_type=random.choice(_get_column_data_types()), null=random.choice([True, False]), comment=_get_random_comment() ) def _get_random_name() -> str: return f"{get_random_word()}_{_get_...
The code generates a TableItem with a specified number of columns (default 200) by creating a list of columns using get_table_column(), then returns a TableItem instance with the provided database, a random name, the generated columns, and a random comment.
def get_table_item(database: DatabaseItem, column_size=200) -> TableItem: columns = [] for i in range(column_size): columns.append(get_table_column()) return TableItem(database=database, name=_get_random_name(), columns=columns, comment=_get_random_comment())
def check_com(self): # s = serial.Serial('COM6') # print("reading com6") try: data = self.s.readline()[:-2] #the last bit gets rid of the new-line chars # data = re.findall(r'\d+', data)[0] except SerialException: print("doh") if data: print("read:") data = data.decode...
The main task of the code is to execute three key operations: validating communication components via `check_com()`, verifying conditions with `check_Q()`, and updating system settings through `update_settings()`. These steps ensure proper functionality, data integrity, and configuration readiness before proceeding wit...
def runp(self): self.check_com() self.check_Q() self.update_settings()
def normalize(coor,threshDistance ,threshAngle): x, y,t = coor x = round(x / threshDistance) * threshDistance y = round(y / threshDistance) * threshDistance t = round(t / threshAngle) * threshAngle return [x, y, t] def distance(startPosition, goalPosition): sx, sy,_ = startPosition gx, gy,_ ...
This function generates a collision-free path for a robot from a start to a goal position using a priority queue-based search algorithm. It explores possible states by applying 8 predefined motion actions, checks if new states are within clearance constraints, and updates the path if a lower-cost route is found. The al...
def generatePath(q, startEndCoor, nodesExplored,robotParams,dt,radiusClearance,threshDistance = 0.1,threshAngle = 5): # normalize goal and start positions sx, sy, st = normalize(startEndCoor[0],threshDistance,threshAngle) gx, gy, gt = normalize(startEndCoor[1],threshDistance,threshAngle) # Initializin...
def read_data(): ''' Read the train, dev, and test datasets ''' def read_d(file_name): data = pd.read_csv(f"{file_name}", header=0) train_Y = data['1'] # First column is the labels column data = data.drop(['1'], axis=1) train_X = minmaxscaler(data) return train_X, pd.DataFrame(train_Y) raw_test_X = np....
The code trains a neural network model with specified hyperparameters (epochs, batch size, learning rate) and regularization. It loads training/development/test data, initializes the model architecture, configures an optimizer, and executes training. Finally, it generates predictions on the test dataset using the train...
def main(): # Hyper-parameters max_epochs = 500 batch_size = 16 learning_rate = 10**-3 num_layers = 1 num_units = 256 lamda = 0.0005 # Regularization Parameter train_input, train_target, dev_input, dev_target, test_input = read_data() net = Net(num_layers, num_units) optimizer = Optimizer(learning_rate) tr...
def rev_var(n): i = 0 j = 0 k = 0 div_i = 11 * 11 div_j = 11 if columns > 11: div_i = columns * columns div_j = columns if n > div_i: i = (n - 1) // div_i n = n - (i * div_i) if n > div_j: j = (n - 1) // (div_j) n = n - (j * div_j) k = ...
This code determines if the current board state has changed after applying a SAT-based solution to a Minesweeper puzzle, checking for win/loss conditions or cell updates. It returns True if changes occur or if the game state ends, otherwise False.
def solve_current_state(current_board, board_answer, mines): prev_board = [] for i in current_board: temp = [] for j in i: temp.append(j) prev_board.append(temp) [sat, solution] = sat_solve.solve(sat_solve, current_board, mines) for i in range(1, len(solution)): ...
def generate_numbers(board, r, c): new_board = board for i in range(0, r): for j in range(0, c): if new_board[i][j] != mine: count = 0 for a in range(-1, 2): for b in range(-1, 2): if (a + i > -1 and a + i < rows) an...
The main task of the code is to generate a Minesweeper board with `n` mines on an `r x c` grid, ensuring mines are not placed on or adjacent to the first clicked cell (`first`). It initializes a board with mines marked as `9` and safe cells as `10`, avoiding conflicts with the initial move. For `setup != -1`, it also i...
def mine_board(r, c, n, first, setup): if setup == -1: random.seed() mines = [] for x in range(0, n): check = True i = -1 j = -1 while check == True: check = False i = random.randint(0, r - 1) j =...
def create_empty_board(r, c): board = [] for i in range(0, r): temp_list = [] for j in range(0, c): temp_list.append(10) board.append(temp_list) return board def print_board(board): for i in board: for j in i: if j == 9: print(" *",...
The code implements a Minesweeper game where the player (or AI) interacts with a board, using a solver and guesser to uncover cells and avoid mines. It initializes the board, processes mine placement, and iteratively updates the game state. The loop handles turns, checks for win/loss conditions, and uses a SAT solver t...
def play(r, c, fast, setup): # States: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 # 0 = No mines next to it # 9 = mine # 10 = Not Discovered current_board = create_empty_board(rows, columns) print_board(current_board) # r = int(input("What is your row?")) # c = int...
def test(cases): testcases = [] # ([capacities], target, correct answer) testcases.append(([1,4,10,15,22],181,20)) testcases.append(([2,5,6,72],143,7)) testcases.append(([3,6],2,-1)) testcases.append(([2],143,-1)) testcases.append(([1,90,200],20,-1)) for i in cases: capacities = ...
The main task of the code is to execute a series of tests using an A* algorithm on different input configurations. It first runs predefined test cases, then processes `.txt` files from a directory, loading capacities and targets, sorting capacities, and applying the A* algorithm to compute solutions. The results are co...
def main(): # test cases = [0, 1, 2, 3, 4] test(cases) return test_path = './tests/' txt_files = [f for f in os.listdir(test_path) if f.endswith('.txt')] answers = [] for i in range(len(txt_files)): capacities, target = load_file(test_path + txt_files[i]) capac...
def h(p1, p2): x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2) def reconstruct_path(came_from, current, draw): while current in came_from: current = came_from[current] current.make_path() draw() x,y = current.get_pos() path.append([x,y]) path.reverse() np.savetxt("pathvalues.csv", ...
This code implements the A* pathfinding algorithm on a grid. It uses a priority queue to explore nodes, calculating the shortest path from a start to an end node by evaluating 'g_score' (distance from start) and 'f_score' (estimated total cost). The algorithm visualizes the search process using Pygame, updating node st...
def algorithm(draw, grid, start, end): count = 0 open_set = PriorityQueue() open_set.put((0, count, start)) came_from = {} points = {} g_score = {node: float("inf") for row in grid for node in row} #Shortest distance from start node to end node g_score[start] = 0 f_score = {node: float("inf") for row in...
def make_grid(rows, width): grid = [] gap = width // rows for i in range(rows): grid.append([]) for j in range(rows): node = Node(i, j, gap, rows) grid[i].append(node) return grid def draw(win, grid, rows, width): for row in grid: for node in row: node.draw(win) draw_grid(win, rows,...
This code initializes a grid-based pathfinding visualization using Pygame, reads coordinates from a CSV file to set start/end points, and executes a pathfinding algorithm (e.g., A*). It creates a 50x50 grid, processes Tello drone coordinates from 'cordinates_tello.csv', updates node neighbors, and runs the algorithm wi...
def main(win, width): ROWS = 50 grid = make_grid(ROWS, width) start = None end = None run = True pygame.init() while run: draw(win, grid, ROWS, width) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False graph_data = open('cordinates_tello.csv','r').read() ...
def stari_posibile_pune_piese(stare_joc_parinte, jucator, max_depth, depth, camera=False): configuratii_posibile = [] piese_tabla = stare_joc_parinte.piese_tabla JMIN_piese = stare_joc_parinte.JMIN_num_piese JMAX_piese = stare_joc_parinte.JMAX_num_piese if depth == max_depth: stare_joc_pari...
The code implements a minimax algorithm with depth limitation for a game involving placing and moving pieces. It evaluates game states using a heuristic, recursively exploring possible moves (placing or moving pieces) up to a specified depth. The function selects the optimal move by choosing the maximum (for the initia...
def min_max_pune_piese(stare_joc: StareJoc, heuristic, jucator_initial, jucator, max_depth=3, depth=3): # configuratie_tabla_rezultata = np.random.choice([-1, 0, 1], size=24) # date de test random if depth <= 0: stare_joc.estimare = stare_joc.estimare_scor(depth, jucator_initial, heuristic) ret...
def stari_posibile_pune_piese(stare_joc_parinte, jucator, max_depth, depth, camera=False): configuratii_posibile = [] piese_tabla = stare_joc_parinte.piese_tabla JMIN_piese = stare_joc_parinte.JMIN_num_piese JMAX_piese = stare_joc_parinte.JMAX_num_piese if depth == max_depth: stare_joc_pari...
This function implements the Alpha-Beta pruning algorithm for a game involving placing/moving pieces. It evaluates game states recursively, considering depth limits and heuristic scoring. It generates possible moves, evaluates them through recursive calls, and selects the optimal move by comparing estimated scores, upd...
def alpha_beta_pune_piesa(stare_joc: StareJoc, heuristic, jucator_initial, jucator, alpha, beta, max_depth=3, depth=3): if depth <= 0: stare_joc.estimare = stare_joc.estimare_scor(depth, jucator_initial, heuristic) return stare_joc if alpha > beta: return stare_joc # este intr-un inter...
def calculeaza_piese_in_moara(self, jucator): enemy_counter_pieces_in_morris = 0 player_counter_pieces_in_morris = 0 for index, valoare in enumerate(self.piese_tabla): if valoare == jucator: if self.check_moara(index, jucator): player_counter_piece...
The function estimates a game score based on specified heuristics, evaluating factors like closed morrises, blocked pieces, 2-piece configurations, and winning states. It returns heuristic-specific scores or a weighted combination of multiple factors for the "Best heuristic," prioritizing winning configurations and clo...
def estimare_scor(self, depth, jucator, heuristic): # number of pieces in morris enemy_pieces_in_morris, player_prices_in_morris = self.calculeaza_piese_in_moara(jucator) # ( 1 ) # Closed Morris: # 1 if a morris was closed in the last move by the player # -1 if a morris...
def get_bitesize(query: str): """Function: get_bitesize @params query: the string query inputted by the user Web scrapes from a specific BBC Bitesize article and returns the paragraphs, title and link from the article given the search query. """ link, title = get_bitesize_articleURL(query) ...
The function `bitesize` retrieves a Bitesize article's title, link, and word frequency list based on a user query. It performs web scraping, saves raw data to a file, processes text to extract headers, and generates a frequency list. The output includes the article title, link, and keyword frequency analysis for furthe...
def bitesize(query: str): """Function: get_bitesize_articleURL @params query: the string query inputted by the user The main bitesize function, which collates the other three functions. Returns the title, link and freqlist from the bitesize article given a search query. Also interfaces with a f...
def Euclid(p1, p2): return Minkowski(p1, p2, 2) def Supremum(p1, p2): return abs(p1 - p2).max() def MSE(p1, p2): return _square(p1 - p2).mean() def RMSE(p1, p2): return _sqrt(MSE(p1, p2)) def NRMSE(p1, p2): return RMSE(p1, p2) / (max(p1) - min(p1))
(EvaluateSets computes pairwise error metrics between corresponding columns of two dataframes p1 and p2. It calculates Euclidean distance, Supremum norm, MSE, RMSE, and NRMSE for each column, storing results in a DataFrame indexed by column names. The function returns this metric DataFrame, enabling comparative analysi...
def EvaluateSets(p1, p2, cols=None): if cols is None: cols = p1.columns df = _DataFrame(index=cols, columns=['Euclid', 'Supremum', 'MSE', 'RMSE', 'NRMSE']) for col in cols: df['Euclid'][col] = Euclid(p1[col], p2[col]) df['Supremum'][col] = Supremum(p1[col], ...
def torch2icdf(x): x=x.numpy() x=np.log2(x+1) x=np.sum(x, 0) x=1/x x[x==np.inf]=0 return pd.DataFrame({'x':list(range(len(x))), 'y': x }) def __getitem__(self, index): pwm_processed = self.center_pad_pwm(self.AA_PWM_dict_list[index]['pwm']) aa_mat_processed = self.pad_aa_seqmat(s...
The main task of the code is to plot aggregated information content (IC) values across centered PWM positions using a specified aggregation function. It processes IC data from a dataset, groups values by position, applies the aggregation function, and visualizes the results as a bar chart with appropriate axis labels a...
def plot_ic(self, aggfn): all_ic = [ torch2icdf(self.__getitem__(i)[1]) for i in range(self.__len__()) ] all_ic = pd.concat(all_ic) summed_ic = all_ic.groupby('x').agg(aggfn).reset_index(drop=False) import plotnine as pn p=( pn.ggplot(summed_ic) + ...
def findChild(self, node): while not node.state.IsTerminal() and node.IsFullyExpanded: node = self.findBestChild(node) return node def playout(self, node): curState = node.state.Copy() while not curState.IsTerminal(): if self.actionMethod == "intelligent": action = curState.GetIntelligentAction() ...
The code performs Monte Carlo Tree Search (MCTS) for `iterations` to determine the next optimal action. It repeatedly selects a node, expands it if not terminal, simulates a playout, and backpropagates results. Finally, it returns the most visited child of the root node, representing the best action identified through ...
def findNextAction(self, iterations): for _ in range(iterations): # 1 selection node = self.findChild(self.root) # 2 expansion if not node.state.IsTerminal() and not node.IsFullyExpanded: node = node.expand() # 3 playout result = self.playout(node) # 4 backpropagation self.backpropagate...
def negate(str): if '~' in str: return re.sub('~', '', str) return '~' + str def pl_resolution(sos,clauses_set): new = set() memory = set() while True: for a,b in select_clauses(clauses_set): if a not in sos and b not in sos: continue ...
The code processes logical clauses and user commands to manage a clause set, applying resolution and negation checks. It handles '?', '+', and '-' commands to add/remove clauses, check for contradictions via pl_resolution, and update the SOS set. The main task is automated reasoning with clause manipulation and resolut...
def call_cooking(clauses, commands): clauses_set = set() sos = set() for x in clauses: if 'v' in x: ntorka = tuple(x.split(' v ')) flag = False for x in set(ntorka): for y in set(ntorka): if negate(x) == y: ...
def read_clauses_from_file(file_path): clauses_list = [] with open(file_path, 'r') as file: for line in file: cleaned_line = line.strip().lower() if not cleaned_line.startswith('#') and cleaned_line: clauses_list.append(cleaned_line) return clauses_list def pr...
The main task of the code is to process logical clauses based on a specified mode. If the mode is "resolution," it prints the clauses. If the mode is "cooking," it reads user commands from a file and applies them to the clauses. The code handles command-line arguments, validates the mode, and executes corresponding ope...
def main(): mode = sys.argv[1] clauses_file = sys.argv[2] if mode != "resolution": commands_file = sys.argv[3] clauses = read_clauses_from_file(clauses_file) if mode == "resolution": print_res(clauses) elif mode == "cooking": commands = read_user_commands_from_file(comm...
def most_common_label(self, dataset): labels = self.get_labels(dataset) labels.sort() counter = Counter(labels) return counter.most_common(1)[0][0] def entropy(self, dataset): labels = self.get_labels(dataset) freq = Counter(labels) ent = 0 for x in freq: ...
This code implements the ID3 algorithm to build a decision tree recursively. It selects the most discriminating feature, splits the dataset accordingly, and constructs subtrees until stopping conditions (maximum depth or zero entropy) are met, returning Leaf or Node structures to represent the tree.
def id3(self, d, d_par, X, depth=0): if depth == self.hiperparam: return Leaf(self.most_common_label(d)) if not d: return Leaf(self.most_common_label(d_par)) v = self.most_common_label(d) if not X or self.entropy(d)...
def get_waveform_freq(fs, params): return get_amp(fs, params) * np.exp(1.j * get_phase(fs, params)) def inner(a, b, Ss, df): integrand = 4. * (np.real(a)*np.real(b) + np.imag(a)*np.imag(b)) / Ss inner_prod = integrate(integrand, dx=df) return inner_prod def partial_waveform(freqs, params, index): ds...
The code computes a metric matrix that quantifies the relationship between parameters in a signal model. It calculates normalized waveforms and their partials, then computes a symmetric matrix where each element represents a derived metric based on inner products of these components, adjusted by SNR. This matrix likely...
def metric(freqs, params, Ss, df): waveform = get_waveform_freq(freqs, params) normalization = 1 / np.sqrt(inner(waveform, waveform, Ss, df)) norm_waveform = normalization * waveform partials = [partial_waveform(freqs, params, i) for i in range(num_params)] norm_partials = normalization * np.array(p...
def is_compound(x): if "(" in x: return True else: return False def get_variable(str_args): args = str_args.split(",") for arg in args: if not is_variable(arg): args.remove(arg) return args def get_args(a): if is_compound(a): return a[a.find("(")+1:len...
This function replaces variables in a compound statement with corresponding values from a substitution dictionary. It iterates through variables in the statement's arguments, checks if they exist in the substitution, and replaces them. The modified statement is returned after all applicable substitutions are applied.
def substitute(statement, subst): if is_compound(statement): for i in get_variable(get_args(statement)): if i in subst.keys(): statement = replace_var_val(statement, i, subst[i]) return statement
def break_contractions(self, tokenized: list[list[str] | str]) -> list[str | list[str]]: """ Break contractions on the given input :param tokenized: A list[str | list[str]], from which we replace contractions :returns: A list[str | list[str]], with replaced contractions ...
This function breaks text contractions (e.g., "won't" → "will not") after tokenizing based on the specified `acting_on` parameter. If `acting_on` is `WORD`, it tokenizes by words with punctuation and splits contractions. If `acting_on` is `WORD_SENT`, it tokenizes by word-sentence boundaries with punctuation and simila...
def break_contractions_on(self, acting_on: utils.TokenizeType) -> list[list[str] | str]: """ Breaks contractions after tokenizing on the given tokenize type :param acting_on: The tokenization type to break our text into :returns: A list[str | list[str]], depending on `acting...
def call(self): self.contexts = list(pathlib.Path(self.segm_parquet_dir).glob('*.parquet')) self.contexts_cam_images = list(pathlib.Path(self.dataset_im_parquet_dir).glob('*.parquet')) self.allcontexts = self.saveallcontextsmapping() self.allcontextsindexed = list(enumerate(self.allconte...
This code defines a method that performs data conversion based on the mode specified in self.trainvaltest. It handles 'train', 'val', 'test', or 'all' modes, switching defaults and executing the conversion process (via self.call()) for each dataset type. For 'all', it sequentially processes train, val, and test dataset...
def __call__(self): if self.trainvaltest == 'train': print("Conversion of train data started") self.call() print("Conversion of train data completed") elif self.trainvaltest == 'val': self.changedefaulttraintoval() print("Conversion of val data...
def is_a_dialog_open_and_focused(): window = Krita.instance().activeWindow() if window: widget = QtWidgets.QApplication.focusWidget() return is_widget_in_dialog(widget) return False def get_active_doc(): return Krita.instance().activeDocument() def export_image(doc): if doc and doc....
The code's main task is to prevent Krita from exporting images when a dialog is open, avoiding a bug where silent exporting closes dialogs. It checks if a dialog is focused by examining the focused widget's ancestors, ensuring performance. If no dialog is open, it exports the active modified document after updating its...
def onTick(): # There seems to be a bug with Krita where silent exporting closes any open dialogs. # This code is a workaround that detects whether a dialog is open and skips exporting when there is. # To remain performant, this code doesn't search the whole widget tree. # Instead, it only checks the fo...
def bandwidth(self, tau): h0 = min((len(self.mX) + np.log(self.n)) / self.n, 0.5) ** 0.4 return max(0.01, h0 * (tau - tau ** 2) ** 0.5) def fit(self, tau=0.5, h=None, kernel="Laplacian", beta0=np.array([]), res=np.array([]), weight=np.array([]), standardize=True, adjust=True): ''' ...
The function generates multiplier bootstrap estimates for quantile regression coefficients. It fits a model using specified kernel and weight distributions, then performs bootstrapping by resampling residuals with given weights. The output includes the original estimate and bootstrap samples, with optional standardizat...
def mb(self, tau=0.5, h=None, kernel="Laplacian", weight="Exponential", standardize=True): ''' Multiplier Bootstrap Estimates Parameters ---------- tau : quantile level; default is 0.5. h : bandwidth. The default is computed by self.bandwidth(tau). kernel :...
def self_tuning(self, tau=0.5, standardize=True): ''' A Simulation-based Approach for Choosing the Penalty Level (Lambda) Reference --------- l1-Penalized Quantile Regression in High-dimensinoal Sparse Models (2011) by Alexandre Belloni and Victor Chernozhukov ...
The main task of the code is to perform iteratively reweighted L1-penalized estimation using a specified concave penalty (e.g., SCAD) to estimate regression coefficients. It initializes with an L1-conquer model, iteratively updates coefficients by reweighting the penalty based on current estimates, and adjusts for stan...
def irw(self, Lambda=None, tau=0.5, h=None, kernel="Laplacian", beta0=np.array([]), res=np.array([]), penalty="SCAD", a=3.7, nstep=5, standardize=True, adjust=True, weight=np.array([])): ''' Iteratively Reweighted L1-Penalized Conquer (irw-l1-conquer) Arguments ---------...
def self_tuning(self, tau=0.5, standardize=True): ''' A Simulation-based Approach for Choosing the Penalty Level (Lambda) Reference --------- l1-Penalized Quantile Regression in High-dimensinoal Sparse Models (2011) by Alexandre Belloni and Victor Chernozhukov ...
The function `boot_select` performs model selection via bootstrap for statistical models. It computes bootstrap estimates using specified regularization, smoothing, and penalty parameters, then applies two selection methods: majority vote (selecting variables frequently included in bootstrap models) and intersection (r...
def boot_select(self, Lambda=None, tau=0.5, h=None, kernel="Laplacian", weight="Multinomial", alpha=0.05, penalty="SCAD", a=3.7, nstep=5, standardize=True, parallel=False, ncore=None): ''' Model Selection via Bootstrap Arguments --------- ...
def cqr_self_tuning(self, XX, tau=np.array([])): cqr_lambda_sim = np.array([max(abs(XX.dot(self.cqr_conquer_lambdasim(tau)))) for b in range(200)]) return 2*cqr_lambda_sim def cqrp_admm_path(self, lambda_seq, tau, order="ascend", sg=0.03, maxit=20000): ''' ...
The code performs model selection for a Composite Quantile Regression (CQR) using the ADMM algorithm, optimizing parameters via Bayesian Information Criterion (BIC). It generates a sequence of models over varying regularization parameters (lambda_seq), computes BIC values incorporating model fit and complexity penaltie...
def cqrp_admm_bic(self, tau, lambda_seq=np.array([]), nlambda=100, order='ascend', max_size=False, Cn=None, sg=0.03): K = len(tau) X = self.X XX = np.tile(X.T, K) if not lambda_seq.any(): sim_lambda = self.cqr_self_tuning(XX, tau=tau) lambda_seq ...