dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
The main task of the code is to retrieve a user's perpetual account asset information by constructing an API request with a timestamp and cryptographic signature, then returning the response data from the "/openApi/swap/v2/user/balance" endpoint.
def get_perpetual_balance(self): """ Get asset information of user‘s Perpetual Account """ path = "/openApi/swap/v2/user/balance" url = self.ROOT_URL + path parameters = self.__generate_params(timestamp=self.get_timestamp()) body = self.__generate_params(params=pa...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This code retrieves a user's open perpetual swap positions by sending a signed GET request to an API endpoint. It constructs the URL, generates parameters with a currency pair and timestamp, creates a signed body, and processes the response. If no positions are found, it returns a message indicating none; otherwise, it...
def get_my_perpetual_swap_positions(self, pair="NULL"): path = "/openApi/swap/v2/user/positions" url = self.ROOT_URL + path parameters = self.__generate_params(currency=pair, timestamp=self.get_timestamp()) body = self.__generate_params(params=parameters, signature=self.__sign_hex(parame...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function places a market order to open a perpetual futures position on a specified trading pair with a given volume and position side (LONG/SHORT). It includes optional stop-loss (SL) and take-profit (TP) orders, converting them into JSON format. The function constructs API parameters, generates a signature, sends...
def open_market_order(self, pair, position_side, volume, sl="NULL", tp="NULL", client_order_id="NULL"): """ APIKEY must have 'perpetual futures trading' permission for this to work. :param pair: Symbol you want to trade i.e. BTC-USDT :param position_side: LONG/SHORT :param volum...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function closes a perpetual futures market position by executing a sell order for LONG positions or a buy order for SHORT positions. It generates signed API parameters, sends a POST request to the trading endpoint, and returns the order response. Key parameters include the trading pair, position side, volume, and ...
def close_market_order(self, pair, position_side, volume, client_order_id="NULL"): """ APIKEY must have 'perpetual futures trading' permission for this to work. :param pair: Symbol you want to trade i.e. BTC-USDT :param position_side: LONG/SHORT :param volume: Amount of trade fo...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function places a trigger market order for perpetual futures trading, specifying parameters like symbol, trade direction, position side, volume, trigger price, and optional take-profit/stop-loss settings. It constructs API request parameters, generates a signature, and sends a POST request to execute the order, re...
def place_trigger_market_order(self, pair, desicion, position_side, trigger_price, volume, trigger_price_type="NULL", client_order_id="NULL", time_in_force="NULL", tp="NULL", sl="NULL"): """ APIKEY must have 'perpetual futures trading...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function places a trigger limit order for perpetual futures trading, specifying parameters like symbol, trade direction, position side, entry price, volume, and trigger price. It includes optional stop-loss and take-profit configurations, generates API request parameters with a signature, and submits the order via...
def place_trigger_limit_order(self, pair, desicion, position_side, price, volume, trigger_price, trigger_price_type="NULL", client_order_id="NULL", time_in_force="NULL", tp="NULL", sl="NULL"): """ APIKEY must have 'perpetual futures tra...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function places a trailing stop market order on a perpetual futures contract, requiring an API key with trading permissions. It validates input parameters, constructs a signed request with details like symbol, order type, side, position side, volume, price/price rate, and sends it to the API endpoint. It returns t...
def place_trailing_stop_order(self, pair, desicion, position_side, volume, price="NULL", price_rate="NULL", client_order_id="NULL", time_in_force="NULL"): """ APIKEY must have 'perpetual futures trading' permission for this to work. :param pair: Symbol you want...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
Your return The function `place_test_order` simulates placing a test trade order on a perpetual futures platform without affecting real funds. It accepts parameters like trade type, symbol, position direction, price, volume, and stop-loss/take-profit details. The function constructs a request with these parameters, g...
def place_test_order(self, trade_type, pair, desicion, position_side, price, volume, stop_price, priceRate, sl, tp, working_type, client_order_id, time_in_force): """ APIKEY must have 'perpetual futures trading' permission for this to work. The participation and return a...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
The main task of the code is to close all open trading positions via a POST request to a specified API endpoint. It constructs the request URL, generates necessary parameters including a timestamp and signature, sends the request, and returns the API's response data. This function is part of a trading system's logic to...
def close_all_positions(self): """ Closes any open position based on Market price. """ path = "/openApi/swap/v2/trade/closeAllPositions" url = self.ROOT_URL + path parameters = self.__generate_params(timestamp=self.get_timestamp(), recvWindow="10000") body = s...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This code cancels an unfilled order by sending a signed API request to a trading endpoint, using parameters like order ID, symbol pair, client order ID, and a timestamp. It constructs a URL, generates required parameters, creates a cryptographic signature, and executes a GET request to cancel the specified order, retur...
def cancel_order(self, pair, order_id="NULL", client_order_id="NULL"): """ Cancel an order that is currently in an unfilled state """ path = "/openApi/swap/v2/trade/order" url = self.ROOT_URL + path parameters = self.__generate_params(orderId=order_id, symbol=pair, client...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This method cancels all open orders for a specified trading pair on a swap market. It constructs a DELETE request with parameters including the symbol, timestamp, and signature, then sends it to the API endpoint. The response data is returned, typically confirming order cancellations.
def cancel_all_orders_of_symbol(self, pair): path = "/openApi/swap/v2/trade/allOpenOrders" url = self.ROOT_URL + path parameters = self.__generate_params(symbol=pair, timestamp=self.get_timestamp()) body = self.__generate_params(params=parameters, signature=self.__sign_hex(parameters)) ...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function cancels multiple orders (up to 10) for a specified trading pair using either system-generated order IDs or user-defined client IDs. It constructs a signed API request with parameters including order lists, symbol, and timestamp, then sends a DELETE request to cancel the orders, returning the API's respons...
def cancel_batch_orders(self, pair, orderid_list="NULL", client_orderID_list="NULL"): """ orderIdList LIST < int64 > order number up to 10 orders in a list [1234567, 2345678] ClientOrderIDList LIST < string > Customized order ID for users, up to 10 orders[1234567, 23...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
Your return The main task of the code is to retrieve pending (open) orders from a trading API by constructing a signed request. It generates parameters with a timestamp and trading pair, creates a signature using `__sign_hex`, and sends a GET request to the specified API endpoint. The function returns the raw data fr...
def query_pending_orders(self, pair="NULL"): path = "/openApi/swap/v2/trade/openOrders" url = self.ROOT_URL + path parameters = self.__generate_params(symbol=pair, timestamp=self.get_timestamp()) body = self.__generate_params(params=parameters, signature=self.__sign_hex(parameters)) ...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
The code retrieves order details from a trading API, using either an order ID or client order ID, and returns the order data including its status (e.g., pending, filled, canceled). It constructs a request with parameters like symbol, timestamp, and a signature for authentication, then fetches and returns the API respon...
def query_order(self, pair, order_id="NULL", client_order_id="NULL"): """ Pending Order that has not been closed PartiallyFilled Order that has been Partially filled Cancelled Order is canceled Filled Order is Filled Failed Order is Failed ...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
The main task of the code is to retrieve the margin trading mode (isolated or cross) for a specified trading pair by sending a signed API request to a swap trading endpoint, then parsing and returning the corresponding margin type data from the response.
def get_margin_mode(self, pair): path = "/openApi/swap/v2/trade/marginType" url = self.ROOT_URL + path parameters = self.__generate_params(symbol=pair, timestamp=self.get_timestamp()) body = self.__generate_params(params=parameters, signature=self.__sign_hex(parameters)) response...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function sets the margin mode (ISOLATED/CROSSED) for a specified trading pair on a cryptocurrency exchange. It validates the mode, constructs an API request with parameters, signs it, and sends a POST request. On success, it returns a confirmation message indicating the margin mode was updated for the given tradin...
def set_margin_mode(self, pair, mode): """ symbol String There must be a hyphen/ "-" in the trading pair symbol. eg: BTC-USDT marginType String ISOLATED or CROSSED In cross margin mode, any position can automatically utilize the available balance of the relevant cryptocurrency to a...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This code retrieves leverage information for a specified trading pair by sending a signed GET request to an API endpoint. It constructs the URL, generates required parameters with a timestamp and signature, and returns the parsed response data.
def get_levarage(self, pair): path = "/openApi/swap/v2/trade/leverage" url = self.ROOT_URL + path parameters = self.__generate_params(symbol=pair, timestamp=self.get_timestamp()) body = self.__generate_params(params=parameters, signature=self.__sign_hex(parameters)) response = se...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function sets the leverage for a specific trading pair and position side (long/short) by sending a POST request to a swap trading API. It validates the position side, generates signed parameters with a timestamp, and returns the API response data after adjusting the leverage amount.
def set_levarage(self, pair, position_side, amount): path = "/openApi/swap/v2/trade/leverage" url = self.ROOT_URL + path valid_ask = ['ASK', 'Ask', 'ask', 'short', 'Short', 'SHORT'] valid_bid = ['BID', 'Bid', 'bid', 'long', 'Long', 'LONG'] if position_side in valid_ask: ...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
This function retrieves forced liquidation orders (including ADL orders) from a trading platform's API, filtered by trading pair, order type, and time range. It constructs a request with parameters like symbol, auto_close_type, timestamps, and limit, signs it, and returns the API response data.
def query_force_orders(self, pair, auto_close_type="NULL", start_timestamp="NULL", end_timestamp="NULL", limit="NULL"): """ symbol String There must be a hyphen/ "-" in the trading pair symbol. eg: BTC-USDT autoCloseType String "LIQUIDATION" for liquidation or...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
The function retrieves historical order data from a trading API, querying up to 500 records (max 1000) within a 7-day time frame. It constructs a signed API request with parameters like trading pair, timestamp range, and order ID, then returns the raw response data from the "/openApi/swap/v2/trade/allOrders" endpoint.
def query_orders_history(self, pair, limit=500, order_id="NULL", start_timestamp="NULL", end_timestamp="NULL"): # The maximum query time range shall not exceed 7 days # Query data within the last 7 days by default # limit is: number of result sets to return //Default: 500 //Maximum: 1000 ...
def get_current_optimal_price(self, pair): """ Obtain the current optimal order(Best bid and offer) # Use best bid to sell and use best offer to buy. """ path = "/openApi/swap/v2/quote/bookTicker" url = self.ROOT_URL + path parameters = self.__generate_params(symb...
This function places a limit order for perpetual futures trading, specifying a trading pair, position side (LONG/SHORT), entry price (or using best bid/offer), and volume. It optionally includes take-profit (TP) and stop-loss (SL) orders, formatted as JSON. The function constructs API parameters, signs them, and sends ...
def open_limit_order(self, pair, position_side, price, volume, sl="NULL", tp="NULL", client_order_id="NULL"): """ APIKEY must have 'perpetual futures trading' permission for this to work. :param pair: Symbol you want to trade i.e. BTC-USDT :param position_side: LONG/SHORT :param...
def get_current_optimal_price(self, pair): """ Obtain the current optimal order(Best bid and offer) # Use best bid to sell and use best offer to buy. """ path = "/openApi/swap/v2/quote/bookTicker" url = self.ROOT_URL + path parameters = self.__generate_params(symb...
This function closes a limit order on a perpetual futures contract by executing a trade (BUY or SELL) to offset an existing position (LONG or SHORT) at a specified price and volume. It uses "BBO" to dynamically select the best bid/offer price, generates API parameters with a timestamp and signature, and sends the order...
def close_limit_order(self, pair, position_side, price, volume, client_order_id="NULL"): """ APIKEY must have 'perpetual futures trading' permission for this to work. :param pair: Symbol you want to trade i.e. BTC-USDT :param position_side: LONG/SHORT :param price: Entry price f...
def read_configuration(): global urlResultSheetPath global urlSheetPath global contentFilePath global data with open('Configuration.json') as json_data_file: data = json.load(json_data_file) print("Input Website List File Path : "+ data["input"]["Input_WebSite_list"]) ...
The code's main task is to extract content from multiple websites and their sublinks. It reads domain names from an Excel sheet, deletes existing results, and processes each main site URL to extract content. For each main site, it also extracts content from its sublinks, storing results. Finally, it prints the list of ...
def execute_content_extraction_engine(): global urlArr global websiteSubLinks url_list=[] read_configuration() #Delete Extraction Result Sheet delete_extraction_result_File() #Read all 80K domain names from Excel Sheet url_list=read_excel_sheet(0,1,0) #Ex...
def get(self, url): print('[get] url=%s' % url) self.chrome.get(url) def select(self, xpath, text): print('[select] xpath=%s, text=%s' % (xpath, text)) while True: try: return Select(self.element(xpath)).select_by_visible_text(text) except: ...
This code executes a predefined workflow by iterating through steps, performing actions like GET requests, element selection, clicks, window switches, OCR, and input, with optional pauses and halts. It handles user interruptions gracefully by cleaning up resources.
def run(self, halt): try: for step in self.flow['steps']: if step['action'] == 'get': self.get(step['url']) elif step['action'] == 'select': self.select(step['xpath'], step['text']) elif step['action'] == 'click'...
def get_mediapipe_app( max_num_faces=1, refine_landmarks=True, min_detection_confidence=0.5, min_tracking_confidence=0.5, ): """Initialize and return Mediapipe FaceMesh Solution Graph object""" face_mesh = mp.solutions.face_mesh.FaceMesh( max_num_faces=max_num_faces, refine_landm...
This code uses Mediapipe and OpenCV to track eye movements in real-time, calculates Eye Aspect Ratio (EAR) to detect closed eyes, and triggers an audio alert when eyes remain closed for over 1 second. It displays FPS, eye landmarks, and elapsed closure time on a video feed, terminating on 'q' key press.
def run1(): global start, endd,cal,summ,tong,flag flag = False start = None cal= 0 endd= None summ=0 tong=0 mpfacemesh = mp.solutions.face_mesh face =get_mediapipe_app() mpdraw = mp.solutions.drawing_utils left_eyes = list(mpfacemesh.FACEMESH_LEFT_EYE) right_eyes = ...
def set_up_game(self, number_of_apples): self.__board.add_starting_snake(self.__board_size) self.__board.add_starting_apples(self.__board_size, number_of_apples) self.print_board() def move_snake_up(self): apples = self.__board.get_apples() snake = self.__board.get_snake() ...
This code runs a snake game by taking user input for board size and apples, then handling movement commands (up/down/left/right) with collision checks. It validates direction changes, updates the snake's position, prints the board state, and processes 'move' commands with step arguments. The loop continues until an exc...
def run_game(self): self.__board_size = int(input('Board size: ')) number_of_apples = int(input('Number of apples: ')) self.set_up_game(number_of_apples) last_turn = None while True: command_line = input('>>> ') try: if command_line == '...
def handleDirection(): global currentDirection global changeDirectionTo match getDirection(): case Direction.UP: changeDirectionTo = Direction.UP case Direction.DOWN: changeDirectionTo = Direction.DOWN case Direction.LEFT: changeDirectionTo = Dire...
This function handles the core game loop of a snake game by updating the snake's movement, checking for fruit collisions to increase the score, managing the snake's body length, redrawing game elements, and checking game over conditions. It processes direction input, updates the snake's position, spawns new fruits when...
def handleSnakeGame(): global snakePosition, snakeBody, fruitSpawn, fruitPosition, score, snakeSpeed, currentDirection, changeDirectionTo, gameState handleDirection() if snakePosition[0] == fruitPosition[0] and snakePosition[1] == fruitPosition[1]: score += 1 LCDdisplayScore() fruit...
def get_processed_data(cnfg, context, coverage_threshold=10, annotseqs_from_file=True, sequneces_df_from_file=True): organism_name = cnfg['organism_name'] sequences = data_reader.readfasta(cnfg['seq_address']) #Can get shrinked the size. annot_df = data_reader.read_annot(cnfg['annot_address']) if organi...
The code trains and evaluates neural network models for methylation prediction across organisms and contexts, using varying window/block sizes. It processes data, builds CNN models, trains on chunked datasets, evaluates performance metrics (accuracy, F1, etc.), and saves results to a CSV. The task involves hyperparamet...
def run_experiments(config_list, context_list, window_sizes, block_sizes, steps, coverage_threshold=10, include_annot=True, memory_chunk_size=10000): res = [] for cnfg in config_list: organism_name = cnfg['organism_name'] for context in context_list: sequences_onehot, methylations, a...
def parse_url(job_url, test_suite, output_file, format): files = get_files_by_url(job_url, test_suite) return parse_files(files, test_suite, output_file, format) def parse_files(paths, test_suite, output_file, format): data = {} if not isinstance(paths, list): paths = [paths] for p in paths:...
The main task of the code is to parse Ginkgo test logs from a file or Prow job URL, process specified test suites (or all), and output results in JSON format to a designated file. It uses command-line arguments to configure input sources, test suites, output paths, and formats, then executes parsing logic based on prov...
def main(): parser = argparse.ArgumentParser( __doc__, description="Parse Ginkgo test log, i.e. deploy_and_test_sriov.log") parser.add_argument( "-u", "--job-url", help="URL of the job from Prow.", ) parser.add_argument( "-p", "--path", help="File path with ginkgo log." ...
def _shuffle_data(self, X, y): """ Shuffle the data! """ y_size = y.shape[1] X = np.hstack((X, y)) if self.shuffle: np.random.shuffle(X) return X[:, :-y_size], X[:, -y_size:] def _get_valid_test_sets(self, data, targets): num_data = data.shape[0] ...
The main task of the code is to train a machine learning model by iterating over epochs, either a fixed number or until validation loss stabilizes. It initializes weights, shuffles data, splits into training/validation/test sets, tracks metrics (MSE, accuracy) across splits, and returns these metrics along with the num...
def fit(self, X, y, initial_weights=None): """ Args: X (array-like): A 2D numpy array with the training data, excluding targets y (array-like): A 2D numpy array with the training targets initial_weights (array-like): allows the user to provide initial weights ...
def _unmerge_points( board_points: Tuple[int, ...] ) -> Tuple[Tuple[int, ...], Tuple[int, ...]]: """Return player and opponent board positions starting from their respective ace points.""" player: Tuple[int, ...] = tuple( map( lambda n: 0 if n < 0 else n, board_points, ...
The code encodes a game position (e.g., Backgammon) into a unique string ID. It combines player and opponent board points, bars, and off pieces into a tuple, generates a hashable key from this data, and converts it into a compact position ID using base64-like encoding. This ID uniquely represents the game state for sto...
def encode(self) -> str: """Encode the position and return a position ID. >>> position = Position(board_points=(-2, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, -5, 5, 0, 0, 0, -3, 0, -5, 0, 0, 0, 0, 2), player_bar=0, player_off=0, opponent_bar=0, opponent_off=0) >>> position.encode() '4HPwATDgc/ABMA'...
def get_current_icons(self, new=True, available=False): current_icons = [] # Update screen and load screenshot as grayscale if new: self.getScreen() img_rgb = self.screenRGB img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) # Check every target in dir ...
The main task of the code is to detect game screen buttons using image recognition, navigate through game states (e.g., battle, home, friend menu), and perform automated actions like clicking buttons or retreating based on detected icons. It handles PvE/PvP battles, menu transitions, and returns status indicators like ...
def battle_screen(self, start=False, pve=True, floor=5): # Scan screen for any key buttons df = self.get_current_icons(available=True) if not df.empty: # list of buttons if (df == 'fighting.png').any(axis=None) and not (df == '1cont_button.png').any(axis=None): ...
def click_button(self, pos): coords = np.array(pos) + 10 self.click(*coords) time.sleep(SLEEP_DELAY * 10) def find_store_refresh(self): self.click_button((100, 1500)) # Click store button self.click_button((475, 1300)) # Click store button [self.swipe([0, 0], [2, 0]) fo...
The code automates purchasing items in a store by clicking specific coordinates to navigate, buy the first (free) and last (legendary) items, dismiss pop-ups, and attempt to refresh the shop via a refresh button, logging purchases. It uses coordinate-based interactions for GUI automation, likely in a game or app.
def refresh_shop(self): self.click_button((100, 1500)) # Click store button self.click_button((475, 1300)) # Click store button # Scroll up and find the refresh button pos = self.find_store_refresh() if isinstance(pos, np.ndarray): self.click_button(pos - [300, 750]...
def get_current_icons(self, new=True, available=False): current_icons = [] # Update screen and load screenshot as grayscale if new: self.getScreen() img_rgb = self.screenRGB img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) # Check every target in dir ...
The main task of the code is to automate watching and interacting with in-game ads by detecting specific UI elements, clicking through ad interfaces, and handling ad completion or escape sequences. It checks for available buttons, triggers ad interactions, waits for ad completion, skips ads if stuck, and restarts the g...
def watch_ads(self): avail_buttons = self.get_current_icons(available=True) # Watch ad if available if (avail_buttons == 'quest_done.png').any(axis=None): pos = get_button_pos(avail_buttons, 'quest_done.png') self.click_button(pos) self.click(700, 625) # coll...
def scan_grid(self, new=False): boxes, box_size = get_grid() # should be enabled by default if new: self.getScreen() box_list = boxes.reshape(15, 2) names = [] if not os.path.isdir('OCR_inputs'): os.mkdir('OCR_inputs') for i in range(len(bo...
The code's main task is to determine which units to merge on a grid based on priority, grid fullness, and specific conditions (e.g., preserving trappers, balancing knight statues, targeting high-DPS units). It filters candidates, applies special merging rules, and performs merges to optimize the grid while adhering to ...
def try_merge(self, rank=1, prev_grid=None, merge_target='zealot.png'): info = '' merge_df = None names = self.scan_grid(new=False) grid_df = bot_perception.grid_status(names, prev_grid=prev_grid) df_split, unit_series, df_groups, group_keys = grid_meta_info(grid_df) # Se...
def init_variables(self, origin, destination): ''' Initialize all necessary variables in variables of a class. It is equal to say `this.variable` in Java. In python, we use `self.variable` ''' self.origin = self.load_station(origin) self.destination = self.load_station(de...
The code initializes a pathfinding algorithm (A*) to calculate routes between origin and destination nodes. It checks if origin/destination are identical, computes path costs (g_score) and distances, converts them using a fixed ratio (18.0267), and prints results. The A* algorithm is executed twice, with intermediate v...
def __init__(self, origin, destination, data): if origin == destination: print("Su destino y origen son lo mismo") return self.json = data self.init_variables(origin, destination) self.all_route = self.a_star() ratio = 18.0267 print(self.g_score...
def _argparse(): p = argparse.ArgumentParser() p.add_argument('infile', nargs='+') p.add_argument('-t', '--threshold', type=int, default=100) p.add_argument('-M', '--skip-number-images', type=int, default=None) p.add_argument('-N', '--restrict-number-images', type=int, default=None) p.add_argume...
The code processes images for cluster analysis, either using pre-clustered data or analyzing each image sequentially. It accumulates cluster results, skips/skips images based on arguments, displays frames interactively if enabled, and finally processes the aggregated clusters.
def main(): args = _argparse() images = _load_images(args) if args.interactive: plt.ion() if hasattr(images, 'dtype') and images.dtype == Cluster_dtype: _log.info('processing pickled clusters from %s...', args.infile[0]) clusters_acc = images else: _log.info('reading ...
def get_chesscom_win_percentage(self): return round((self.get_all_chesscom_games_by_result('win') * 100) / self.get_all_chesscom_games(), 2) def get_chesscom_draw_percentage(self): return round((self.get_all_chesscom_games_by_result('draw') * 100) / self.get_all_chesscom_games(), 2) def get_chesscom_los...
This function generates a pie chart URL displaying win, draw, and loss percentages from chess.com statistics using the ChartVisualizer class, formatting data and labels dynamically from method calls to create a 200x200 pixel visual representation of the user's chess performance.
def games_chesscom_stats_chart_url(self): chart = ChartVisualizer() chart.set_cht('cht=p') # pie chart chart.set_chs('chs=200x200') chart.set_chdl('chdl=wins%7Cdraws%7Closses') chart.set_chl( f'chl={self.get_chesscom_win_percentage()}%%7C{self.get_chesscom_draw_perce...
def writeToTx(message): tx = open("Temp_T.txt", "a+") tx.write(message + '\n') tx.close() def getNumberOfTx(): with open("Temp_T.txt") as tx: count = sum(1 for _ in tx) return count def mine(): global balance clientPort = 10001 # client to send confirmed Tx to, change depending on w...
This code implements a UDP server handling transactions and blockchain data. It distinguishes between full nodes (127.0.0.1) and clients (192.168.1.255), processing transactions by writing them to a file and triggering mining when four transactions accumulate. It appends received blocks to a blockchain file, slices tra...
def main(): global turn while 0 != 1: serverPort = 10000 # server port // CHANGE DEPENDING ON IF THIS IS F1 OR F2 serverSocket = socket(AF_INET, SOCK_DGRAM) # set listening port serverSocket.bind(('', serverPort)) # listen print('The server is ready to receive') messa...
def motive_truth(): print ("The Driver: 'I can help you out. There's a town not far from here. Hop in...") print ("You step in the car. The driver looks friendly enough. He looks middle aged, sporting a brown beard and wearing a dark blue beanie.") print ("The Driver:'Tell me. What were you doing out there ...
The code presents a narrative scenario where a character's bike breaks down, leading to an interaction with a driver. The user chooses between two options (A or B) to determine the story's direction, triggering either the 'motive_truth()' or 'motive_lie()' functions. If an invalid input is given, the function loops bac...
def Opening(): print ("... It's a cold, snowy, misty night... You are biking right by a highway at a fast pace and your bike eventually breaks down.") print ("You leave the bike in a snowy ditch and keep walking.") print ("You eventually reach a road sign right by the highway. You rest your arm against the...
def __format_text(text: str, reduce_punct: bool) -> str: text = unidecode(text).upper() if reduce_punct: text = text.lstrip("!&,-.:;?") text = text.rstrip("&,-.:;") return text def text_is_blank(text: str, words: List[str]) -> bool: return text.isspace() or not words def text_has_no_wo...
The function formats input text by validating it against rules like word count, length, allowed characters, and consecutive letters. It raises exceptions for violations, then wraps text if specified. Returns the formatted text and list of words.
def format_text( text: str, reduce_punct: bool, wrap_text: bool ) -> Tuple[str, List[str]]: """ Format the given text and return it along with a list of its words. Raise InvalidTextSubmissionException if the given text breaks the rules. """ text = __format_text(text, reduce_punct) words = te...
def load_graph_data_euclidean(filepath): problem = tsplib95.load(filepath) coordinates = problem.node_coords return create_adjacency_matrix_euclidean(coordinates) def print_adjacency_matrix(adjacency_matrix): for row in adjacency_matrix: print(" ".join(f"{distance:2d}" for distance in row)) def...
The code's main task is to load graph data from TSP files, compute the length of a canonical tour using an adjacency matrix, and verify matrix loading. It first loads a Euclidean graph ('pcb442.tsp'), calculates the cycle length of the ordered node sequence, and prints the result. Then, it checks the full adjacency mat...
def main(): # Cannonical tour to test the distance calculation adjacency_matrix = load_graph_data_euclidean('data/pcb442.tsp') cannonical_tour_length = cycle_length(adjacency_matrix, list(range(len(adjacency_matrix)))) print(cannonical_tour_length) # Check the full matrix loading print_adjacen...
def connect_to_database(self,database_name="Main_db"): try: if self.exist_db(database_name): logging.info(f"Connecting to database {database_name}...") for i in self.client.get_databases(): # print(i['info']['name'],i['id']) ...
This function retrieves data from a specified database, converts it into a CSV file, and archives the data in an 'Archived' database. It connects to the source database, paginates through all collections, extracts documents, and stores them as a DataFrame. The CSV is saved to a specified path, while the data is also in...
def pull_latest_data(self,database_name="Main_db",raw_data_path=None,passwd=None): try: db_con = self.connect_to_database(database_name=database_name) list_of_docs = [] for collection in db_con.get_collections()["status"]["collections"]: co...
def connect_to_database(self,database_name="Main_db"): try: if self.exist_db(database_name): logging.info(f"Connecting to database {database_name}...") for i in self.client.get_databases(): # print(i['info']['name'],i['id']) ...
The code pulls the latest data from a specified database, converts it into a DataFrame, saves it as a CSV file, archives the data in an "Archived" database, and deletes the original collections from the main database. It handles exceptions and logs progress.
def pull_latest_data(self,database_name="Main_db",raw_data_path=None,passwd=None): try: db_con = self.connect_to_database(database_name=database_name) list_of_docs = [] if len(db_con.get_collections()["status"]["collections"])==0: logging.i...
def group(things): """Group a (list of) x3d elements.""" return element("group", children=things) def x3d_atom(atom): """Represent an atom as an x3d, coloured sphere.""" x, y, z = atom.position r, g, b = jmol_colors[atom.number] radius = covalent_radii[atom.number] material = element("mate...
The code converts an atomic structure into an X3D 3D visualization. It creates atom spheres, a cell wireframe, centers the structure at the origin, calculates optimal viewpoint distance based on atomic positions and cell dimensions, then returns an X3D scene with the centered structure and properly positioned viewpoint...
def x3d_atoms(atoms): """Convert an atoms object into an x3d representation.""" atom_spheres = group([x3d_atom(atom) for atom in atoms]) wireframe = x3d_wireframe_box(atoms.cell) cell = group((wireframe, atom_spheres)) # we want the cell to be in the middle of the viewport # so that we can (a)...
def count_zero(self): zero_counter = 0 row_counter = 0 column_counter = 0 while row_counter < self.dimension: while column_counter < self.dimension: if self.box[row_counter][column_counter] == 0: zero_counter += 1 column_cou...
The code solves a Sudoku puzzle iteratively by repeatedly applying constraint propagation techniques. It loops until no empty cells remain, using methods to fill cells with single possible values in rows, columns, 3x3 boxes, and then more complex deductions. Each iteration draws the board, checks for singles, and resol...
def solve(self): while self.count_zero() > 0: self.draw() self.solve_row_with_one_zero() self.solve_column_with_one_zero() self.solve_little_box_with_one_zero() self.solve_row() self.solve_column() self.solve_little_box() ...
def repo_url_to_owner_and_name(repo_url): # bqbeo@example.com:funfair-tech/funfair-games.git # https://github.com/funfair-tech/funfair-labs-tictactoe-server if repo_url.startswith("bqbeo@example.com:"): split = repo_url[15:-4].split("/") return { "owner": split[0], "...
The code updates GitHub repository branch protection settings for 'main' branches listed in a config file, skipping two specified repos. It reads repo URLs, extracts owner/repo names, compares existing settings with predefined ones, and applies changes only if they differ, using a GitHub token for authentication.
def update(): if GITHUB_TOKEN == "": raise "Invalid Github token" repository_list_file = root / "personal/repos.lst" print(repository_list_file) repos = repository_list_file.open("r").read().splitlines() print(repos) for repo in repos: print("**********************************...
def last_ball_gone(): if Game.num_lives == 0: start_level_reset() else: start_soft_reset() def try_spawn_powerup(rect): if rand.randint(1, 100) / 100 < POWERUP_PERCENT: spawn_rand_powerup(rect) def last_tile_gone(): level_completed()
The function `check_for_death` removes a dead game object from the game, triggering specific actions based on its tag. If the object is a "ball" and it's the last one, it removes it and calls `last_ball_gone()`. For a "tile", it plays a sound, spawns a power-up, removes the tile, and calls `last_tile_gone()` if no tile...
def check_for_death(object): if object.dead: if object.tag == "ball" and len(get_objects("ball")) == 1: Game.objects.remove(object) last_ball_gone() elif object.tag == "tile": pygame.mixer.Sound('Audio/bounce.wav').play() try_spawn_powerup(object) ...
def soft_reset_level(): Game.paddle.w = PADDLE_WIDTH center_rect_in_rect(Game.paddle, Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), x_center = True) Game.rest_state = True def reset_level(): soft_reset_level() Game.num_lives = NUM_LIVES Game.current_level = level_map_to_tile_map(Game.level_maps[Game....
The function `timed_events()` checks three time-based milestones in a game. If a milestone ("soft_reset", "reset", or "level_completed") has passed, it resets the milestone and triggers corresponding actions: `soft_reset_level()`, `reset_level()`, or `next_level()`, respectively. Its main task is to monitor and respond...
def timed_events(): if Game.timer.milestones["soft_reset"].passed: Game.timer.reset_milestone("soft_reset") soft_reset_level() if Game.timer.milestones["reset"].passed: Game.timer.reset_milestone("reset") reset_level() if Game.timer.milestones["level_completed"].passed: ...
def level_map_to_tile_map(level_map): tile_map = [] for j in range(len(level_map)): for i in range(len(level_map[j])): if level_map[j][i] != 0: tile_map.append(Tile(i * TILE_WIDTH, j * TILE_HEIGHT, level_map[j][i])) return tile_map def get_input(): keys = pygame.key.g...
This code initializes a Pygame-based block-breaking game, setting up the display, game objects (paddle, levels), timers, and fonts. It runs a main loop processing events, updating game state, and rendering graphics at 60 FPS until the user quits. Key tasks include level loading, input handling, collision detection, and...
def main(): pygame.init() pygame.display.set_caption('Block-Buster') Game.screen = pygame.display.set_mode((SCREEN_WIDTH + SCREEN_WIDTH_EXTENSION, SCREEN_HEIGHT)) Game.stop = False Game.clock = pygame.time.Clock() Game.timer = Timer() Game.paddle_dx = 0 Game.level_maps = get_level_maps(...
def _retrieve_thresholds(self): """ Returns features with their threshold values. :return: A dictionary with feature names as keys and thresholds as values. :rtype: dict """ forest_dump = self.forest.dump_model() tree_info = [] feature_names = s...
The main task of the code is to create and train a Generalized Additive Model (GAM) using a given LightGBM Booster forest. It processes feature types, computes feature importance, generates synthetic training/test data, and fits the GAM. The method saves the resulting model, loss metrics, and related data, returning th...
def explain(self, forest, lam_search_space=None): """ Creates the GAM, runs it on a Booster and returns the resulted model. It also saves some further information in the class fields i.e. the resulting GAM model, the RMSE or the accuracy ecc. :param forest: The forest of trees to be exp...
def message_is_for_our_bot(user_id, message_text): ''' Check if the username and the word 'bot' appears in the text ''' regex_expression = '.*@' + user_id + '.*bot.*' regex = re.compile(regex_expression) # Check if the message text matches the regex above match = regex.match(message_text) ...
The code processes Slack events by filtering messages from users intended for the bot, extracting station names from user queries, and generating appropriate responses. It ignores non-message events, bot-generated messages, and messages not directed at the bot. If a station name is successfully extracted, it prepares a...
def process_slack_event(event): ''' The Slack RTM (real time messaging) generates a lot of events. We want to examine them all but only react to: 1. Messages 2. ...that come from a user 3. ...that ask our bot to do something 4. ...and act only for messages for which we can extract the data w...
def GetP_Q(): primeList=[0,0] while(primeList[0] == primeList[1]): for i in range(0, 2): n = sympy.randprime(2, 2**8) primeList[i] = n return primeList[0], primeList[1] def Calculate_e(phi_n): e = 2 while(e < phi_n): if GCD...
This code sends an encrypted message via a client socket using RSA encryption. It generates primes p/q, computes public keys (e, n), ensures message size fits within modulus n, encrypts the message, and transmits the ciphertext along with public key components to a server. The loop handles prime regeneration if the mes...
def client_send(): while True: x = f'{alias}: ' message = f'{input("")}' p, q = GetP_Q() while Choice == 0: p=poriginal q= qoriginal break n = p * q print(p) print(q) phi_n = (p-1)* (q-1) e = Ca...
def str_to_list(str): return list(str.split(" ")) def str_to_int(M): return [int(i) for i in M] def mult_inv(e,r): gcd,s,_=ExtendedEuclid(e,r) if(gcd!=1): return None else: return s%r def Decryption(C, d, n): M = [] for c in C: M.append((c ** d) % n) ...
The code receives messages from a client, checks for an alias request, and decrypts data using RSA. If a 'Keys:' message is detected, it extracts public key parameters (e, n, φ(n)), processes the encrypted message, computes the private key (d), decrypts the message, and prints the decrypted result along with the user's...
def client_receive(): while True: try: message = client.recv(1024).decode('utf-8') if message == "alias?": client.send(alias.encode('utf-8')) else: if message.find('Keys:')!= -1: temp = message.find('Keys:') ...
def __get_position( self, offset: Optional[tuple[int, int]] = None, ) -> CodePosition: """ Returns the position of the given node, for use with error reporting. """ assert self.__current_node is not None position = self.get_metadata( PositionProvid...
The code processes a docstring by evaluating commands enclosed in double braces (`{{...}}`), handling nested structures, and reporting syntax errors for incomplete commands. It uses a state machine to track brace counts, command buffers, and positions, transforming the docstring by executing commands and returning the ...
def __process_docstring(self, docstring: str) -> str: """ Process the given docstring according to the rules of the DocTransformer. """ # This code is extremely yucky but I cannot be bothered to write a # nicer version of it # Perhaps I could use a state machine o...
def generate_json_for_acad_org(self, acad_org, strm): subjects = self.sql_helper.get_unique_subjects_in_org(strm, acad_org) data = {subject: [] for subject in subjects} for subject_descr in subjects: # 'Computer Science' is considered a subject catalog_numbers = self.sql_helper.ca...
The main task of the code is to generate structured JSON files organizing academic organizations (departments) and their requirements by academic groups (e.g., Colleges). It creates a hierarchical data map, saves it as `latest_sem.json`, and writes metadata including the current semester and timestamp. Special handling...
def generate(self): # make sure the json directory exists if not os.path.exists(self.save_dir): os.makedirs(self.save_dir) acad_groups = self.sql_helper.get_unique_acad_groups(self.strm) data_map = {} # all_orgs = [] for group in acad_groups: # looping over...
def getAttachFrom(nextDomino: Domino, game: Game, end): attachFrom = '' if end == LEFT: attachFrom = LEFT if game.leftCount > 4: if game.leftCount == 5 and nextDomino.isDouble: attachFrom = LEFT else: attachFrom = UP if game.leftCou...
The code places a chosen domino on a game board, determining its attachment position (left/right end) and orientation. It updates the domino's coordinates, flow direction, and visually renders it. The player's selected domino is then removed from their hand, and the game state is updated to reflect the move, including ...
def putDomino(player: Player, game: Game, end): nextDomino = player.hand[player.chosenDominoIndex] attachFrom = getAttachFrom(nextDomino, game, end) if end == LEFT: nextFlow, nextCoor = attach( game.lastDominoLeft, nextDomino, game.leftEnd, game.lastDo...
def canChoose(dominoIndex, player: Player, game: Game): d = player.hand[dominoIndex] if len(game.table) == 0: return d.isDouble else: return game.leftEnd in (d.A, d.B) or game.rightEnd in (d.A, d.B) def chooseDomino(player: Player, game: Game, dominoIndex): player.chosenDominoIndex = dom...
This function handles mouse click events in a domino game: it selects dominoes from the player's hand, places them on the table (left/right), or takes from the stock. It checks click positions against game elements like hand area, placeholders, and stock, triggering actions like choosing dominoes, placing them, or draw...
def click(mousePos, player: Player, game: Game): x, y = mousePos if y > WIN_HEIGHT - DOMINO_WIDTH_2 * 5 and y < WIN_HEIGHT - DOMINO_WIDTH_2: x0 = x - DOMINO_WIDTH_2 if x0 > 0 and x0 < len(player.hand) * DOMINO_WIDTH_2 * 3: dominoIndex = x0 // (3 * DOMINO_WIDTH_2) if canCh...
def putFirstDomino(player: Player, game: Game): coor0 = Coordinate(WIN_WIDTH_2, WIN_HEIGHT_2) domino = player.hand[player.chosenDominoIndex] domino.xy = Coordinate(WIN_WIDTH_2, WIN_HEIGHT_2) domino.flow = 'D' #update player #player.hand.remove(domino) player.chosenDominoIndex = -1 #updat...
The code places a series of dominoes on a graphical window by sequentially attaching them to the left and right ends of an initial domino. It uses the `attach` and `putDomino1` functions to position each new domino in specific directions ('L', 'R', 'U', 'D'), creating a connected chain of dominoes with coordinated plac...
def drawtest(): d1 = Domino(3,3) coor, flow, leftEnd, rightEnd = putFirstDomino(win, d1) rightDominoFlow = flow leftDominoFlow = flow rightDominoCoor = coor leftDominoCoor = coor d2 = Domino(3, 4) d2Flow, d2Coor = attach(d1, d2, leftEnd, leftDominoCoor, leftDominoFlow, 'L') leftEnd ...
def getAllTransactionsSorted(self): rawFromMongo = self.dbAccess.find_sort_by(("name", 1), DbAccess.Collection.Transactions) retData = {} for nextEntry in rawFromMongo: name = nextEntry["name"] if name not in retData: retData[name] = {} ticke...
The code calculates the financial gain from trading compared to non-trading scenarios for each stock, considering stock splits and transaction costs. It processes sorted transactions, computes initial and final stock values, adjusts for splits, and calculates net gains. Results are sorted by gain magnitude, and total g...
def calcSuperScore2(self): finalResult = {} transactionList = [] totGain = 0 print("Calulating superscore 2...") try: allTransactions = self.getAllTransactionsSorted() for ticker, transactions in allTransactions.items(): name = None ...
def getNewYieldFromAvanza(self): newYield = 0 rawYieldFromAvanza = requests.get(URLYield) if rawYieldFromAvanza.status_code != 200 or rawYieldFromAvanza.content is None: print("Problems getting yield from avanzaHAndler...") return 0 jsonLoadedRawYield = json.loa...
The function updates MongoDB with current funds, yield, and transaction metrics data. It fetches funds from an API, calculates values if API fails, and stores updated figures (funds, putin, yield, taxes) along with transaction accuracy metrics. The process includes error handling, data initialization, and document upda...
def updateFundsToMongo(self, purchaseValueSek: int, additionalPutinSek: int = 0): try: if purchaseValueSek != 0: print(f"{datetime.datetime.now(pytz.timezone('Europe/Stockholm'))} Updating funds to mongo {purchaseValueSek}") if additionalPutinSek != 0: pr...
def fetchDailyDataFromMongoByDate(self, dayAsString, allowCrawlingBack = False): for a in range(15 if allowCrawlingBack else 1): nextDateToCheck = self.getDateAsStringDaysBack(self.dayStringToDatetime(dayAsString), a) hits = self.dbAccess.find({"day": nextDateToCheck}, DbAccess.Collecti...
The code calculates the financial difference between stock and fund data from a specified start date and the most recent data, returning the result or -88888.8 if an error occurs.
def getDevelopmentSinceDate(self, startDate): try: stocksAtStart, fundsAtStart = self.fetchDailyDataFromMongoByDate(startDate) stocksMostRecent, fundsMostResent = self.fetchDailyDataMostRecent(self.getTodayAsString()) self.addCurrentStockValueToStocks(stocksMostRecent) ...
def fetchDailyDataFromMongoByDate(self, dayAsString, allowCrawlingBack = False): for a in range(15 if allowCrawlingBack else 1): nextDateToCheck = self.getDateAsStringDaysBack(self.dayStringToDatetime(dayAsString), a) hits = self.dbAccess.find({"day": nextDateToCheck}, DbAccess.Collecti...
The main task of the code is to calculate the percentage change in portfolio value between two dates (startDate to endDate), considering both stocks and funds. It fetches stock/fund data, computes their total values using current prices, adjusts for fund-related expenses, and returns the relative change as a TP Index (...
def calcTpIndexSince(self, startDate: str, endDate: str, sampleSingleStartDate = True, sampleSingleEndDate = True): print(f"{datetime.datetime.now(pytz.timezone('Europe/Stockholm'))} calcTpIndexFrom {startDate} to {endDate}") if startDate is None or endDate is None: return 0.0, -999889 ...
def fetchDailyDataFromMongo(self, daysback, allowCrawlingBack = True): for a in range(5 if allowCrawlingBack else 1): dayBackToCheck = daysback + a dayAsString = self.getDayAsStringDaysBackFromToday(dayBackToCheck) hits = self.dbAccess.find({"day": dayAsString}, DbAccess.Col...
The code calculates the financial difference between historical stock/fund data from a specified number of days ago and today's data. It fetches historical and current data from MongoDB, updates current stock values, then computes the difference using getFinancialDiffBetween. The function returns this difference or -88...
def getHistoricDevelopment(self, daysback): try: stocksDaysBack, fundsDaysBack = self.fetchDailyDataFromMongo(daysback, allowCrawlingBack=True) stocksToday, fundsToday = self.fetchDailyDataFromMongo(0) self.addCurrentStockValueToStocks(stocksToday) return self.g...
def dayStringToDatetime(self, stringDate): return datetime.datetime.strptime(stringDate, '%Y-%m-%d') def getTodayAsString(self): return self.getDateAsStringDaysBack(datetime.datetime.now(tz=pytz.timezone('Europe/Stockholm')), 0) def getDateAsString(self, date: datetime): return f"{date.year}-{da...
The code calculates monthly TP indexes by iterating from a defined start date (DAY_ZERO) to the current date, using a 30-day step. For each period, it computes a TP index, accumulates results, reverses the order, averages the TP index across months, and extrapolates to a yearly basis. The output includes detailed month...
def getTpIndexesByMonth(self): DAY_STEPPING = 30 today = self.dayStringToDatetime(self.getTodayAsString()) startDate = self.dayStringToDatetime(DAY_ZERO) monthlyResult = [] totDays = 0 while True: if self.getDateAsString(startDate) >= self.getDateAsString(t...
def _load_dicts(self): # Load in a few lexicons self.usdw = set() self.usdwl = set() # /usr/share/dict/words f = open(_getpath("words.txt"), "r", encoding="utf-8", errors="replace") for l in f: l = l.strip() if len(l) > 0: self.usdw...
The code initializes a Featurizer class to either train a model using provided sequences or load a pre-trained model from a file/JSON. It sets up a BERT tokenizer, loads necessary dictionaries, and determines the initialization path based on whether training data or a model file is provided.
def __init__(self, train=None, model=None, extrachem=None, bert_pretrain_path='allenai/scibert_scivocab_cased'): """ Train the Featurizer, or Args: train: if not None, the training sequences from corpusreader model: if not None, a text file or JSON object produc...
def get_all_urls(): cursor = database.cursor() cursor.execute("SELECT id, created_at, url, title, summary FROM url") records = cursor.fetchall() print(f"Fetched {len(records)} records") return [db_record_to_url_record(r) for r in records] def fill_in_missing_fields(urls): for url in urls: ...
The main task of the code is to retrieve URLs, fill missing fields, update database records, generate summaries, and update records again with summaries. It ensures database entries for URLs are complete by iterating through them twice: first to fill missing data, then to add summaries, with progress updates printed fo...
def fill_missing_database_info(): urls = get_all_urls() fill_in_missing_fields(urls) for url in urls: update_record(url) fill_in_summary_field(urls) for url in urls: update_record(url) print(f"Updated: {url}")
def get_compression_action(S,sent,epsilon,model_comp): prob = np.zeros(2) sent_vec = get_sentence_representation(sent,S) new_sent = get_compressed_sentence(sent,S) comp_vec = get_sentence_representation(new_sent,S) sent_val = model_comp.predict(sent_vec) comp_val = model_comp.predict(comp_vec) ...
This code trains a model to generate a summary by iteratively selecting sentences from a text corpus (T) using reinforcement learning. It evaluates potential new states (sentences) against the current state, decides to include or exclude each sentence via epsilon-greedy policy, and updates the model with ROUGE-based re...
def learn(S,T,model,model_comp,epsilon): max_val = 0 rouge_num = 1 sent_objects = T.sent_obj_list sentences_tmp = copy.deepcopy(sent_objects) while len(sentences_tmp): sent = random.choice(sentences_tmp) sentences_tmp.remove(sent) new_vec = S.get_new_state_vec(sent)...
def tf_idf(data_list): for i, text in enumerate(data_list): art = text.article token_dict[i] = art.translate(string.punctuation) tfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english') tfs = tfidf.fit_transform(token_dict.values()) return tfidf, tfs def get_sentence_info2(data...
The code implements value function approximation using linear or neural network models (SGDRegressor/MLPRegressor) to learn optimal policies for text data. It processes article-abstract pairs with TF-IDF features, trains models via iterative learning with exploration (epsilon), evaluates performance on test data, and s...
def value_function_approximation(): # main function multiprocess = 0 num_episodes = 100 #100 batch_size = 1 # each doc contains 1000 article-abstract pairs alpha = 0.005 # learning rate epsilon = 0.1 k = 100 itr = 30 # 50 iterations per article data_list = read_articles_and_summaries()[:...
def get_nuclear_z_variance(structure): nuc_var = structure.positions[:,2].var() return nuc_var def get_dft_energy_from_file(filename_base, wait): if wait > 100: raise ValueError("Waited for 100 cycles") dft_energy = list() try: with paropen(filename_base + '.txt', 'r') as f: ...
The code optimizes the interlayer position of a crystal structure by calculating total energies (DFT + dispersion) across varied z-offsets. It iterates through configurations, computes energies, identifies the minimum energy state, fits a polynomial to estimate optimal positions, and returns the optimized structure and...
def run_il_optimization(structure, type='eclipsed'): scale = False if type != 'staggered': z_offsets = np.linspace(max_z_coord, min_z_coord, num_z_coord, endpoint=True) if type == 'inclined': tx = txt_output[:-4] + '_inclined' asf = 'ase_dftd3_inclined' else: ...
def get_dft_energy_from_file(filename_base, wait): if wait > 100: raise ValueError("Waited for 100 cycles") dft_energy = list() try: with paropen(filename_base + '.txt', 'r') as f: for line in f: if 'Extrapolated' in line: dft_energy.append(flo...
The code performs an inclined scan on a crystal structure's cell parameters by systematically varying x and y offsets. It calculates DFT and dispersion (D3) energies for each configuration, sums them to determine total energy, identifies the minimum energy configuration, and outputs the optimized structure in a CIF fil...
def run_inclined_scan(structure): x_y = list(); dft_energies = list(); d3_energies = list(); total_energies = list() alpha_offsets = np.linspace(min_x, max_x, num_x, endpoint=True) beta_offsets = np.linspace(min_y, max_y, num_y, endpoint=True) offsets = list(itertools.product(alpha_offsets, beta_o...
def get_nuclear_z_variance(structure): nuc_var = structure.positions[:,2].var() return nuc_var def get_dft_energy_from_file(filename_base, wait): if wait > 100: raise ValueError("Waited for 100 cycles") dft_energy = list() try: with paropen(filename_base + '.txt', 'r') as f: ...
This code performs a staggered scan on a crystal structure by systematically shifting atomic layers in the x and y directions. For each offset, it calculates DFT and dispersion (D3) energies, identifies the lowest-energy configuration, and returns the optimized structure along with its total energy. The process involve...
def run_staggered_scan(structure): x_y = list(); dft_energies = list(); d3_energies = list(); total_energies = list() x_offsets = np.linspace(min_x, max_x, int((num_x/2)+1), endpoint=True) y_offsets = np.linspace(min_y, max_y, int((num_y/2)+1), endpoint=True) offsets = list(itertools.product(x_offsets,...
def get_dft_energy_from_file(filename_base, wait): if wait > 100: raise ValueError("Waited for 100 cycles") dft_energy = list() try: with paropen(filename_base + '.txt', 'r') as f: for line in f: if 'Extrapolated' in line: dft_energy.append(flo...
The function calculates the total energy of a 2-layer inclined material structure by combining DFT energy and displacement energy. It creates a supercell, attempts to retrieve precomputed DFT energy from a file, and if unavailable, calculates it. Similarly, it retrieves or computes displacement energy, then returns the...
def run_inclined_2layer(structure): inclined_cif = structure.copy() inclined_2layer_cif = make_supercell(inclined_cif, [[1, 0, 0],[0, 1, 0],[0, 0, 2]]) filename_base = txt_output[:-4] + '_inclined_2layer' ase_filename = 'ase_dftd3_inclined_2layer.out' try: dft = float(get_dft_energy_from_fil...
def debug(*args): from legacypipe.utils import log_debug log_debug(logger, args) def model_selection_one_source(self, src, srci, models, B): if self.bigblob: mods = [mod[srci] for mod in models.models] srctims,modelMasks = _get_subimages(self.tims, mods, src) # Crea...
The code performs model selection for sources in a catalog by iteratively fitting each source individually. It subtracts initial models, fits each source (brightest first), updates the catalog with fitted models, and stores results like chi-square values and model details in object B. It also handles image restoration ...
def run_model_selection(self, cat, Ibright, B): # We compute & subtract initial models for the other sources while # fitting each source: # -Remember the original images # -Compute initial models for each source (in each tim) # -Subtract initial models from images # -Duri...
def _create_training_progress_scores(self, **kwargs): extra_metrics = {key: [] for key in kwargs} training_progress_scores = { "global_step": [], "tp": [], "tn": [], "fp": [], "fn": [], "mcc": [], ...
The code trains a model on a given dataset using a custom loss function that combines two loss components (loss_0 and loss_1) via a power-based averaging formula. It supports multi-GPU training, gradient accumulation, FP16, checkpointing, logging (TensorBoard/WandB), evaluation during training, and early stopping based...
def train(self, train_dataset, output_dir, show_running_loss=True, eval_data_0=None, eval_data_1=None, verbose=True, **kwargs): """ Trains the model on train_dataset. Utility function to be used by the train_model() method. Not intended to be used directly. """ device = self.de...
def _move_model_to_device(self): self.model.to(self.device) def load_and_cache_examples(self, examples, m,evaluate=False, no_cache=False, output_examples=False): """ Converts a list of examples to a TensorDataset containing InputFeatures. Caches the InputFeatures. Utility function for t...
The main task of the code is to train a machine learning model using two input datasets (train_data_0 and train_data_1), optionally evaluate during training, manage output directories, and return training metrics. It combines datasets, handles lazy/loading, trains the model, saves the trained model, and returns global ...
def train_model( self, train_data_0,train_data_1, output_dir=False, show_running_loss=True, args=None, eval_data_0=None, eval_data_1=None , verbose=True, **kwargs ): """ Trains the model using 'train_data' Args: train_data: Path to JSON file containing training data OR l...
def masks_to_boxes(masks: Tensor, anomaly_maps: Tensor | None = None) -> tuple[list[Tensor], list[Tensor]]: """Convert a batch of segmentation masks to bounding box coordinates. Args: masks (Tensor): Input tensor of shape (B, 1, H, W), (B, H, W) or (H, W) anomaly_maps (Tensor | None, optional):...
This code performs anomaly detection on images using a pre-trained PadimModel. It loads statistics, processes images through a neural network, generates anomaly maps, applies thresholds, and visualizes results with heatmaps and bounding boxes.
def predict(): stats = torch.load('dist.pt') mean = stats['mean'] inv_covariance = stats['inv_covariance'] input_size = (512, 512) # model = PadimModel(input_size=(256, 256), backbone='resnet18', layers=['layer1','layer2','layer3'])# model = PadimModel(input_size=input_size, backbone='resnet18',...
def compute_kernel_size(sigma_val: float) -> int: """Compute kernel size from sigma value. Args: sigma_val (float): Sigma value. Returns: int: Kernel size. """ return 2 * int(4.0 * sigma_val + 0.5) + 1 def get_gaussian_kernel2d(kernel_size: Tuple[int, int], sigma: Tuple[float, floa...
This code initializes a 2D Gaussian kernel for convolution operations, configuring parameters like standard deviation (sigma), kernel size, normalization, and padding. It computes the kernel, normalizes it if specified, expands it to match input channels, and sets padding behavior for boundary handling during convoluti...
def __init__( self, sigma: float | tuple[float, float], channels: int = 1, kernel_size: int | tuple[int, int] | None = None, normalize: bool = True, border_type: str = "reflect", padding: str = "same", ) -> None: """Initialize model, setup kernel etc.....
def locate_drawer_on_pos(pos, playing_type): locate_drawer_on_pos.counter += 1 pos = str(pos) drawer.pu() if playing_type == "x": drawer.setpos(-50 + (int(pos[0]) - 1) * 100, 40 - 100 * (int(pos[1]) - 1)) elif (playing_type == "o") and (locate_drawer_on_pos.counter != 1): drawer.setp...
The code maps mouse click coordinates (x,y) to a 3x3 grid position (e.g., '11', '23'), determines the player's symbol (X/O) based on game state, draws the symbol, sends the move to a server, and checks for win/loss conditions. It handles game logic for a turn-based grid game like Tic-Tac-Toe.
def click_position(x, y): possible_poses = ['11', '21', '31', '12', '22', '32', '13', '23', '33'] #print(WAIT_MSG) if (messages) and (messages[-1] != WAIT_MSG) and (messages[-1] != str(client_socket)): print(x,y) if (x > -100) and (x < 0) and (y > 0) and (y < 100): pos = 1...
def locate_drawer_on_pos(pos, playing_type): locate_drawer_on_pos.counter += 1 pos = str(pos) drawer.pu() if playing_type == "x": drawer.setpos(-50 + (int(pos[0]) - 1) * 100, 40 - 100 * (int(pos[1]) - 1)) elif (playing_type == "o") and (locate_drawer_on_pos.counter != 1): drawer.setp...
This function handles an opponent's moves in a game by updating the game board with the opponent's symbol (X or O) based on received messages. It checks for valid positions, updates the board, removes used positions, and triggers win/loss checks. If the opponent wins, it displays a loss message, plays a sound, and exit...
def opponent_moves_handler(): possible_poses = ['11', '21', '31', '12', '22', '32', '13', '23', '33'] while True: if not("you lose!" in messages): if "o" in messages: opponent_type = "x" else: opponent_type= "o" if (len(messages) > ...
def validate_webhook_origin(push_payload, repo_owner, repo_name): try: origin_repo = push_payload["repository"]["full_name"] except KeyError: raise PayloadBadFormatError( f"Could not validate payload origin, 'repository/full_name' is missing." ) expected_repo = f"{repo_ow...
The function processes Bitbucket push events to identify changed file paths in a repository. It validates the webhook origin, establishes a retryable HTTP session with authentication, extracts change set hashes from the payload, and retrieves modified paths. Error handling is implemented for specific exceptions, with r...
def process_bitbucket_push_events( push_payload, repo_owner, repo_name, bitbucket_user, bitbucket_password ): validate_webhook_origin(push_payload, repo_owner, repo_name) retry_strategy = Retry( total=3, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["GET"], ) ...
def get_absolute_path(file_path): return os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "files", file_path) def load_source(file_path): file = open(file_path) source = json.load(file) file.close() return source def __save_to_graph(self, source): graph = Graph() grap...
The code's main task is to load data from a specified file path by converting it to an absolute path, retrieving the source data, and then saving this data into a graph structure using the `__save_to_graph` method. This process involves three key steps: path normalization, data loading, and graph storage.
def load(self, file_path): absolute_path = get_absolute_path(file_path) source = load_source(absolute_path) self.__save_to_graph(source)
def data_analysis(): #columns = ['Gender','Satisfaction','Business Travel','Department','EducationField','Salary','Home-Office','label'] columns = ['SnoringRate', 'RespirationRate', 'BodyTemperature', 'LimbMovement', 'BloodOxygen', 'EyeMovement', 'SleepingHours', 'HeartRate', 'label'] df = pd.read_csv('Stre...
The main task of the code is to train a random forest classifier on employee data, split into training and testing sets, evaluate its accuracy, and print predictions and individual decision trees. The process involves data analysis, model training with specified parameters, prediction, and accuracy calculation.
def main(): employeeData = data_analysis() train_df, test_df=train_test_split(employeeData,test_size=0.7) forest = randomForestAlg(train_df, n_trees=4, n_bootstrap=len(train_df), n_features=999, dt_max_depth=4) predictions = randomForestPred(test_df, forest) accuracy = calcAcc(predictions, test...
def make_space(): print('================================================================================') def check_turn_option(): invalid_turn_option = True while invalid_turn_option == True: try: global turn_chosen_option turn_chosen_option = int(input((f'{new_line}Select...
This function manages a turn-based game loop, handling player actions (spinning wheel, buying vowels, guessing word), updating game state variables, and controlling turn progression. It displays player info, the hidden word, and available options, then processes the selected action. Depending on outcomes, it either end...
def turns(): global turn_number turn_number = 1 while True: global turn_player_name turn_player_name = players_information[player_order[turn_number]]['Name'] global turn_player_round_earnings turn_player_round_earnings = players_information[player_order[turn_number]]['Round E...
def cancel_programm(dm_property): dm_property.touch_active = False clear_touch_id(dm_property) dm_property.touch_device_id = -1 def cancel(self, context): wm = context.window_manager wm.event_timer_remove(self._timer) def get_window_rect(hwnd): rect = win32gui.GetWindowRect(hwnd) x ...
This code handles touch input for a Blender add-on, processing Pygame events to manage finger interactions. It adjusts window positions, updates character positions based on touch motion, and manages touch states (down/motion/up). It also checks for active touch, cancels operations if disabled, and updates navigation o...
def modal(self, context, event): dm_property = context.scene.dm_property if dm_property.touch_active == False: print("EXIT TOUCH BY Property") cancel_programm(dm_property) pg.quit() self.cancel(context) return {'CANCELLED'} s...
def replace_ids(sentence): sentence = re.sub(" id ", " identifier ", sentence) return re.sub(" ids ", " identifiers ", sentence) def get_verb(tokens): root = [t for t in tokens if t["dep"] == ROOT][0] return find_verb_with_noun_child(tokens, root) def identify_method(verb_token): if verb_token is No...
This function parses a sentence to extract linguistic components, identifying tokens, verbs, HTTP methods, target resources, their parent resources, and potential parameters, returning structured data for further processing.
def get_all_info(sentence): sentence = replace_ids(sentence) tokens = get_tokens(sentence) verb = get_verb(tokens) method = identify_method(verb) target_resource = get_target_resource(tokens, verb) resource_parent = get_resource_parent(tokens, verb) possible_parameters = get_possible_paramet...
def get_path(info, doc): paths = doc["paths"].keys() matching_paths = list(paths) dummy_pattern = "" pattern = "" if info["resource_parent"] is not None and info["resource_parent"]["parent"] is not None: pattern = "^" + get_regex_pattern(info['resource_parent']['parent']) + "/.*" dum...
The function generates a request configuration by validating a path, constructing a URL with query parameters and headers, and returning the method, URL, headers, and empty body for an API call based on provided information and document structure.
def get_result(info, doc, path=None): if path is None: path = get_path(info, doc) if isinstance(path, str) is not True: return path else: info["resource_parent"] = None if path not in list(doc["paths"].keys()): raise CustomException("The path you specified...
def createStack(): stack = [] return stack def push(stack,item): stack.append(item) def pop(stack): if isEmpty(stack): return return stack.pop()
The main task of the code is to reverse a given string using a stack data structure. It pushes each character of the input string onto the stack, then pops them back into a new string, resulting in the reversed version. This leverages the stack's LIFO (Last-In-First-Out) property to invert the character order.
def reverse(string): n = len(string) #create an empty stack stack = createStack() # push all the characters of string to stack for i in range(0,n,1): push(stack,string[i]) # making the string empty since all characters are in stack string = '' # pop all characters of string and put them bac...
def sendmsg(sock, message): sock.send(message.encode()) def receive_data(sock): fragments = [] while True: try: data = sock.recv(1024) fragments.append(data .decode() .replace(" ", "") .spl...
The code implements a state machine to control a process involving sensor data reception, actuator movement, and status transitions. It cycles through states like 'waiting for plate', 'unaligned', and 'aligned', using received data to update the status and trigger actions such as sending commands, printing data, or ret...
def run_covi(status): global runApp while True: while runApp: match status: case 'waiting for plate': #transportdata = receive_data(CONNTRANSPORT) #if transportdata[0] == TRANSPORTRECV: status = 'plate arrived' ...
def handle_countSteps(steps, clear, getcount): global countSteps if clear: countSteps = [0, 0, 0] return 0 if getcount: return countSteps else: for i in range(len(steps)): if abs(countSteps[i] + steps[i]) >= MAXSTEPS: steps[i] = 0 e...
This code implements a state machine to control a mechanical system, transitioning between states like 'waiting for plate', 'aligned', and 'return to neutral'. It processes sensor data, sends commands to actuators, and updates status based on received responses, ensuring proper alignment and coordination with external ...
def handle_data(status): firstRun = True while True: match status: case 'waiting for plate': handle_countSteps(0, True, False) #data = receive_data(CONNEXTERN) #if data == 'OK': if runApp: firstRun = True ...
def advance_animation(self): """ Moves the animation by tik, returning the updated Circles list. """ for a, b in enumerate(self.people): b.move(self.tik) self.p2b_contact(b) self.circles[a].center = b.location self.p2p_contact() self.c...
The main task of the code is to update an animation frame by frame, tracking time progression (10 frames = 1 day), updating line graphs, and saving a simulation snapshot after 1000 frames (100 days). It increments counters, appends time data, triggers a save and animation stop at 1000 frames, and returns graphical elem...
def animate(self, i): """ FuncAnimation loop. """ self.advance_animation() self.timer = self.timer + 1 self.timeTOsave = self.timeTOsave + 1 # i/10 because 10 frames = 1 day self.x1.append(i/10) self.update_line_graph() # After a 1000frames...
def pawncheckmove(chboard, turn, pieceid, rank, file, movehistlist): # CORE PAWN MOVEMENT/CAPTURE FUNCTION, returns [True/False,ep/p/n] if turn == 1: if (p1pawncheckmove(chboard, pieceid, rank, file, movehistlist)[0]) and ( p1pawncheckmove(chboard, pieceid, rank, file, movehistlist)[1] == '...
This function applies a pawn move on a chessboard, validating the move via 'pawncheckmove'. If valid, it updates the board by removing the pawn from its original position and placing it at the new [rank,file]. It handles en-passant captures by removing the captured pawn, promotes the pawn if required using 'pawnpromote...
def applypawnmove(chboard, turn, pieceid, pmtdpieceid, rank, file, movehistlist): # moves pawn piece on chboard to index [rank,file], if promoted, promote checkresult = pawncheckmove(chboard, turn, pieceid, rank, file, movehistlist) if checkresult[0] == True: # pawnmove is valid, make pawn move if che...
def cloneboardlist(boardhistlist): # copies boardhiistlist onto a tempboardlist size = len(boardhistlist) if size == 0: return [] tempboardlist = [] for i in range(size): tempboard = np.copy(boardhistlist[i]) tempboardlist.append(tempboard) return tempboardlist def unipieced...
The function `threefoldcheck` determines if a three-fold repetition draw can be declared in chess by checking if the latest three board states in the history are identical, while ensuring en passant (EP) and castling rights remain unchanged across those positions. It clones historical boards, counts identical states, a...
def threefoldcheck(chboard, boardhistlist, movehistlist): # determines if three-fold repetition rule draw can be declared by the player tfboard, tfcounter, tempboardlist, tfturnlist, tfmovelist, tfsubmovelist = np.zeros((8, 8)), 0, cloneboardlist(boardhistlist), [], [], [] tfboardlist, tfsubboardlist = [], [] ...
def cloneboard(chboard): # copies chboard onto a tempboard tempboard = np.zeros((8, 8)) ranks, files = chboard.shape[0], chboard.shape[1] tempboard = np.zeros((ranks, files)) tempboard = np.copy(chboard) return tempboard def piecelocator(chboard, pieceid): # finds location of piece on the board, r...
The function checks if the current player's king is in check by analyzing all opponent pieces on the board. It iterates through each square, evaluates if any opposing pawn, knight, bishop, rook, or queen can capture the king in one move, and returns True if a threat is detected, otherwise False.
def checkcheck(chboard, turn, movehistlist): # determines if any player's king is currently in check tempboard, kingpos = cloneboard(chboard), [99, 99] if turn == 1: # Player 1 kingpos = piecelocator(tempboard, piecetypelist(turn, 'king')[0]) for rank in list(range(8)): for file i...
def cloneboard(chboard): # copies chboard onto a tempboard tempboard = np.zeros((8, 8)) ranks, files = chboard.shape[0], chboard.shape[1] tempboard = np.zeros((ranks, files)) tempboard = np.copy(chboard) return tempboard def piecelocator(chboard, pieceid): # finds location of piece on the board, r...
The function `kingcheckmove` verifies the validity of a king's move or capture in chess, checking for check/checkmate conditions and castle legality. It simulates the king's move on a cloned board, tests if any opposing piece can capture the king, and validates castling by ensuring the path is clear and the king isn't ...
def kingcheckmove(chboard, turn, pieceid, rank, file, movehistlist): # CHECKS for 'check' & 'checkmate' conditions, determines validity of king movement/capture kschboard = cloneboard(chboard) # kscboard stands for 'King Simulation CHess Board' kingloc = piecelocator(kschboard, pieceid) # king piece's rank/f...
def piecetypelist(turn, piecetype): # lists all possible pieceid for player's piecetype if turn == 1: if piecetype == 'pawn': return list(range(1, 9)) elif piecetype == 'knight': return [11, 12] + list(range(101, 109)) elif piecetype == 'bishop': return [...
The function determines all valid move positions for a specified chess piece on the board by iterating through every possible square, checking movement rules for the piece's type (pawn, knight, bishop, rook, queen, king), and collecting valid positions into a list. It uses specialized movement-checking functions for ea...
def pospiecemove(chboard, turn, pieceid, movehistlist): # determines all possible locations that a piece can move to poslist = [] if pieceid in piecetypelist(turn, 'pawn'): # check for all pawn movement locations for rank in list(range(chboard.shape[0])): for file in list(range(chboard.sha...
def checkturn(chboard,boardhistlist,movehistlist): # checks current player turn size = len(movehistlist) startboard = np.zeros((8, 8)) startboard[6, 0], startboard[6, 1], startboard[6, 2], startboard[6, 3], startboard[6, 4], startboard[6, 5], startboard[6, 6], startboard[6, 7] = 1, 2, 3, 4, 5, 6, 7, 8 s...
The function validates a chess move's legality based on the current turn and piece-specific movement rules, excluding check status checks. It verifies the correct turn, then assesses pawn, knight, bishop, rook, queen, or king moves using dedicated validation functions. Pawns include promotion checks. Returns True if va...
def chessimchecker(chboard, movehistlist, boardhistlist, pmtdpieceid, turn, pieceid, rank, file): # checks validity of move, does not check for check status if checkturn(chboard, boardhistlist, movehistlist) != turn: # If incorrect turn, function exits return False if pieceid in piecetypelist(turn, 'pa...
def cloneboard(chboard): # copies chboard onto a tempboard tempboard = np.zeros((8, 8)) ranks, files = chboard.shape[0], chboard.shape[1] tempboard = np.zeros((ranks, files)) tempboard = np.copy(chboard) return tempboard def checkcheck(chboard, turn, movehistlist): # determines if any player's kin...
The function `checkmatecheck` determines if the current player (P1 or P2) is in checkmate by simulating all possible moves of their pieces. If the player is already in check, it iterates through every piece on the board, generates new board states for each potential move, and checks if any move removes the check. If an...
def checkmatecheck(chboard, turn, movehistlist, boardhistlist): # determines if P1/P2 is in checkmate # no matter how the checkmated player moves, he cannot remove/evade the threat of check simboard = cloneboard(chboard) if checkcheck(simboard, turn, movehistlist) == True: # Player currently in a check ...
def average(rows): if len(rows)==0: return 0 arr = [] for row in rows: arr.append(data[target_attr][row]) npar = np.array(arr) avg = npar.mean() return avg def mean_squared_error(root, test_rows): total_squared_error=0 n = len(test_rows) if n==0: ...
The code prunes a decision tree by recursively evaluating whether removing a node's children reduces prediction error. It compares the mean squared error of pruned vs. unpruned states, discarding children if pruned error is lower. It tracks error rates per tree depth, updating a dictionary when pruning occurs. The func...
def prune(root, rows): if root.left == root.right == None: return Left = root.left Right = root.right root.left = root.right = None root.result = average(rows) pruned_error = mean_squared_error(best_root, test_rows) root.left = Left root.right = Right a...
def average(rows): if len(rows)==0: return 0 arr = [] for row in rows: arr.append(data[target_attr][row]) npar = np.array(arr) avg = npar.mean() return avg def best_attribute(rows, attributes): min_error = 10**18 # used as infinity best_attr = None partition_v...
This function builds a decision tree recursively by selecting the best attribute to split the data, handling numeric and categorical attributes differently. It partitions the dataset, creates left and right subtrees, and assigns average values when partitions are empty, continuing until no attributes remain.
def build_tree(rows, attributes): if len(attributes)==0: return Node(average(rows)) root = Node() root.attr, root.partitionVal=best_attribute(rows, attributes) # partitionVal is None for boolen attributes if(is_numeric(root.attr)): # if all values of the root.attr in the current ro...