dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def trans_start(cfg, start): s0 = fresh_nonterminal() return (s0, cfg + [[s0, [start]]]) def trans_term(cfg): terms = terminals(cfg) new = [] for [lhs, rhs] in cfg: new_rhs = [] for tok in rhs: if tok in terms: n = fresh_nonterminal() new.a...
The main task of the code is to convert a context-free grammar (CFG) into Chomsky Normal Form (CNF) by sequentially applying transformations: renaming the start symbol, eliminating terminal symbols from productions, removing binary rules, and resolving unit productions. The function returns the modified start symbol an...
def to_cnf(cfg, start): cnf = cfg s0, cnf = trans_start(cnf, start) cnf = trans_term(cnf) cnf = trans_bin(cnf) cnf = trans_unit(cnf) return (s0, cnf)
def to_num(s): n = 0 factor = 1 for i in range(len(s)): n += (ord(s[-(i + 1)]) - ord('a')) * factor factor *= 26 return n def next_valids(n): while True: while not valid(n): n += 1 yield n n += 1 def from_num(n): s = '' for d in digits(n): ...
The code reads a numeric value from a file, generates valid passwords using a generator function, and prints the first two valid passwords. It converts the file's content to a number, processes it to find valid passwords, then outputs the first two results. The task involves password validation and sequential retrieval...
def main(): with open('resources/day11.txt', 'r') as f: n = to_num(f.read().strip()) pws = next_valids(n) print(f'Part 1: {from_num(next(pws))}') print(f'Part 2: {from_num(next(pws))}')
def nearestPrime(num): x = num y = num while not isPrime(x): x -= 1 continue diff1 = num-x while not isPrime(y): y += 1 continue diff2 = y-num if(diff1 <= diff2): return x return y def relativePrime(phi, p, q): for e in range(2, phi): ...
The code implements RSA encryption and decryption. It generates public and private keys using primes derived from input string lengths, computes modular inverses, and applies encryption/decryption functions to a plaintext message, demonstrating the RSA algorithm's key generation and data transformation process.
def RSA(str1, str2, pt): # Step1 p = nearestPrime(len(str1)) q = nearestPrime(len(str2)) # Step2 n = p * q # Step3 phi = (p-1) * (q-1) # Step4 e = relativePrime(phi, p, q) print(e) # Step5 d = extEuclidean(phi, e) print(d) # Step6 ct = encryption(pt, e, n) ...
def get_brand_tweets(brand): conn = sqlite3.connect('./usernames.db') cursor = conn.execute("select brandId, tweetId from tweets where brandId = '{0}'".format(brand)) l = [] for row in cursor: l.append(row) conn.close() return l def get_already_parsed_tweets(): conn = sqlite3.connect...
The code retrieves tweets for a given brand, fetches their likes and retweets, and stores the associated usernames in a database. It skips already processed tweets and handles rate limits by pausing when no data is found. The function extracts engagement data (likes/retweets) and records user interactions with brand tw...
def get_retweet_favorite_usernames(brand): tweet_ids = get_brand_tweets(brand) extracted = get_already_parsed_tweets() for brand,tweet_id in tweet_ids: if not tweet_id.isnumeric() or tweet_id in extracted: print(tweet_id in extracted) continue url = "https://twitter.c...
def print_granularity(self) -> str: if self.exchange == Exchange.KUCOIN: return self.granularity.to_medium if self.exchange == Exchange.BINANCE: return self.granularity.to_short if self.exchange == Exchange.COINBASEPRO: return str(self.granularity.to_integer) ...
This code initializes and runs a trading bot for a specified cryptocurrency exchange (Coinbase Pro, Binance, or Kucoin). It establishes websocket connections for real-time data, configures smartswitch settings, sends notifications via Telegram, executes trading jobs, handles errors with auto-restart, and gracefully shu...
def run(self): try: message = "Starting " if self.exchange == Exchange.COINBASEPRO: message += "Coinbase Pro bot" if self.websocket and not self.is_sim: RichText.notify("Opening websocket to Coinbase Pro", self, "normal") ...
def clear(): #Clears the terminal if platform.system()=="Windows": subprocess.Popen("cls", shell=True).communicate() print('') else: print("\033c", end) def ace_switch(player_active): #Turns an ace from being worth 11 to 1 #Check if player busted if player_active.get_val()>21: ...
This function handles a player's first turn in a card game, displaying their hand and the dealer's face-up card. It prompts the player to 'Hit' or 'Stay', deals a card if they choose 'Hit', checks for a bust (exceeding 21) considering aces, and either ends the turn or continues gameplay if no bust occurs.
def player_turn1(cards,player_active,dealer): #Player's first hand if split clear() #Show cards print(f'Your first hand:{player_active.hand}') print(f'Dealer card: {dealer.hand[0]}') #Player decides action ans=getAnsStr('Hit or Stay: ',['Hit','Stay']) if ans=='Hit': #Deal first hand player_a...
def clear(): #Clears the terminal if platform.system()=="Windows": subprocess.Popen("cls", shell=True).communicate() print('') else: print("\033c", end) def ace_switch(player_active): #Turns an ace from being worth 11 to 1 #Check if player busted if player_active.get_val()>21: ...
This function handles a player's second hand in a card game (likely blackjack) after splitting. It displays the player's split hand and dealer's upcard, prompts the player to 'Hit' or 'Stay', deals a card if 'Hit' is chosen, checks for a bust (exceeding 21) considering aces, and continues the turn if not busted. If bus...
def player_turn2(cards,player_active,dealer): #Player's second hand if split clear() #Show cards print(f'Your second hand:{player_active.hand_split}') print(f'Dealer card: {dealer.hand[0]}') #Player decides action ans=getAnsStr('Hit or Stay: ',['Hit','Stay']) if ans=='Hit': #Deal first action ...
def _get_class(self, classes_path): classes_path = os.path.expanduser(classes_path) with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def _get_anchors(self, anchors_path): anchors_path = os.path...
This code initializes a YOLO-based face detection model by loading pre-defined class names, anchor boxes, and a trained model from a specified path. It sets detection thresholds (IoU and score), image size, and prepares the model for inference by initializing session variables and output components like bounding boxes,...
def __init__( self, iou_threshold=0.45, score_threshold=0.5, model_path="models/YOLO_Face.h5", classes_path="models/face_classes.txt", anchors_path="models/yolo_anchors.txt", img_size=(416, 416), ): self.iou_threshold = iou_threshold self.score...
def setGaussianWave(xPos,yPos,waveWidth,kx,ky): for i in range(1,g_NNx-1): for j in range(1,g_NNy-1): x = i*g_dx y = j*g_dy phAb = math.exp(-((x-xPos)*(x-xPos)+(y-yPos)*(y-yPos))/(4*waveWidth*waveWidth) ) phPh = kx*x+ky*y g_psi[i][j][0] = phAb*math.cos(phPh) g_psi[i][j][1] = phAb*math.sin(phPh) fo...
This function initializes simulation conditions based on the input theme by setting global variables and configuring wave/potential parameters. It defines different physical scenarios (free space, parabolic potential, tunnel effect, etc.) through conditional logic, using appropriate wave and potential setup functions f...
def setInitialCondition(theme): global g_inkey, g_pauseFlag, g_sysTime, g_theme, g_lossSW g_theme = theme g_inkey = 0 g_pauseFlag = 0 g_sysTime = 0.0 g_lossSW = 0 # set potential and wave xMax = g_NNx*g_dx yMax = g_NNy*g_dy if (theme==0): # 0:free space setGaussianWave(0.25*xMax,0.5*yMax,5.0,1.0,0.0) #...
def phaseStep(ph, vv, dt): for i in range(1,g_NNx-1): for j in range(1,g_NNy-1): th = dt*g_vv[i][j] cs = math.cos(th) sn = math.sin(th) phr = ph[i][j][0] phi = ph[i][j][1] ph[i][j][0] = cs*phr+sn*phi ph[i][j][1] = cs*phi-sn*phr def kxStep(ph, dt): a = 4.0*g_dy*g_dy/dt; aaAb = 4.0+a*a; for j i...
The code simulates the time evolution of a quantum system's wavefunction (g_psi) over nCalc steps. It advances system time (g_sysTime) by g_timeStep, applying phase, kx, and ky steps to evolve the state. If lossSW=1, it applies energy loss/damping via lossEnergy(). The function likely implements a split-step method for...
def timeEvolution(nCalc, lossSW): # nCalc: repeat evolve times # lossSW: 0:no loss, 1:loss global g_sysTime for i in range(nCalc): g_sysTime += g_timeStep phaseStep(g_psi,g_vv,0.5*g_timeStep) kxStep(g_psi,g_timeStep) kyStep(g_psi,g_timeStep) phaseStep(g_psi,g_vv,0.5*g_timeStep) if (lossSW==1): lossEn...
def drawText(txt,x,y): # render(text, antialias, color, background=None) -> Surface text = g_font.render(txt, 1, g_textColor) # blit(source, dest, area=None, special_flags=0) -> Rect g_screen.blit(text, (x,y)) def meanKinetic(ph): h2 = g_dx*g_dx p = 0.0 for i in range(1,g_NNx-1): for j in range(1,g_NNy-1): ...
The main task of the code is to render a quantum simulation visualization by clearing the screen, drawing a bounding box, displaying simulation parameters (time, energy, normalization), and rendering the wavefunction (ψ) in different modes (density, phase, current, etc.) based on the drawMode input. It updates the disp...
def drawScreen(drawMode): # clear screen g_screen.fill(g_backgroundColor) # draw box # rect(surface, color, rect) -> Rect (filled box) # draw rect outline: rect(surface, color, rect, width, ... ) -> Rect pygame.draw.rect(g_screen, g_boxColor, g_boxRect) drawText('box(au) = %s x %s' % ( str(round(g_NNx*g_dx,1))...
def setFreePotential(): for i in range(g_NNx): g_vv[i] = 0.0 def setWave(wavePos, waveWidth, momentum): a = pow(2.0*math.pi*waveWidth*waveWidth,-0.25) for i in range(g_NNx): x = i*g_dx phAb = a*math.exp(-((x-wavePos)/(2.0*waveWidth))*((x-wavePos)/(2.0*waveWidth))) phPh = momentum*x g_phRe[i] = phAb*math.co...
The function `setInitialCondition` initializes simulation parameters based on a given theme. It sets global variables (`g_theme`, `g_inkey`, etc.) and configures potential and wave functions for different scenarios: free space (theme 0), parabolic potential (theme 1), tunnel effect (theme 2), step hill (theme 3), and h...
def setInitialCondition(theme): global g_inkey, g_pauseFlag, g_sysTime, g_theme, g_lossSW g_theme = theme g_inkey = 0 g_pauseFlag = 0 g_sysTime = 0.0 g_lossSW = 0 # set potential and wave xMax = g_NNx*g_dx if theme==0: # 0:free space setFreePotential() setWave(0.25*xMax, 10.0, 1.0) # (wavePos,waveWidt...
def phaseStep(hdt): # evolve hdt=0.5*dt for i in range(1,g_NNx-1): th = hdt*g_vv[i] cs = math.cos(th) sn = math.sin(th) phr = g_phRe[i] phi = g_phIm[i] g_phRe[i] = cs*phr+sn*phi g_phIm[i] = -sn*phr+cs*phi def kxStep(dt): bbRe = 2.0 bbIm = 4*g_dx*g_dx/dt aaRe = -2.0 aaIm = 4*g_dx*g_dx/dt aaAb = aaR...
This function simulates a system's time evolution over `nCalc` steps using a time step `dt`. It updates the global system time (`g_sysTime`), applies phase and kinetic steps (`phaseStep`, `kxStep`), and optionally calculates energy loss using `lossEnergy` if `lossSW` is enabled. The simulation incorporates time advance...
def timeEvolution(dt, nCalc, lossSW): global g_sysTime dt = g_timeStep for i in range(nCalc): g_sysTime += dt phaseStep(0.5*dt) kxStep(dt) phaseStep(0.5*dt) if lossSW==1 : lossEnergy(g_dampingFactor)
def ajustVelocity(temp): a = math.sqrt(temp/systemTemperature()) for i in range(g_N): g_vx[i] = a*g_vx[i]; g_vy[i] = a*g_vy[i]; def registerNearParticles(): rCut = g_rCutoff+20*2000*g_timeStep rcut2 = rCut*rCut for i in range(g_N-1): k = 1 for j in range(i+1,g_N): r2 = (g_px[i]-g_px[j])*(g_px[i]-g_px[j]...
The function `timeEvolution` simulates a system's time evolution over 20 steps. It adjusts particle velocities based on the controlled temperature (`contTemp`) if `tempMode` is set to 1. It registers nearby particles, increments the global system time (`g_sysTime`) by `g_timeStep` repeatedly, and updates particle posit...
def timeEvolution(tempMode,contTemp): # tempMode: 0:adiabatic, 1:controled # contTemp: system tempeature controled to conTemp(K) global g_sysTime if (tempMode==1): ajustVelocity(contTemp) registerNearParticles() for i in range(20): g_sysTime += g_timeStep moveParticles(g_timeStep)
def check_auth(self, username, password): return username == USERNAME and password == PASSWORD def auth_required(self,request): return Response( "Please log-in to continue", 401, {"WWW-Authenticate": 'Basic realm="login required"'} ) def dispatch_request(self,...
This code defines a WSGI application function that processes incoming requests. It creates a request object, checks for authentication credentials, and either returns an authentication-required response or dispatches the request to the appropriate handler based on authentication status. The function returns the respons...
def wsgi_app(self, environ, start_response): request = Request(environ) auth = request.authorization if not auth or not self.check_auth(auth.username, auth.password): response = self.auth_required(request) else: response = self.dispatch_request(request) re...
def getMathSH2DValue(degree, idx, phi): if degree == 0: if isinstance(phi, list): return [1.0 for _ in range(len(phi))] return 1.0 if not isinstance(phi, list): return getSH2DValueWithMethod(degree, idx, phi, math, "math") value_list = [] for p in phi: value...
This function computes a 2D spherical harmonic value based on the specified method (e.g., math, numpy, torch, etc.), degree, index, and angle. It acts as a dispatcher, selecting the appropriate implementation from different libraries while handling optional data type specifications for tensor-based methods like numpy, ...
def getSH2DValue(degree, idx, phi, method_name="math", dtype=None): assert method_name in ["math", "numpy", "torch", "jittor", "scipy"] match method_name: case "math": return getMathSH2DValue(degree, idx, phi) case "numpy": if dtype is None: return getNum...
def getMathSH3DValue(degree, idx, phi, theta): if degree == 0: if isinstance(phi, list): return [1.0 for _ in range(len(phi))] return 1.0 if not isinstance(phi, list): return getSH3DValueWithMethod(degree, idx, phi, theta, math, "math") value_list = [] for p, t in z...
This function computes the 3D spherical harmonic value for given parameters (degree, idx, phi, theta) using a specified library/method (math, numpy, torch, jittor, scipy). It routes the computation to the corresponding implementation function based on the method name, with optional dtype handling for tensor-based libra...
def getSH3DValue(degree, idx, phi, theta, method_name="math", dtype=None): assert method_name in ["math", "numpy", "torch", "jittor", "scipy"] match method_name: case "math": return getMathSH3DValue(degree, idx, phi, theta) case "numpy": if dtype is None: ...
def clear_screen(self): """Clears the screen. It's either Unix-like or Windows.""" try: os.system('clear') except Exception: os.system('cls') def display_menu(self): """Display menu.""" print('\t\t\tHousehold Inventory Application') print() print('\t\t1. New Inventory (Not Implemented)') print('\t...
The main task of the code is to start an application loop that repeatedly clears the screen, displays a menu, and processes user menu choices until the loop is terminated by setting self.keep_going to False.
def start_application(self): """Start the applications.""" while self.keep_going: self.clear_screen() self.display_menu() self.process_menu_choice()
def stem(x, filters, kernel_size=(3, 3), padding="same", strides=1): conv = Conv2D(filters, kernel_size, padding=padding, strides=strides)(x) conv = conv_block(conv, filters, kernel_size=kernel_size, padding=padding, strides=strides) shortcut = Conv2D(filters, kernel_size=(1, 1), padding=padding, strides=s...
This code defines a ResUNet model for image segmentation, combining residual blocks in an encoder-decoder structure. It uses downsampling in the encoder, a bridge, and upsampling with concatenation in the decoder. The model outputs binary segmentation maps via a sigmoid-activated layer, compiled with Adam optimizer and...
def ResUNet(pretrained_weights = None, input_size = (256,256,1)): f = [16, 32, 64, 128, 256] ## Encoder inputs = Input(input_size) e1 = stem(inputs, f[0]) e2 = residual_block(e1, f[1], strides=2) e3 = residual_block(e2, f[2], strides=2) e4 = residual_block(e3, f[3], strides=2) e5 = resi...
def get_joint_names(self): # return self.joint_positions.joint_names return self.joint_names def publish_servo_positions(self, names, cmd: JointTrajectoryPoint): # rospy.loginfo("publish_servo_positions") # TODO: Transform joint positions to servo positions to pwm values angles =...
This function publishes joint position commands to servo controllers and the joint state topic. It checks if joint positions are available, retrieves the first command, gets joint names, then calls two publishing methods to send the positions to servos and the joint state interface.
def publish_positions(self, event): if not self.joint_positions: # No commands received yet return # print("Timer called at " + str(event.current_real)) cmd = self.joint_positions.points[0] names = self.get_joint_names() self.publish_servo_positions(names,...
def getDestIP(): yourIP = input("Do you want to use your own IP as a victim (Y/N)? ") if(yourIP == "Y" or yourIP == "y"): destIP = get_if_addr(conf.iface) return destIP elif (yourIP =="N" or yourIP =="n"): destIP = input("Target IP: ") return destIP else: pri...
The main task of the code is to initiate a SYN flood attack by calling the SYN_DOS function with parameters like destination IP, port, packet count, and flags to determine attack configuration (single IP or same subnet). It clears the screen, collects user inputs, and executes the attack.
def main(): os.system("cls") #Clearing the screen destIP = getDestIP() print("Destination IP is {}".format(destIP)) destPort = getDestPort() counter = getNumofPackets() singleIPBool = getifSingleIP() subIPBool = getifSameSubnet() SYN_DOS(destIP,destPort,counter,singleIPBool, subIPBool)
def enterOffboard(dummySetpoint : tuple, stateMt : stateMoniter, ctl : control, paramState : rospy.ServiceProxy, local_pos_pub : Publisher, local_vel_pub : Publisher, rate : rospy.Rate) -> None : # Switching the state to offboard while not rospy.is_shutdown() : # ctl.setAccAllowance() # print('...
The code navigates a drone through a sequence of setpoints, ensuring it remains in OFFBOARD mode by correcting mode errors. It publishes position and velocity commands to reach each setpoint, checks for target detection, and adjusts trajectories accordingly. If the target is found or all setpoints are completed, it lan...
def coverSetpoints(setpointsIndices : list, setpoints : list, stateMt : stateMoniter, local_pos_pub : Publisher, local_vel_pub : Publisher, rate : rospy.Rate, ctl : control, paramState : ServiceProxy, findingTarget = True) -> None : for setpoint in setpointsIndices : while not rospy.is_shutdown() : ...
def addSetpoint(coords : tuple, velocity : tuple, setpoints : list) -> None : # Neatly adds setpoints, given coordinates and velocity vector # coords must be a 3D tuple having x, y, z values # velocity must be likewise a 3D tuple having linear velocity componenets along x, y and z axes. # setpoints is t...
The main task of the code is to control a drone through a predefined sequence of movements using setpoints, including takeoff, navigation along waypoints, object pickup/drop via gripper control, and landing. It subscribes to sensor data, publishes setpoints for position/velocity, transitions to OFFBOARD mode, and itera...
def main(name : str) -> None: stateMt = stateMoniter() ctl = control(name) rospy.Subscriber(name + '/mavros/local_position/pose', PoseStamped, stateMt.posiCallBack) rospy.Subscriber(name + '/gripper_check', std_msgs.msg.String, stateMt.gripperCallBack) Subscriber(name + '/camera/image_raw', Image,...
def ransac_registration(self, verbose = True): """ Implements Global RANSAC registration based on feature matching and returns a registration.RegistrationResult object. Source: Adapted from open3d global registration documentation: http://www.open3d.org/docs/release/tutorial/pipelines/global_registrati...
This function registers point cloud data using a specified algorithm (RANSAC, ICP, or Colored ICP), dispatching to the corresponding method based on the input. It accepts a 'verbose' flag to control output detail. If an invalid algorithm is specified, it raises an error requiring a valid choice from the listed options.
def register_pcd(self, registration_algorithm, verbose = True): if registration_algorithm == 'ransac': self.ransac_registration(verbose = verbose) elif registration_algorithm == 'icp': self.icp_registration(verbose = verbose) elif regist...
def extract_info(self, files): processed_filenames = [] for idx, file in enumerate(files): data = json.load(open(Path(__file__).parent.parent / 'data' / file, 'r')) jsonData = [] for page in data: soup = BeautifulSoup(page['content'], 'html.parser') ...
The main task of the code is to perform data ingestion in three stages: fetching data from a source using multiple threads, extracting relevant information from the fetched data, and combining the extracted data into a unified dataset. The process is logged with start and completion markers for tracking progress.
def main(self): self.logger.info('<<<<<<<<<<<<<<<<< STAGE 1: Data Ingestion Started >>>>>>>>>>>>>>>>>') files = self.extract_info(self.fetch_data_from_source(self.n_threads)) self.combine_files_to_dataset(files) self.logger.info('<<<<<<<<<<<<<<<<< STAGE 1: Data Ingestion Completed >>>>>>...
def localBackup(self): bkFile = self.tsm('backup') print("Backup Complete. Downloading File") self.moveTabBackup('download', bkFile) def runSshCommand(self, cmd, live=True): domain = getVar(self.varList, 'domain_zone') cname = getVar(self.varList, 'dns_cname') if live: ...
The code's main task is to perform a local backup, confirm it, execute an unlicensing script via SSH, confirm that step, and then destroy Terraform-managed infrastructure, ensuring each critical action is acknowledged by the user before proceeding.
def kill(self): print("Backing Up Locally") self.localBackup() input("Did it Backup?") print("Unlicensing") self.runSshCommand("/opt/tableau/data/unlicense.sh") input("Did it unlicense?") self.terraform('destroy')
def terraform(self, tfAction): loc = f"{self.buildLoc}/{self.deployment}" os.chdir(loc) print(f"in {loc}") tf = nconfig.deployments()[self.serviceName]['terraformPath'] print(tf) if tfAction.lower() == "apply": runCmdLive([tf, "init"]) runCmdLive([...
This method determines which action to execute based on the `self.action` value, invoking corresponding functions like Terraform operations, SSH commands, backup/restore tasks, or error handling for unknown actions.
def runArgs(self): if self.action.lower() == 'plan': return self.terraform('plan') elif self.action.lower() == 'apply': return self.terraform('apply') elif self.action.lower() == 'destroy': return self.terraform('destroy') elif self.action.lower() == 'kill': return self.kill() el...
def add_block(self, block, x=4, y=0): block.set_pos([x, y]) self.current_block = block try: self.update() except: self.running = False def notify_new_block(self): for view in self.views: view.draw_next_block() def generate_bag(self): ra...
The main task of the code is to retrieve and add a block from the `bag` list, notify of the new block, and generate a new bag if the current bag contains fewer than 6 items, ensuring a minimum of 6 blocks are available for processing.
def next_block(self): self.add_block(self.bag.pop()) self.notify_new_block() if len(self.bag) < 6: self.generate_bag()
def clear_block(self, board, pos, shape): for i in range(len(shape)): for j in range(len(shape[0])): if board[i+pos[1]][j+pos[0]][0] - shape[i][j] < 0: raise ValueError if shape[i][j] == 1: board[i+pos[1]][j+pos[0]] = [0, (15, 1...
This function handles holding a game piece by clearing the current block from the board. If a held piece exists, it swaps the current block with the held one and restores the former held piece. If no held piece exists, it stores the current block and advances to the next block. Finally, it disables further holding unti...
def hold_piece(self): if not self.able_to_hold: return self.clear_block(self.board, self.current_block.pos, self.current_block.shape) if self.held_piece != 0: former_held = self.held_piece self.held_piece = self.current_block self.add_block(former_...
def test_update(self, prev_pos=False, prev_shape=False): test_board = deepcopy(self.board) if prev_pos or prev_shape: self.clear_block(test_board, prev_pos, prev_shape) if self.current_block: self.place_current_block(test_board) def update(self, prev_pos=False, prev_sha...
This code simulates dropping a block in a game (like Tetris) by repeatedly moving it down until it collides with another block. It uses a loop to test the move, reverts to the previous position on collision, then places the block permanently. The main task is to determine the block's final resting position by checking ...
def drop(self): prev_pos = deepcopy(self.current_block.get_pos()) prev_shape = deepcopy(self.current_block.get_shape()) self.current_block.move_down() while True: try: self.test_update(prev_pos, prev_shape) except: self.current_bloc...
def _make_output(self): return dict( force = 0. ) def fuzzification(self, input_value_dict): cp = input_value_dict.get('cp') cv = input_value_dict.get('cv') pa = input_value_dict.get('pa') pv = input_value_dict.get('pv') #print(cp,cv,pv,pa) if ...
This code performs fuzzy logic-based decision-making by fuzzifying input data, applying inference rules, defuzzifying results, and returning the computed force value as the output.
def decide(self, world): output = self._make_output() fuzzi_value_dict = self.fuzzification(self._make_input(world)) fuzzi_output_value_dict = self.inference(fuzzi_value_dict) force = self.defuzzification(fuzzi_output_value_dict) output['force'] = force return output['...
def read_releaseinfo(self) -> None: """Reads release info page (https://www.imdb.com/title/{movie_id}/releaseinfo)""" releaseinfo_page = r.get(self.base_url + "/releaseinfo") soup = Bs(releaseinfo_page.content, "html.parser") # get titles (from the AKAs section) title_table = ...
The code's main task is to load data from a site by reading release information, title page details, and optionally full credits if enabled, ensuring comprehensive data retrieval in a structured manner.
def load(self) -> None: """Loads all data from site""" self.read_releaseinfo() self.read_titlepage() if self.load_credits: # optional data self.read_fullcredits()
def unary(self,): if self.check_token(Token_Type.PLUS) or self.check_token(Token_Type.MINUS): self.emitter.emit(self.cur_token.text) self.next_token() self.primary() def check_token(self, kind): return kind == self.cur_token.kind def next_token(self,): self.cur_t...
The main task of the code is to parse division/multiplication terms in an expression. It first processes a unary operand, then repeatedly checks for '/' or '*' operators, emitting the operator token and parsing the next unary operand, allowing chained operations like "a / b * c"
def term(self,): self.unary() while self.check_token(Token_Type.SLASH) or self.check_token(Token_Type.ASTERISK): self.emitter.emit(self.cur_token.text) self.next_token() self.unary()
def term(self,): self.unary() while self.check_token(Token_Type.SLASH) or self.check_token(Token_Type.ASTERISK): self.emitter.emit(self.cur_token.text) self.next_token() self.unary() def check_token(self, kind): return kind == self.cur_token.kind def next_to...
This code parses arithmetic expressions with addition and subtraction. It starts by parsing a term, then repeatedly checks for '+' or '-' operators. When found, it emits the operator, advances the token, and parses another term, building the expression step-by-step.
def expression(self,): self.term() while self.check_token(Token_Type.PLUS) or self.check_token(Token_Type.MINUS): self.emitter.emit_line(self.cur_token.text) self.next_token() self.term()
def expression(self,): self.term() while self.check_token(Token_Type.PLUS) or self.check_token(Token_Type.MINUS): self.emitter.emit_line(self.cur_token.text) self.next_token() self.term() def is_comparison_operator(self,): return self.check_token(Token_Type.G...
The code parses a comparison expression by first evaluating an expression, checking for a comparison operator, emitting it if found, and recursively evaluating another expression. It continues this process in a loop to handle chained comparisons, aborting if an expected operator is missing. The main task is to validate...
def comparison(self,): self.expression() if self.is_comparison_operator(): self.emitter.emit(self.cur_token.text) self.next_token() self.expression() else: self.abort('Expected comparison operator at: {}'.format( self.cur_token.te...
def check_token(self, kind): return kind == self.cur_token.kind def next_token(self,): self.cur_token = self.peek_token self.peek_token = self.lexer.get_token() def expression(self,): self.term() while self.check_token(Token_Type.PLUS) or self.check_token(Token_Type.MINUS): ...
This code processes programming language statements, generating C code via an emitter. It handles PRINT (strings/expressions), IF/WHILE loops, LABEL/GOTO jumps, variable declarations (LET), and INPUT. It validates syntax, manages symbols, and emits corresponding C constructs like printf, if/while blocks, and scanf, whi...
def statement(self,): # PRINT (expression | string) if self.check_token(Token_Type.PRINT): self.next_token() if self.check_token(Token_Type.STRING): self.emitter.emit_line('printf(\"{}\\n\");'.format( self.cur_token.text ) ...
def prep_macro(mac,mac_vars): """Function to prepare the macroeconomic input data by carrying out the feature engineering. For each feature, this involves finding the 12 month difference (ACH), the 12 month percentage change (PCH), before finding the 3 month moving average and then finding the ACH and P...
The function `stock_data_prep` prepares data for direct modeling by performing feature engineering (smoothing, differencing, percentage change), feature screening to retain independent variables strongly correlated with the target, and standardization. It aligns stock and macroeconomic data, removes missing values, app...
def stock_data_prep(stock_act,full_prc_pch,full_prc_ach,full_est_pch,full_est_ach, mac,mac_vars,stock_isin,full_isins, wanted_dates,keep_est,train_size=0.8): """Parent function to prepare data for direct modelling. This involves feature engineering to create multiple diff...
def gaussian_blur(image, kernel_size): kernel = gaussian_kernel(kernel_size, sigma=math.sqrt(kernel_size)) return convolution(image, kernel, average=True) def sobel_edge_detection(image, edge_filter): copy_image = image.copy() new_image_x = convolution(copy_image, edge_filter) new_image_y = convolut...
The code performs edge detection on a grayscale image using a specified edge filter. It applies Gaussian blurring, computes gradient magnitude and direction via Sobel detection, applies non-max suppression, thresholds the result, and uses hysteresis to finalize edges, returning the processed image as an 8-bit unsigned ...
def edge_detect(gray_image, edge_filter): copy_image = gray_image.copy() gaussian_blurred_image = gaussian_blur(copy_image, len(edge_filter) * len(edge_filter[0])) gradient_magnitude, gradient_direction = sobel_edge_detection(gaussian_blurred_image, edge_filter) out = non_max_suppression(gradient_magnit...
def create_individuals(howmany,fromold): individuals=[] if (not fromold): d=howmany else: d=howmany-len(fromold) for ii in range(0,d): skim_small=skimmers(15,100,np.random.randint(1,50)) #https://www.globalspill.com.au/product/weir-skimmer-30000-lhr-gsw30esp/ skim_large=s...
This code implements a genetic algorithm to optimize skimmer and boom configurations for a scenario, aiming to minimize a fitness metric. It evolves populations over generations, evaluates fitness, visualizes results, and outputs optimal parameters like skimmer numbers and boom lengths. The algorithm halts when fitness...
def main(): # Genetic Algorithm n=20 # We are gonna have 9 individuals in each gen maxgens=200 bestfitness_old=0 old=[] plt.ion() for gen in range(0,maxgens): ind=create_individuals(n,old) fitness,boom_length,rem,ns,nl=compute_fitness(ind) min_fit=min(fitness) ...
def initalize(): gs = [] for i in range(0,boardsize): gs.append([]) for j in range(0,boardsize): gs[i].append('-') return gs def printboard(gs): global boardsize for row in gs: rowprint = '' for element in row: rowprint += element r...
The main task of the code is to manage a turn-based board game between 'x' and 'o' players. It initializes the game state, alternates turns, validates moves, tracks groups and scores, and determines the winner. The loop continues until both players pass consecutively, after which scores are calculated and the result is...
def main(): ## Either 'o' or 'x', determines who's turn it is global xoro ## The opposite of xoro, determines who's turn it is not global notxoro ## Game State Current, the current layout of the board ## This value is two-dimensional list, the higher dimension being ## lists representing the...
def playerMoving(self, player, symbol): playerMove = int(input(f"Enter the block number to place {symbol} in any of the vacant Positions: ")) currentPlayerMoveCheck = self.checkPlayerMoveValidity(playerMove) while(not currentPlayerMoveCheck): if(player.foulPlay<=2): s...
This code manages a tic-tac-toe game between two players. It alternates turns, handles human and CPU moves, updates the game board, checks for a win after each move, and determines the winner or declares a draw when all 9 moves are exhausted.
def beginGame(self, player1, player2): gameMoves = 0 while(gameMoves<9): if gameMoves==0: self.gameBoard.printGameBoard() if player1.name!='CPU': player1Move=self.playerMoving(player1, 'X') if player1Move==-1: ...
def reverse_engineering_menu(): while True: print("\nReverse Engineering Menu:") print(colored("1. Patch reversing(strings from exe)", "blue")) print(colored("2. Hex Dump", "blue")) print(colored("3. Analyze Exe", "blue")) print(colored("4. Back to Main Menu", "blue")) ...
The main task of the code is to display a menu-driven interface for the HashHawk Cracker and Analyzer tool, featuring colored ASCII art and options for reverse engineering, network analysis, scans, zip file handling, password cracking, and DDoS attacks. It processes user input to navigate sub-menus, handles invalid cho...
def main_menu(): while True: ART_COLOR = "blue" art = colored(''' ██░ ██ ▄▄▄ ██████ ██░ ██ ██░ ██ ▄▄▄ █ █░██ ▄█▀ ▓██░ ██▒▒████▄ ▒██ ▒ ▓██░ ██▒▓██░ ██▒▒████▄ ▓█░ █ ░█░██▄█▒ ▒██▀▀██░▒██ ▀█▄ ░ ▓██▄ ▒██▀▀██░▒██▀▀██░▒██ ▀█▄ ▒█░...
def cyan(s): return "\x1b[1;36m" + str(s) + "\x1b[0m" def do_503(self): if self.server.restart: message = "Try again in a moment" else: message = "It needs to be manually restarted" self.send_response(503) ...
This method handles HTTP GET requests by triggering server shutdown/restart, initializing content, serving pages, or returning 404 errors based on the request path and server state.
def do_GET(self): """ Called when the server receives an HTTP GET request """ if self.path == '/shutdown': print(cyan("Shutting down immediately...")) self.server.timer = 0 self.server.restart = ...
def execute(self): raise NotImplementedError() def _handle_exception(self, ex: Exception): if self._error_callback: self._error_callback(self, ex) else: raise ex self.stop() def _schedule_next_execution(self): with self._next_execution_lock: if...
This method executes a task while handling exceptions and scheduling the next execution. It acquires a lock to ensure thread safety, runs the core execution logic, catches any exceptions to handle them, and schedules the next execution only if the current one completes successfully without errors.
def _execute(self): try: with self._next_execution_lock: self.execute() except Exception as ex: self._handle_exception(ex) else: self._schedule_next_execution()
def perform_mapping(self, struct_dict, element_mapping_dict): output_dict = {} for key, value in struct_dict.items(): if key in element_mapping_dict: if isinstance(value, str): self.set_dictionary_value(output_dict, element_mapping_dict[key], value) ...
The main task of the code is to process each section of a file (e.g., PE file) by mapping its attributes using predefined mappings, calculating data hashes and entropy values, and returning a list of dictionaries containing these processed section details.
def parse_sections(self): sections_list = [] for section in self.root_entry.sections: section_dict = self.perform_mapping(section.dump_dict(), IMAGE_SECTION_HEADER_MAPPINGS) section_dict['data_hashes'] = self.get_hash_list(section) section_dict['entropy'] = self.get_e...
def parse_headers(self): headers_dictionary = {'dos_header': self.perform_mapping( self.root_entry.DOS_HEADER.dump_dict(), IMAGE_DOS_HEADER_MAPPINGS), 'file_header': self.perform_mapping( self.root_entry.FILE_HEADER.dump_dict(), IMAGE_FILE_HEADER_MAPPINGS), 'optional_header':...
The function constructs a dictionary representing a PE file's metadata, including headers, sections, imports, exports, and resources. It checks for specific PE directories and parses them into the dictionary if present, returning the structured data for further analysis or processing.
def handle_pe_object(self): pe_dictionary = {'xsi:type': 'WindowsExecutableFileObjectType', 'headers': self.parse_headers(), 'sections': self.parse_sections()} self.load_data_directories() if hasattr(self.root_entry, 'DIRECTORY_ENTRY_IMPORT'): pe_dictionary[...
def handle_input_file(self): try: self.root_entry = pefile.PE(self.infile, fast_load=True) except pefile.PEFormatError: return None def handle_file_object(self): file_dictionary = {'type': 'FileObjectType', 'file_name': os.path.basename(self.infile), ...
The main task of the code is to process a PE file entry by handling input files, validating the entry, and generating a dictionary containing file data, PE object details, and calculated hashes. If the entry is invalid, it raises a TypeError. The method first processes the input file, checks if the root entry exists, a...
def process_entry(self): self.handle_input_file() if self.root_entry: self.entry_dict['file'] = self.handle_file_object() self.entry_dict['pe'] = self.handle_pe_object() self.entry_dict['hashes'] = self.calculate_hashes() else: raise TypeError('Er...
def create_malware_instance(self, file_data, file_hashes): """Create a base Malware Instance""" malwareInstance = {"type": "malware-instance", "id": "malware-instance--" + str(uuid.uuid4())} file_obj_id, file_obj = self.create_file_obj(file_data) # Add the hashes for the Malware Instanc...
This code generates MAEC (Malware Analysis Exchange Format) data by parsing a PE file with pefile, creating a structured malware instance with UUID identifiers, adding analysis metadata (tool refs, automated static analysis details), and extracting file header information. It organizes results into a package with obser...
def generate_maec(self): entry_dict = self.pefile_parser.entry_dict self.package["id"] = "package--" + str(uuid.uuid4()) if "file" in entry_dict: self.primary_instance = self.create_malware_instance(entry_dict["file"], entry_dict["hashes"]) # Add cuckoo information ...
def get_dataset(self): series_count = len(self.active_series) series_names = [] o = defaultdict(lambda: [0] * series_count) for i, s in enumerate(self.active_series): series_names.append(s.name) for dt, value in s._get_data(**self.calculate_range()): ...
This code constructs a configuration dictionary for a chart, setting options like title, time-based x-axis, value y-axis, grid layout, and series data. It conditionally includes dataset based on `with_data`, and incorporates scrollable legend, tooltip, and toolbox settings for visualization rendering.
def build_options(self, with_data=True): return { "title": { "text": self.title, "left": "5%" }, "useUTC": True, "dataset": self.get_dataset() if with_data else None, "toolbox": self.get_value("toolbox"), "to...
def get_context_value(self, name, default=None): if name in self.context: return self.context[name] if default is not None: return default raise KeyError("context value {} not found".format(name)) def build_options(self, with_data=True): return { "titl...
The code returns a JSON response containing either reload options or dataset information based on the 'reload' flag. It checks the 'reload' context value, updates the output with build_options (if reload is True) or adds the dataset (if reload is False), then returns the structured data as a JSON response.
def data(self): r = self.get_context_value("reload", False) out = {"reload": r} if r: out.update(self.build_options(with_data=True)) else: out["dataset"] = self.get_dataset() return jsonify(out)
def print_start_program_text(): ''' Description: This function prints the entery text to the program. Inputs: None. Outputs: None. prints text. ''' print('\n\n') print('----------------------------------------\n') print('Cyclic redundancy check (CRC) rev...
The function `start_program` initializes the CRC reversing tool by printing startup text, prompting the user to select a program mode, and retrieving packets and CRC width from user input. It uses a logger for tracking and returns the collected packets and CRC width for further processing.
def start_program(logger): ''' Description: This function starts the run of the CRC reversing tool, collects the user data, and output the packets and the crc width of the crc we want to reverse. Inputs: logger - logger object. Outputs: packets - list - a list of packets....
def _ensure_read_header(self): if self.header: return flag = self.infile.read(1) assert flag == b'\xff' length = unpack("!H", self.infile.read(2))[0] self.header = (flag, length) def read(self, count): data = self.infile.read(count) self.bytes_read += ...
This function reads the next line from a data stream by parsing the line number and associated tokens, returning them as a formatted string. It ensures the header is read, checks for EOF, and validates data integrity using assertions. If the end of the program is reached, it verifies no extra data exists and returns No...
def next_line(self): self._ensure_read_header() pos = self.ptr_next_line - self.base_address #assert pos == self.bytes_read, (pos, self.bytes_read) #print(">>", pos, self.bytes_read) h = self.read(2) if not h or len(h) < 2: raise EOFError (self.ptr_nex...
def _extract_input_data(arguments: list[str], stdin: TextIO) -> tuple[list[str], str | None]: input_data: list[str] = [ _read_file_argument_content(arguments[idx + 1]) for idx, arg in enumerate(arguments) if (arg == "-f" or arg == "--filename") and idx + 1 < len(arguments) ] if len(input_data): ...
The main task of the code is to act as a kubectl extension for FLUIDOS, handling input data from stdin or files, detecting its format (MSPL/K8S), and routing it to appropriate handlers (on_mlps, on_k8s_w_intent). If no specific handler applies, it falls back to standard kubectl apply behavior via on_apply, ensuring com...
def fluidos_kubectl_extension(argv: list[str], stdin: TextIO, *, on_apply: Callable[[list[str], str | None], int] = _default_apply, on_mlps: Callable[..., int] = _behavior_not_defined, on_k8s_w_intent: Callable[..., int] = _behavior_not_defined) -> int: logger.info("Starting FLUIDOS kubectl extension") try: ...
def _decode(self, raw_message: Tuple[str, str, Optional[str], Optional[str]]) -> Union[SubscribeResponse, Telemetry]: if raw_message[0] == "gnmi": self.log.debug("In decode gnmi") self.log.debug(raw_message[1]) sub = SubscribeResponse() sub.ParseFromString(raw_mes...
The main task of the code is to decode and parse raw responses into a list of ParsedResponse objects. It iterates through `self.raw_responses`, decodes each response using `_decode`, and applies either `parse_gnmi` or `parse_ems` based on the encoding type (`gpb_encoding`). Errors during processing are logged with trac...
def decode_and_parse_raw_responses(self) -> List[ParsedResponse]: self.log.debug("In decode and parse") parsed_list: List[ParsedResponse] = [] try: for response in self.raw_responses: gpb_encoding = response[0] decoded_response = self._decode(response)...
def _data_from_host_to_device(self, images): print("data interaction from host to device") for i in range(self.input_node_size): self.input_info[i]['dims_info']['dims'] = list(images[i].shape) # copy images to device self._data_interaction(images, ACL_MEMCPY_HOST_TO_DEVICE) ...
The code processes input images by validating their type, transferring data to a device, generating 'in' and 'out' datasets, executing a forward pass, and returning processed data to the host. It handles numpy array lists, transfers data between host/device, and performs model inference.
def run(self, images): if isinstance(images, list) and len(images) > 0 and isinstance(images[0], np.ndarray): self._data_from_host_to_device(images) self._gen_dataset('in') self._gen_dataset("out") else: print('images not a known type') return ...
def line_comment(self, comment: str, aligned: bool = False): self.src.append(f"{(' ' * (self.cmd_padding+1)) if aligned else ''}; {comment}") def restore_end(self): self.extruder += self.printer.retract_amount self.gcode(f"G1 E{self.extruder:.5f} F{self.printer.retract_speed}", "restore extruder...
This function generates 3D printing G-code for a body by processing a list of paths. It sets speed, adjusts extrusion width (thicker first layer), and extrudes along each path segment. Comments mark path progression, and layer-based extrusion ensures proper first-layer adhesion.
def add_body(self, paths: list[Path]): self.line_comment("BEGIN body") self.restore_end() for i in range(len(paths)): self.line_comment(f'path {i+1} of {len(paths)}', aligned=True) self.move(paths[i].vertices[0]) self.set_speed(self.printer.default_speed) ...
def line_comment(self, comment: str, aligned: bool = False): self.src.append(f"{(' ' * (self.cmd_padding+1)) if aligned else ''}; {comment}") def retract_end(self): self.extruder -= self.printer.retract_amount self.gcode(f"G1 E{self.extruder:.5f} F{self.printer.retract_speed}", "retract extruder...
The main task of the code is to execute post-printing operations by retracting the extruder, moving to a safe position for print removal, disabling heaters and the fan, and deactivating motors. It adds comments to mark the epilogue section, ensuring the printer is prepared for shutdown or manual intervention after comp...
def add_epilogue(self): self.line_comment("BEGIN epilogue") self.retract_end() self.move([self.printer.bed_center[0], self.printer.max_y - 10, 25], "move for print removal") self.set_bed_temp(0) self.set_end_temp(0) self.set_fan(False) self.gcode("M84 X Y E", "dis...
def reset(self): self.src = [] self.extruder = 0.0 def add_prologue(self): self.line_comment("BEGIN prologue") self.gcode("M201 X500 Y500 Z100 E5000", "set max accelerations (mm/s^2))") self.gcode("M203 X500 Y500 Z10 E60", "set max feedrate (mm/s)") self.gcode("M204 P500 ...
The code generates a file by combining a prologue, body (from given paths), epilogue, and settings. If an output path is provided, it writes the concatenated source lines to that file; otherwise, it returns the generated content as a list.
def generate(self, paths: list[Path], out: Optional[str] = None): self.reset() self.add_prologue() self.add_body(paths) self.add_epilogue() self.add_settings() if out: with open(out, 'w+') as f: f.write('\n'.join(self.src)) return self...
def validate_transaction(self, wallet_utxos, t): # print("validate_transaction") try: # verify signature if not t.verify_signature(): raise Exception('invalid signature') if t.sender == t.receiver: raise Exception('sender must be different from recepient') if t.amount <= 0: raise Exception(...
This function creates a cryptocurrency transaction by selecting sufficient UTXOs from the sender's wallet, constructing a signed transaction with inputs/outputs, validating it, and broadcasting if valid. It ensures fund sufficiency, handles change outputs, and integrates with the blockchain network.
def create_transaction(self, sender_public, senderID, receiver_public, receiverID, amount): # print("create_transaction") sum = 0 inputs = [] global trans_time_start if (not trans_time_start): trans_time_start = time.gmtime(time.time()) try: if(self.wallet.balance() < amount): raise Exception(...
def create_new_block(self, valid_trans): if len(self.valid_chain.block_list) == 0: idx = 0 prevHash = 0 else: prevBlock = self.valid_chain.block_list[-1] idx = prevBlock.index + 1 prevHash = prevBlock.hash newBlock = block.Block(index = idx, previousHash = prevHash) newBlock.listOfTransactions ...
The code mines a block from valid transactions, validates it under a lock, updates the blockchain and UTXO state if valid, and broadcasts the block. It ensures thread safety, records mining time, and discards invalid blocks.
def init_mining(self, valid_trans, current_utxos): global lock, trans_time_end, block_time newBlock = self.create_new_block(valid_trans) tmp_utxos = copy.deepcopy(self.wallet.utxos_snapshot) if not self.block_REDO(newBlock, tmp_utxos): # print("Stopping mining, block already added") return self.mine_...
def block_REDO(self, block, utxos): for trans in block.listOfTransactions: if (self.validate_transaction(utxos, trans) != 'validated'): print("Failed Transaction: ") print('\t\tsender id: ' + str(trans.senderID) + ' \t\treceiver id: '+ str(trans.receiverID) + ' \t\tamount: '+ str(trans.amount)) return ...
The main task of the code is to process a received block by validating it, updating the wallet's UTXO state, managing pending/unreceived transactions, and resolving conflicts. It uses a lock for thread safety, updates validated transactions, and ensures consistency by removing processed transactions from pending lists ...
def receive_block(self, block): global lock, trans_time_end tmp_utxos = copy.deepcopy(self.wallet.utxos_snapshot) if self.block_REDO(block, tmp_utxos): lock.acquire() if self.validate_block(block): self.valid_chain.add_block(block) global block_time, cnt_blocks trans_time_end = time.gmtime...
def img_normaliser(max_range_value=1, max_range_scaling_factor=2, max_range_offset=-1): """Returns the normaliser function for the input data""" def _norm(data): return data / max_range_value * max_range_scaling_factor + max_range_offset return _norm def img_denormaliser(max_range_...
The code initializes a class by setting up constants, creating image normalizer and denormalizer functions, and loading data from the specified path. Its main task is to prepare data processing components and load dataset for further analysis or model training.
def __init__(self, data_path): self.constants = TnbcConstants() self.normaliser = self.img_normaliser() self.denormaliser = self.img_denormaliser() self.data = self.get_data(data_path)
def parse_sections(fn): with open(fn, "rb") as f: data_all = f.read() sections = {} data = bytes(data_all) while len(data): start_idx = data.index(sysex_header) end_idx = data.index(sysex_term) + 1 assert start_idx == 0 idm = data[start_idx + 4] section...
The main task of the code is to process a cartridge dump file by parsing its sections, extracting and interpolating user-defined wave tables, and saving the results along with a summary text file and a PDF plot. It creates an output directory, handles file overwrites, and logs errors if exceptions occur during processi...
def process_cart_dump(fn): out_dir = os.path.join(os.path.dirname(fn), os.path.basename(fn)[:-4] + " M", "") m_fn = os.path.join(out_dir, os.path.basename(fn)[:-4] + "__SINGLE_BANK_M") try: os.makedirs(out_dir) except FileExistsError as e: print(f"WARNING: Output directory '{e.filename}...
def _check_keydown_events(self,event): if event.key == pygame.K_d: self.ship.moving_right = True elif event.key == pygame.K_a: self.ship.moving_left = True elif event.key == pygame.K_q: self._close_game() elif event.key == pygame.K_SPACE: s...
The main task of the code is to handle user input events in a Pygame application. It checks for quit requests, keyboard key presses/releases, and mouse clicks. If the user closes the window, it exits the game. For key presses, it triggers `_check_keydown_events`; for releases, `_check_keyup_events`. When a mouse button...
def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(ev...
def _check_fleet_edges(self): for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """Respond to the impact of an alien to the ship""" self.explosion2_fx.play() if self.stats.ship...
This method updates alien movement by checking fleet edges, updating their positions, detecting collisions with the player's ship to trigger hit responses, and verifying if any aliens have reached the screen's bottom to handle game-over conditions.
def _update_aliens(self): self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() # Looks for aliens that have reach the end of the screen self._check_aliens_bottom()
def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(ev...
The code defines a game loop that continuously checks for events, updates game elements (ship, bullets, aliens) if the game is active, and renders the screen to create real-time gameplay.
def run_game(self): while True: self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_screen()
def set_up_wandb(wandb_config): """ Setup for 'weights and biases'. :param wandb_config: configuration to be used """ wandb.login(key=api_key.wandb_api_key) wandb.init(project="Oscillogram Classification", config=wandb_config) def prepare_data(train_data_path, val_data_path, test_data_path, ker...
The main task of the code is to train and evaluate a machine learning model using specified training, validation, and test datasets. It initializes a model based on hyperparameters, prepares data, trains the model, and evaluates its performance on test data. If the model is a Keras model, it logs training details with ...
def train_procedure(train_path, val_path, test_path, hyperparameter_config=run_config.hyperparameter_config): """ Initiates the training and evaluation procedures. :param train_path: path to training data :param val_path: path to validation data :param test_path: path to test data :param hyperp...
def print_menu(): print("Enter your Choice ") print("1 to Add Employee") print("2 to Add Office ") print("3 to Fire Employee") print("4 to Display All Employees") print("5 to Display All Offices") print("6 to Display Specific Employee") print("q to Exit") def new_employee(): # if(ch...
The code defines a menu-driven Employee Management System that displays options for adding/deleting employees/offices, viewing all records, or specific details. It processes user input, executes corresponding functions, and loops until 'q' is entered, clearing the screen after each action.
def menu(): print("Welcome to Employee Management System") print_menu() # Taking choice from user ch = input("Enter your Choice: ") while(ch != 'q'): os.system('cls') if(ch == '1'): new_employee() elif(ch == '2'): new_office() elif(ch == '3'):...
def import_data(test_X_file_path): test_X = np.genfromtxt(test_X_file_path, delimiter = ',', dtype = np.float64, skip_header = 1) return test_X def predict_target_values(test_X): train_X = np.genfromtxt("train_X_knn.csv", delimiter = ',', dtype = np.float64, skip_header = 1) train_Y = np.genfromtxt("tra...
The code's main task is to predict target values from a test dataset. It loads test data from the given file path, uses a model (implied by the function name) to generate predictions, and saves the predicted values into a CSV file named "predicted_test_Y_knn.csv". The process involves data import, prediction execution,...
def predict(test_X_file_path): test_X = import_data(test_X_file_path) pred_Y = predict_target_values(test_X) write_to_csv_file(pred_Y, "predicted_test_Y_knn.csv")
def check_rationale_lengths(preds): bad = [] for pred in preds: claim_id = pred.claim_id predictions = pred.predictions for doc_key, prediction in predictions.items(): n_rationales = len(prediction.rationale) if n_rationales > MAX_ABSTRACT_SENTS: t...
The code computes evaluation metrics for a prediction dataset by comparing predicted claims against gold-standard claims. It uses Counters to tally abstract and sentence-level predictions, updates these counts with prediction-gold comparisons, and calculates F1 scores for four task-specific metrics: sentence selection,...
def compute_metrics(preds): """ Compute pipeline metrics based on dataset of predictions. """ counts_abstract = Counter() counts_sentence = Counter() check_rationale_lengths(preds) for pred in preds: gold = preds.gold.get_claim(pred.claim_id) counts_abstract = update_counts...
def get_model_by_path(path: str) -> IrisNet: """Loads and returns the specified model""" model = IrisNet() try: model.load_state_dict(torch.load(path)) model.eval() logging.info(f'Path of the model {path}') return model except Exception as e: logging.error(f'An er...
The main task of the code is to perform inference using a pre-trained model. It configures logging, parses arguments, loads the latest model, retrieves and processes input data, runs predictions, and stores the results. The workflow includes data loading, model inference, and result output with logging for tracking.
def main(): """Main function""" configure_logging() args = parser.parse_args() model = get_model_by_path(get_latest_model_path()) infer_file = args.infer_file infer_data = get_inference_data(os.path.join(DATA_DIR, infer_file)) infer_data_loader = process_data(infer_data) results = predi...
def top_k(logits, thres = 0.9): k = math.ceil((1 - thres) * logits.shape[-1]) val, ind = torch.topk(logits, k) probs = torch.full_like(logits, float('-inf')) probs.scatter_(-1, ind, val) return probs def gumbel_sample(t, temperature = 1., dim = -1): return ((t / max(temperature, 1e-10)) + gumbel...
This function performs speculative decoding using a main model and a smaller "prophet" model. It generates tokens with the prophet model, verifies them with the main model, and accepts/rejects predictions based on probability thresholds. The goal is efficient text generation by leveraging the smaller model's speed whil...
def speculative_decoding_with_prophet_model( net: ModelWithProphetWrapper, prompt: Tensor, seq_len: int, gamma: int = 5, temperature = 1., filter_thres = 0.9, lenience = 1., pad_id = 0 ): """ eq. algorithm 1 in paper https://arxiv.org/abs/2211.17192 """ # extract model, ...
def load_address_data(filename): """Load address data from CSV file to create a mapping of address to index.""" address_index_map = {} # Initialize empty library with open(filename) as csvfile: # Temporary refer to file as 'csvfile' within 'with' block address_reader = csv.reader(csvfile) # Creates ...
The code manages package delivery operations using a hash table and distance matrix. It loads address, package, and distance data, assigns packages to trucks, calculates delivery times, and simulates deliveries. The program provides a menu for users to check individual package status, view all package statuses at a spe...
def main(): """Main function to execute the program.""" package_hash_table = HashTable() # Create hash table instance address_index_map = load_address_data(CSV_DIRECTORY + 'Address.csv') # Load address data load_package_data(CSV_DIRECTORY + 'Package.csv', package_hash_table, address_index_map) # Load pa...
def generate_intermediate_images(category_lines,cols=5): """ Call save_incremental_shape_imgs for multiple shapes :param category_lines: dict containing shape name and vector instructions :param cols: number of columns in collage :return: list of paths of all shapes, list of categories """ t...
The main task of the code is to generate a GIF showcasing the construction process of various shapes by creating intermediate images, arranging them into collages with specified columns, and compiling them into a dynamic GIF. It uses input data containing shape names and vector instructions to produce visual sequences ...
def get_sample_gif(category_lines,cols=5): """ High level method to generate shape collages which will have construction state of all shapes :param category_lines: dict containing shape name and their vector instruction set :param cols: number of columns in collage :return: """ shapes_li...
def is_position_attacked(board: Board, x: int, y: int, by_white: bool) -> bool: color_filter = lambda data: board.fields[data[0]][data[1]].is_white == by_white pieces = tuple(filter(color_filter, board.get_all_pieces_positions())) for (x2, y2) in pieces: mask = create_piece_mask(board, x2, y2, False) if mask.fi...
This function determines if a king is in checkmate by checking if the king is under attack and cannot escape by moving, capturing an attacker, or blocking the attack. It verifies if the king's position is attacked, evaluates possible king moves, checks if attackers can be captured, and assesses if blocking pieces exist...
def is_checkmate(board: Board, is_white: bool) -> bool: king_x, king_y = board.get_pieces_positions(Piece.TYPE_KING, is_white)[0] # 1. is king in check if not is_position_attacked(board, king_x, king_y, not is_white): return False # 2. can the check be cancelled # a. can the king move out of the check po...
def en_passant_cleanup(board: Board, x: int, y: int, x2: int, y2: int) -> None: "Removes a pawn if it's captured en passant" if (x2, y2) == board.en_passant_position and board.fields[x][y].type == Piece.TYPE_PAWN: x3, y3 = board.moved_pieces[-1] board.fields[x3][y3].type = Piece.TYPE_NONE def try_promoting_pawn(...
This function determines if executing the specified move steps on a chess board results in a check or checkmate. It simulates the move, checks if the enemy king is under attack, and verifies if the result matches the target MetaTag (check/checkmate) by analyzing the board state after the move.
def would_result_in(board: Board, is_white: bool, move_steps: tuple, result: MetaTag) -> bool: "is_white = is check/mate done by white. Returns true if performing move_steps would result in result (parameter) MetaTag" assert result in (Meta.TAG_CHECK, Meta.TAG_CHECKMATE) r = False for x, y, x2, y2 in move_step...
def get_cow_predictions(image_path, cowModelPath, yolo=True): global device, CLASSES, YOLO_CLASSES if yolo: cow_model = create_cow_model_yolo(cowModelPath) imgs = [Image.open(image_path)] results = cow_model(imgs) out = results.xyxy[0] #print(out) #print(...
The main task of the code is to detect cows in an image using a YOLO model, determine relevant tags (e.g., numbers) to read based on cow positions and the `drinkingOnly` flag, and then recognize those tags using a digit model. It returns a dictionary mapping tag indexes to their predicted values and confidence scores.
def read_tags_in_image(image_path, cowModelPath, digitModelPath, drinkingOnly=True, yolo=True): classes, labels, bboxes, scores = get_cow_predictions(image_path, cowModelPath, yolo) toBeRead = determine_tags_to_be_read(classes, labels, bboxes, scores, drinkingOnly) opt = Options_single_image(image_path, dig...
def get_cow_predictions(image_path, cowModelPath, yolo=True): global device, CLASSES, YOLO_CLASSES if yolo: cow_model = create_cow_model_yolo(cowModelPath) imgs = [Image.open(image_path)] results = cow_model(imgs) out = results.xyxy[0] #print(out) #print(...
This function processes an image to detect cows using a YOLO model, identifies relevant tags (e.g., drinking-related), employs a digit recognition model to extract tag data, overlays bounding boxes and predictions on the image, and optionally saves the annotated result. It combines object detection, tag identification,...
def show_tags_in_img(image_path, cowModelPath, digitModelPath, drinkingOnly=True, yolo=True, saveFig = None): cow_image = cv2.imread(image_path) classes, labels, bboxes, scores = get_cow_predictions(image_path, cowModelPath, yolo) toBeRead = determine_tags_to_be_read(classes, labels, bboxes, scores, drinkin...
def get_cow_predictions(image_path, cowModelPath, yolo=True): global device, CLASSES, YOLO_CLASSES if yolo: cow_model = create_cow_model_yolo(cowModelPath) imgs = [Image.open(image_path)] results = cow_model(imgs) out = results.xyxy[0] #print(out) #print(...
This function processes an image to detect cows and specific tags (e.g., IDs) using two models: a cow detection model (YOLO-based) and a digit recognition model. It identifies relevant tags based on detection results, applies the digit model to extract tag data, and overlays bounding boxes with predictions on the origi...
def _show_tags_in_img(image_path, cowModelPath, digitModelPath, drinkingOnly=True, yolo=True): cow_image = cv2.imread(image_path) classes, labels, bboxes, scores = get_cow_predictions(image_path, cowModelPath, yolo) toBeRead = determine_tags_to_be_read(classes, labels, bboxes, scores, drinkingOnly) opt ...
def get_cow_predictions_video(capture, cowModelPath, yolo, skipFrames=16): if yolo: cow_model = create_cow_model_yolo(cowModelPath) else: cow_model = create_cow_model(cowModelPath) global device, CLASSES if (capture.isOpened() == False): print('Error while trying to read vid...
The code processes a video to detect and track tags (likely cow-related) using YOLO and digit models. It reads frames, predicts cow positions, determines relevant tags, and extracts digit predictions. Results are aggregated into time intervals with averaged confidence scores, returning a dictionary mapping tags to thei...
def read_tags_in_video(video_path, cowModelPath, digitModelPath, drinkingOnly=True, yolo=True, skipFrames=16, drinkingThresh=2): cap = cv2.VideoCapture(video_path) fps = cap.get(cv2.CAP_PROP_FPS) mod_time = os.path.getmtime(video_path) outcome = dict() largeToBeRead = dict() for batch in ge...
def get_cow_predictions_video(capture, cowModelPath, yolo, skipFrames=16): if yolo: cow_model = create_cow_model_yolo(cowModelPath) else: cow_model = create_cow_model(cowModelPath) global device, CLASSES if (capture.isOpened() == False): print('Error while trying to read vid...
This function processes a video to detect and analyze specific tags (e.g., animal behaviors or text) using machine learning models. It extracts frames, identifies relevant tags, calculates confidence scores, and compiles results into a structured DataFrame with timestamps, confidence metrics, and date ranges for each d...
def read_tags_in_video_to_df(video_path, cowModelPath, digitModelPath, drinkingOnly=True, yolo=True, skipFrames=16, drinkingThresh=2): cap = cv2.VideoCapture(video_path) fps = cap.get(cv2.CAP_PROP_FPS) mod_time = os.path.getmtime(video_path) outcome = dict() largeToBeRead = dict() for batch...
def get_cow_predictions_dir(dir_path, cowModelPath, yolo): outcomes = dict() global device, CLASSES, YOLO_CLASSES l = os.listdir(dir_path) l = list(filter(lambda x: "jpg" in x or "png" in x or "jpeg" in x, l)) if yolo: cow_model = create_cow_model_yolo(cowModelPath) else: ...
This function processes images in a directory to detect cow-related predictions and extract specific tags using YOLO and digit recognition models. It organizes results by image, mapping detected tags to their predicted values and confidence scores, primarily focusing on drinking-related tags if specified.
def read_tags_in_dir(dir_path, cowModelPath, digitModelPath, drinkingOnly=True, yolo=True): outcomes = get_cow_predictions_dir(dir_path, cowModelPath, yolo) toBeReadDict = dict() for img_key in outcomes: toBeReadDict[img_key] = determine_tags_to_be_read(outcomes[img_key][0], outcomes[img_key][1], ou...
def get_cow_predictions_dir(dir_path, cowModelPath, yolo): outcomes = dict() global device, CLASSES, YOLO_CLASSES l = os.listdir(dir_path) l = list(filter(lambda x: "jpg" in x or "png" in x or "jpeg" in x, l)) if yolo: cow_model = create_cow_model_yolo(cowModelPath) else: ...
This function processes images in a directory to extract and compile tag-related data into a structured DataFrame. It uses cow and digit detection models to identify tags, determines relevant tags based on parameters like 'drinkingOnly', and aggregates predicted text, confidence scores, and bounding box coordinates. Th...
def read_tags_in_dir_to_df(dir_path, cowModelPath, digitModelPath, drinkingOnly=True, yolo=True): outcomes = get_cow_predictions_dir(dir_path, cowModelPath, yolo) toBeReadDict = dict() for img_key in outcomes: toBeReadDict[img_key] = determine_tags_to_be_read(outcomes[img_key][0], outcomes[img_key][...
def load_data(database_filepath): engine = create_engine('sqlite:///'+database_filepath) df = pd.read_sql_table('messages', engine) X = df.loc[:,"message"] Y = df.iloc[:,4:40] return (X,Y,list(Y.columns)) def build_model(): ''' Pipeline with FeatureUnion that feeds the output of TfidfTr...
The main task of the code is to train a classifier model using disaster messages data from a database, evaluate its performance, and save the trained model to a specified file. It loads data, splits it into training/test sets, builds a model, trains it, evaluates accuracy, and persists the model for later use.
def main(): if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) ...
def parser(self, input, isRoot): left = "" for i in range(1, len(input)): if input[i] == '>': break left += input[i] if isRoot: self.root = left index = 1 for index in range(1, len(input) - 1): if input[index] == '-'...
This code processes a context-free grammar by reading input lines, parsing them, removing lambda (ε) productions, unit productions, and simplifying rules with more than two variables. It then checks if a given string is accepted by the grammar.
def callGrammarInitialize(self): lineNumber = int(input()) for i in range(lineNumber): self.parser(input(), i==0) self.removeLambdaProduction() self.removeUnitProductions() self.simplifyMoreThanTwoVariables() self.reshte=input() print(self.Acceptance()...
def get_model(self): if not self.model: raise Exception("Model not implemented") return self.model def get_sequences_from_text(self, texts: List[str]): tokenizer = self.get_tokenizer() sequences = tokenizer.texts_to_sequences(texts) return sequences def get_input_from...
The main task of the code is to process input text through a machine learning model to generate labeled predictions. It converts the query into model-compatible input, executes predictions, labels results, and optionally includes the top prediction or encodes outputs into JSON format for structured return.
def predict_text(self, query:str, include_top=True, encode_to_json= True): model = self.get_model() sequences = self.get_sequences_from_text([query]) X_input = self.get_input_from_sequences(sequences) preds = model.predict(X_input)[0] labeled_preds = [self.get_label_pred(i,x) for...
def initiate_env(): """load environment """ absolete_path = os.path.abspath(__file__) file_dir = os.path.dirname(absolete_path) env_path = os.path.join(file_dir, '..', '..', 'environment', ".env") load_dotenv(verbose=True, dotenv_path=env_path, override=True) def validate_env(): env = os.get...
The main task of the code is to initialize and validate the environment, attach configuration settings, log the detected environment, and return the settings. It calls `initiate_env()` and `validate_env()` to prepare the environment, retrieves settings via `attach_settings()`, logs environment details, and finally retu...
def load_settings(): initiate_env() env = validate_env() settings = attach_settings() logging.info( f"-----------------Environment Detected: {env}-----------------------") return settings
def menu_game(): print(Fore.GREEN + Style.BRIGHT + "\nSTARTING GAME" + Fore.RESET) print(Style.RESET_ALL) username = input(Fore.BLUE + Style.BRIGHT + "> Enter username: " + Style.RESET_ALL) role = menu_role() element_name = role['element'] print(Fore.MAGENTA + Style.BRIGHT + f">> {username} sel...
The main task of the code is to display a styled menu with numbered options using PrettyTable, handle user input selection, and route to corresponding functions (e.g., game start, role/element/skill info, help, exit) via a match-case structure, while enforcing input validation and maintaining a clean interface with ANS...
def main_menu(): print(Fore.RED + Style.BRIGHT + "\nMAIN MENU" + Fore.RESET) menu_table = prettytable.PrettyTable() menu_table.add_column("Options", ["1", "2", "3", "4", "5", "6"]) menu_table.add_column("Actions", ["Start game", "Role Info", "Element Info", "Skill Info", "Help", "Exit"]) menu_table....
def calc_attack(base_atk, atk_pct, flat_atk): return base_atk * (1 + atk_pct) + flat_atk def total_dmg_bonus(dmg_types, attributes): sum = 0 for type in dmg_types: sum += attributes.dmg_bonus.get(type, 0) if DmgTag.ALL not in dmg_types: sum += attributes.dmg_bonus.get(DmgTag.ALL, 0) ...
The function calculates outgoing damage by determining attack stats, applying damage bonuses, computing critical damage, and finalizing reaction-based damage against an enemy.
def outgoing_damage(attributes, atk_scaling, dmg_types, enemy): atk = calc_attack(attributes.base_atk, attributes.atk_pct, attributes.flat_atk) dmg_bonus = total_dmg_bonus(dmg_types, attributes) crit_damage = base_damage(atk, atk_scaling, dmg_bonus) * crit_multiplier(attributes.crit_rate, attributes.crit_dm...
def get_vocab(descript_frame, max_df, use_idf): """Gets the vocab labels to be used as inferred keywords. Args: Dataframe with column name (string) to parse vocab from. Max_df (float): max document frequency for sklearn's vectorizer, filters out common words. Use_idf (boolean): Use tf-i...
The code's main task is to generate course keywords using logistic regression on user vector data and course descriptions. It loads user vectors and course info, builds a vocabulary, converts text to bag-of-words, trains a logistic regression model, predicts probabilities, extracts keywords, processes results, and save...
def main(): timebf = time.time() print("[INFO] Loading data...") vec_df = pd.read_csv(vectorfile, sep = '\t') # Vector space representation of each user, all numeric descript_df = pd.read_csv(infofile, sep = '\t') # Course information print("[INFO] Getting vocab...") vocab = get_vocab(descr...
def perform_whatsapp_login(driver): driver.get("https://web.whatsapp.com") input("Press ENTER after logging into WhatsApp Web, and your chats are visible.") time.sleep(10) def perform_login(driver, username, password): driver.get("https://my.gumtree.com/login") username_field = WebDriverWait(drive...
The code automates sending personalized WhatsApp messages to ads by scraping links from a website, using credentials from a config file. It initializes a Chrome browser, logs into WhatsApp and a target site, extracts ad details, checks if ads are already processed, sends messages via WhatsApp, and logs results in CSV f...
def main(): with open("config.json", "r") as file: config = json.load(file) # Extract configuration values username = config["email"] password = config["password"] base_url = config["base_url"] message_template = config["message_template"] chrome_options = webdriver.ChromeOptions()...
def initialize_globs(): global documents, docid_counter, the_index '''Map document titles to document ids''' documents = {} '''A running counter for assigning numerical IDs to documents''' docid_counter = 1 '''The document-term frequencies''' the_index = dict() def add_document(doc): '''...
The code processes text documents from multiple folders, calculates similarity scores between consecutive documents using a result matrix, and writes the folder identifier, document year, length, and similarity score into a CSV file. It handles cases with single or multiple documents, ensuring consecutive years are che...
def result(): with open('../shared/BaseFileResultcsv.csv', 'w') as csv_File: writer = csv.writer(csv_File) writer.writerow(["gvkey", "fyear", "length", "Similarity"]) row = [] for folder in glob.glob('../shared/renamed_files/*/'): initialize_globs() dyears = [...
def jid_to_username(jid): return jid.split('@')[0][0:-4] def print_current_menu(self): message = "At menu " if len(self.curr_directory) == 0: message += "top" else: for directory in self.curr_directory: message += directory + " > " message ...
This code manages user setup and menu navigation. In "in_creation" state, it confirms user setup by saving data to 'users.json' if input is "y", or terminates the session if "n". In "main_menu", it handles commands like 'current' (show menu), 'goback' (exit), or sub-menu navigation. Invalid inputs trigger error message...
def handle(self, parsed_message): if self.state == "in_creation": if parsed_message[0] == "y": with open('users.json', 'r') as userfile: json_users = json.load(userfile) json_users[self.from_jid] = { "group_jid": [self.g...
def check_win(self): cells=[] for line in self.renkBoard: for cell in line:cells.append(cell) a=cells.count("A") b=cells.count("B") if a==0: return "B" elif b==0: return "A" else: return "Continue" def ismore(self,x...
The main task of the code is to check if the game has a winner, identify cells to "bloom" based on the `ismore` condition, apply the bloom operation to those cells, and recursively update the board if any cells were bloomed. It handles game state transitions by printing the winner if the game ends, or continuing the up...
def update_board(self): if self.check_win()!="Continue": print(self.check_win(),"won") else: mores=[] for i,line in enumerate(self.board): for j,cell in enumerate(line): if self.ismore(j,i): mores.append((j,i...
def update_board(self): if self.check_win()!="Continue": print(self.check_win(),"won") else: mores=[] for i,line in enumerate(self.board): for j,cell in enumerate(line): if self.ismore(j,i): mores.append((j,i...
The main task of the code is to handle a player's move on a board game. It increments the board cell at coordinates (x,y), updates the player's turn marker on a separate color board, refreshes the visual board display, switches the current player's turn, updates the color representation, and logs the move coordinates a...
def make_move(self,x,y): self.board[y][x]+=1 self.renkBoard[y][x]=self.sira self.update_board() self.change_sira() self.update_renk() self.hamleler.append((x,y,self.sira))
def check_for_score(frame): if left(frame) and right(frame): return 'both' elif left(frame) or right(frame): return 'one' else: return 'neither' def maybe_label_last(self, clips, frame, vid_id): if len(clips) > 0: if clips[-1].label == None: clips[...
The main task of the code is to label video clips by detecting specific frame patterns (e.g., lights) and saving labeled segments to JSON files. It skips existing labels, processes frames in 10-frame intervals, identifies frames with detected scores, and stores clips when both lights are active. It jumps to blockout ti...
def label_video(self, vid_id): v= f'../precut/{vid_id}' print(v) if os.path.exists(f'../per_vid_labels/{vid_id.replace(".mp4", ".json")}'): print("Already have labels") else: cap = cv.VideoCapture(v) cap.set(cv.CAP_PROP_POS_FRAMES,1000) cli...
def readfile(fn): fd = open(fn,'r') r = fd.read() fd.close() return r def verify_primes(V, s, needtofactor): for n in sorted(s): if not n.is_prime() or n in V: continue needtofactor.add(n-1) if n == 2: V.add(n) continue for trybase in primes(2,10000): base = Integers(n)(tryba...
The code verifies the primality of numbers by iteratively factoring integers, updating a set of verified primes, and ensuring consistency. It creates a 'proof' directory, reads primes from a file, and checks each number against potential factors. If new factors are found, it updates the primes list and repeats until no...
def verify(): try: os.mkdir('proof') except OSError as e: if e.errno != EEXIST: raise try: s = set(map(Integer, readfile('primes').split())) except IOError as e: if e.errno != ENOENT: raise s = set() needtofactor = set() V = set() # distinct verified primes verify_primes(V, s, needt...
def auto_set_values(val): """ TODO: improve at the dataset level sets the bit-range to be the whole range of bits_to_corrupt, based on the precision of the value to corrupt :param val: The value to corrupt """ globals.FIRST_BIT = 0 if isinstance(val, np.float16): globals.LAST_BIT...
The function corrupts a given value (int or float) by modifying specific bits, using either `corrupt_int` or `corrupt_float_at_bits` based on the value's type. It checks the global `FLOAT_PRECISION` setting to determine if automatic handling is needed. After corruption, it logs the original and modified values along wi...
def corrupt_value_at_bits(val, chosen_bits: []): if globals.FLOAT_PRECISION == "auto": auto_set_values(val) str_val_type = str(type(val)) if "int" in str_val_type: new_val, chosen_bits = corrupt_int(val) log_delta("Int", val, new_val, chosen_bits) else: new_val, chosen_bi...
def ingest_data(api: str) -> pd.DataFrame : """ Extract data from outside source Args: api (str): _description_ Returns: pd.DataFrame: _description_ """ data = requests.get(api) df = pd.DataFrame(data.json()) return df def transfrom_data(df: pd.DataFrame, source_data: s...
The code defines a pipeline function that ingests data from a source using an API, transforms the ingested data, and loads the transformed data into a warehouse. It logs progress with print statements, indicating an ETL (Extract, Transform, Load) workflow for data processing and storage.
def pipeline(api: str, src: str) : ##### ingest data print(f"Ingest data from {src}") df = ingest_data(api) transform_df = transfrom_data(df, src) load_to_warehouse(transform_df) print("-------------------------")
def createAffinityWNLL(data, ms, ms_normal, sigmaFlag, labeled_index): ''' Computes WNLL Affinity matrix inputs: data: array of data featrues ms: neighbors number per node ms_normal: neighbor for the kernel std. sigmaFlag: flag...
The function implements semi-supervised learning (SSL) solutions for the Two Moons dataset by applying spectral clustering and Dirichlet-based methods. It computes affinity matrices (WNLL, SSL), derives eigenvectors, clusters unlabeled data, and evaluates performance using NMI and ACC. Results are visualized, showing l...
def TwoMoons_SSL_Solutions(X, y, option_index, ms, ms_normal, sigmaFlag, classes, mu1, labeled_index, model_path): ''' SSL solutions for 2 moons dataset inputs: X: array of data featrues y: array of data labels option_index: index of current la...