dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def set_env_ref(env_ref: EnvRef)->str:
'''Create a string environment reference for use in Conda commands.
The environment command segment has one of two forms:
- If env_ref is the name of an environment:
- *'--name <Environment Name>'*.
- If env_ref is the path to an environment:
... | The function retrieves Conda environment information, optionally saves it as JSON to a specified path, and returns the data as a dictionary. It accepts an environment reference or defaults to the base environment, executes a `conda info` command, and processes the output into structured data for further use. | def get_conda_info(env_ref: EnvRef = None, info_storage_path: Path = None)->dict:
'''Get information about the current Conda environment.
If a file path is provided, save the json info to that file.
Args:
env_ref (EnvRef): A reference to the Conda environment either by it's
name or by ... |
def set_env_ref(env_ref: EnvRef)->str:
'''Create a string environment reference for use in Conda commands.
The environment command segment has one of two forms:
- If env_ref is the name of an environment:
- *'--name <Environment Name>'*.
- If env_ref is the path to an environment:
... | The main task of the code is to remove an Anaconda environment referenced by name or path, execute the conda removal command, capture the JSON-formatted log output, and return it as a dictionary. It constructs a command chain to deactivate the environment and remove it, handling errors with custom messages, then parses... | def remove_environment(env_ref: EnvRef)->Dict[str,str]:
'''Remove an Anaconda environment
Args:
env_ref (EnvRef): A reference to the Conda environment either by it's
name or by the path to the environment.
Returns:
Dict[str,str]: Log output, as a dictionary of dictionaries, gen... |
def set_env_ref(env_ref: EnvRef)->str:
'''Create a string environment reference for use in Conda commands.
The environment command segment has one of two forms:
- If env_ref is the name of an environment:
- *'--name <Environment Name>'*.
- If env_ref is the path to an environment:
... | The main task of the code is to install specified pip packages into an Anaconda environment when they are not available in Conda channels. It activates the environment, iterates through the package list, executes pip install commands, captures detailed logs for each installation, and returns these logs as a dictionary ... | def pip_install_packages(env_ref: EnvRef, pip_package_list: List[str])->Dict[str,str]:
'''Use pip to install packages in an Anaconda environment
This is intended to be used for installing packages that that cannot be
found in one of the Anaconda channels.
Args:
env_ref (EnvRef): A reference to... |
def main_argparse(assigned_args = None):
# type: (List)
"""
Parse and execute the call from command-line.
Args:
assigned_args: List of strings to parse. The default is taken from sys.argv.
Returns:
Namespace list of args
"""
import argparse, logging
parser = argparse... | The main task of the code is to control a user LED based on command-line arguments. It parses input arguments, checks the verbose level for output, and either sets the LED to a specified state or toggles it. Error handling returns 1 on failure. Finally, it prints the current LED state. The function returns 0 on success... | def main(assigned_args = None):
# type: (List)
cargs = main_argparse(assigned_args)
if cargs.verbose_level:
print(cargs)
if cargs.led_toggle == -1:
if cargs.verbose_level:
print("Switch User LED to %s"% led_state_txt(cargs.led_state))
... |
def load_model(CONFIG):
""" Load a model based on CONFIG.
Args:
CONFIG (dict): CONFIG
Raises:
ValueError: CONFIG['new_model_name'] needs to match.
Returns:
model: model ready for training.
"""
if CONFIG['load_new_model']:
model_name = CONFIG['new_model_name']
... | The main task of the code is to train a machine learning model using specified configurations, including data loading, model optimization, and loss calculation. It trains the model over multiple epochs, evaluates it on a test set each epoch, and saves the best-performing model based on test loss. The code also tracks a... | def train_model(CONFIG):
""" Train models based on parameters in CONFIG.
Args:
CONFIG (dict): model configuration dict
"""
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"Use device = {device}\n")
create_output_folder(CONFIG)
save_config(CONFIG)
... |
def open_page(self):
self.driver.get(self.login_url)
def login(self, user: User):
email_input = self.wait.until(EC.element_to_be_clickable(
(By.ID, self.login_username_input_id)))
email_input.clear()
email_input.send_keys(user.email)
login_first_continue_button = se... | The function `get_by_user` logs in a user, handles authentication steps (secret answer, OTP, six-digit code), and retrieves job matches if successful. It returns a list of jobs on success or an empty list if authentication fails or additional verification is required. | def get_by_user(self, user: User) -> list[Job]:
self.open_page()
self.login(user)
if self.is_logged():
print('Logged with success!')
return self.get_best_matches_jobs()
anwser_input = self.need_secret_anwser()
if anwser_input:
print('Need sec... |
def render(self):
board_state = []
for i, piece in enumerate(self.board.state):
if piece == self.board.EMPTY:
board_state.append(str(i + 1))
else:
board_state.append(piece)
print("\n%s %s %s" % (board_state[0], board_state[1], board_state[2]))
print("%s %s %s" % (board_state[3], board_state[4]... | The code's main task is to manage a game loop where it continuously renders the game state, takes player input coordinates, updates the board with the current player's marker, checks for game over conditions, and switches players until the game ends. | def play(self):
self.render()
while True:
coord = self.get_coordinates()
self.board.add_piece(coord, self.player.marker)
self.render()
if self.check_game_over():
break
time.sleep(.1)
self.switch_players() |
def parse_text_file(file_path):
fasta_paths = []
prosites = []
with open(file_path) as file:
#seperate each line
for i, line in enumerate(file):
# first 3 lines contains fasta paths
if (i < 3):
fasta_paths.append(str(line).strip())
co... | The main task of the code is to process input files by parsing paths and prosites, generate a figure, execute fastp on fastq data, and calculate/print the difference in read counts from the processed output. | def main(fastp_path, input_file_path):
fasta_paths, fastq_path, prosites = parse_text_file(input_file_path)
first_part_figure(fasta_paths, prosites)
output = run_fastq_on_fastp(fastp_path, fastq_path)
print(cal_reads_diff(output)) |
def is_terminated(self):
return self.current >= len(self.instructions)
def parse_instruction(self):
opcode, val = self.instructions[self.current].split()
return opcode, int(val)
def is_loop(self):
accumulator = self.accumulator
curr = self.current
exec_counts = self.execu... | The code attempts to fix an infinite loop by swapping 'jmp' and 'nop' instructions in a program. It iterates through instructions, replaces the current opcode with its counterpart, checks if the loop is resolved, and reverts if not. If a valid fix is found, it resets and exits; otherwise, it continues processing instru... | def fix_loop(self):
while not self.is_terminated():
opcode, val = self.parse_instruction()
subs = {'jmp': 'nop', 'nop': 'jmp'}
if opcode in subs:
old_inst = self.instructions[self.current]
new_inst = f'{subs[opcode]} {val:+d}'
... |
def init_menu(window, canvas):
menubar = tk.Menu(window)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Reset", command=lambda: reset(canvas))
filemenu.add_command(label="Exit", command=window.quit)
menubar.add_cascade(label="File", menu=filemenu)
window.config(menu=menubar... | Your return
The main task of the code is to initialize a Minesweeper-style game window using Tkinter. It creates a window with a specified size and title, sets up a canvas for drawing the game grid, initializes the game menu and grid layout, and binds mouse click events to handle player interactions. The `mainloop()`... | def init_window():
# Init window
window = tk.Tk()
window.minsize(600, 600)
window.title("Mine-Schweeps")
# title = tk.Label(
# text="Mine-schweeps",
# foreground="white",
# background="orange",
# )
# title.pack()
# May need to move canvas to the main func so ... |
def forward_pass(self, x):
# input - numpy array of dimensions [n0 x m], where m is the number of examples in the mini batch and
# n0 is the number of input attributes
zs = []
activation = x
activations = [x]
for i in range(len(self.weights) - 1):
z = np.dot(s... | This code trains a neural network using mini-batch gradient descent with exponential learning rate decay and optional L2 regularization. It processes training data in epochs, computes forward/backward passes, updates weights, calculates cross-entropy loss (with L2 penalty if enabled), and evaluates the network on valid... | def train(self, training_data, training_class, eval_data, eval_class, epochs, mini_batch_size,
learning_rate, decay_rate, enable_l2):
# training data - numpy array of dimensions [n0 x m], where m is the number of examples in the data and
# n0 is the number of input attributes
# tra... |
def buildMaxHeap(array):
firstParentIdx=(len(array)-1) // 2
for currentIdx in reversed(range(firstParentIdx+1)):
siftDown(currentIdx,len(array)-1,array)
def swap(i,j,array):
array[i],array[j]=array[j],array[i]
def siftDown(currentIdx,endIdx,heap):
childOneIdx=currentIdx*2+1
while childOneIdx... | The code implements the heap sort algorithm to sort an array in ascending order. It first builds a max heap, then repeatedly swaps the root (maximum element) with the last unsorted element and sifts down the new root to restore the heap property, gradually reducing the unsorted portion of the array. | def heapSort(array):
buildMaxHeap(array)
for endIdx in reversed(range(1,len(array))):
swap(0,endIdx,array)
siftDown(0,endIdx-1,array)
return array |
def process(fname, satPath, h5Path, saveName = "processed", size = 1024, gif = False, startFrame=0, endFrame="end", downSample = 2, filling=True, threshold = False, showSpeed=True):
"""
---------------------------------------------------------------------------
fname = filename of the .h5 label file (... | The `runthrough` function processes a set of test cases (TCs) based on a specified task. It handles four tasks:
1. **`iouspeed`**: Computes Intersection over Union (IoU) accuracy and speed arrays for each TC.
2. **`demonstrate`**: Visualizes AI model predictions on TC images using 3D selections.
3. **`generate`**... | def runthrough(tcs, h5Path, task=None):
"""
---------------------------------------------------------------------------
tcs = which TCs to be analysed, if int, run through the first int tcs.
If an iterable, then run through those in that iterable
h5path = where the labels are located
tas... |
def retrieveTCData(name,year,satPath):
"""
---------------------------------------------------------------------------
name = The TC's name
year = The year in which the TC began
satPath = location of satellite images
Finds the TC and retrieves relevant statistical data about its evolution
i... | The function `process_wind` retrieves tropical cyclone trajectory data and extracts corresponding wind field components (eastward and northward) from specified files. It iterates over time steps, using cyclone coordinates to fetch wind data chunks, appending results to lists. The task involves compiling wind data align... | def process_wind(tcName,tcYear,windPath):
tc = retrieveTCData(tcName, tcYear)
tcTimeIndex = 0
east = []
north = []
for filename,indicies in zip(*wind_files(tc,windPath)):
start = 0 if indicies[0] == False else indicies[0]
end = 2000 if indicies[1] == False else indicies[1]
fo... |
def get_full_tc_info(name,year,ibtracs_dest,sat_path):
"""
---------------------------------------------------------------------------
name = The TC's name
year = The year in which the TC began
ibtracs_dest = Filename of the IBTrACS dataset
sat_path = Where the satellite file... | This code processes satellite data for a tropical cyclone, generating an array of infrared temperature images with missing pixels set to 0. It filters data to include only times when sustained winds exceed 35 knots. If enabled, it creates a GIF visualizing the storm's satellite imagery. The output is a processed image ... | def process(name,year, sat_path, ibtracs_dest,
gif = False, save_name = "processed", verbose = False):
"""
---------------------------------------------------------------------------
name = name of the TC
year = year that the TC occurred
sat_path = Where the satellite f... |
def __AirlightEstimation(self, HazeImg):
if (len(HazeImg.shape) == 3):
for ch in range(len(HazeImg.shape)):
kernel = np.ones((self.airlightEstimation_windowSze, self.airlightEstimation_windowSze), np.uint8)
minImg = cv2.erode(HazeImg[:, :, ch], kernel)
... | This code removes haze from an input image by estimating airlight, calculating transmission maps, and applying dehazing algorithms. It returns the haze-corrected image and the computed transmission map for further analysis or visualization. | def remove_haze(self, HazeImg):
self.__AirlightEstimation(HazeImg)
self.__BoundCon(HazeImg)
self.__CalTransmission(HazeImg)
haze_corrected_img = self.__removeHaze(HazeImg)
HazeTransmissionMap = self._Transmission
return (haze_corrected_img, HazeTransmissionMap) |
def upload_to_cloudinary(api_secret,filename,resource_type = "image", extra_field = {}):
api_key = "871173851884581"
cloud_name = "daxxlcdlw"
body = {
"api_key": api_key,
}
#with open(filename, "rb") as f:
#file_info = f.read()
files ={
"file": open(filename,"rb")
}... | The code processes an uploaded image and metadata to generate an obituary using GPT, converts it to speech via Polly, uploads assets to Cloudinary, and stores details in DynamoDB. It retrieves secrets from SSM, decodes image data, triggers AI generation, and persists results in a database for a fictional obituary servi... | def lambda_handler(event,context):
client = boto3.client('ssm', region_name = "ca-central-1")
response = client.get_parameters_by_path(
Path='/the-last-show/',
Recursive=True,
WithDecryption=True,
)
params = {key["Name"]: key["Value"] for key in response["Parameters"]}
cl... |
def _check_current_state(self):
# define empty state as valid
if len(self.state) == 0:
return True
gidx = len(self.state) - 1
return self._check_state(gidx)
def _push_tile(self) -> bool:
"""Returns False only if we've solved the puzzle (all tiles already used)"""
... | This method performs a full search for solutions in a puzzle-like problem by iterating through possible states. It checks each state, pushes tiles when possible, and prints solutions when found. If no more states can be incremented, it backtracks by popping tiles. The loop continues until a solution is found (returning... | def run_check(self) -> bool:
"""Runs full search for solutions, returning True if one is found."""
while True:
# returns True for initial empty state list
self._states_checked += 1
if self._check_current_state():
# returns True if we have more tiles to... |
def add(self, request):
rid = str(uuid.uuid4())
self.__mainstore__[rid] = (request, float(time.time() * 1000))
for key, value in request.items():
hashkeys = self.__getHashCode__(key, value)
for hashkey in hashkeys:
if hashkey not in docstore.__lookupstore_... | This code processes a request string by parsing the operation type (add, get, delete) and associated JSON data, then executing the corresponding method. It splits the input into operation and parameters, validates the operation, and triggers the appropriate action, printing an error for invalid operations. | def request(self, request_string):
op = request_string[:request_string.index(' ')].strip()
request = json.loads(request_string[request_string.index(' '):].strip())
if op == 'add':
self.add(request)
elif op == 'get':
self.get(request)
elif op == 'delete':
... |
def make_screenshot() -> ndarray:
base = mss()
monitor = (0, 0, 1920, 1080)
screenshot = base.grab(monitor)
screenshot_array = array(screenshot)
return cvtColor(screenshot_array, IMREAD_COLOR)
def is_game_over(screenshot: ndarray) -> bool:
_, _, matched_percent = match_one(GAME_OVER_IMAGE, scre... | The main task of the code is to automate a game controller (likely for a dinosaur-themed game) by continuously checking the game state via screenshots. If the game is active, it detects if a jump is needed and triggers it using the controller. The loop terminates when the game ends. | def dino2() -> None:
game_controller = Controller()
while True:
window_screenshot = make_screenshot()
if is_game_over(window_screenshot):
break
if is_game_going(window_screenshot):
print('game_going')
if is_need_to_jump(window_screenshot):
... |
def run_with_options(options, args, extra_args=None, stdout=None, quiet=False):
if extra_args is None:
extra_args = []
app_provided_pg_conf = False;
# todo(121018500): remove when memory is under control
if not any('-Xmx' in arg for arg in extra_args):
if options.max_memory:
extra_args.append('-Xm... | The function `find_min_xmx` determines the minimum `-Xmx` (maximum heap size) value required for a program to execute successfully. It performs a binary search between a lower (`not_working`) and upper (`working`) memory limit, testing midpoints by running the program with `-Xmx<size>M`. Based on exit codes (success, t... | def find_min_xmx(options, args):
# Args will be destroyed
assert len(args) == 0
# If we can run in 128 MB then we are good (which we can for small examples
# or D8 on medium sized examples)
if options.find_min_xmx_min_memory:
not_working = options.find_min_xmx_min_memory
elif options.compiler == 'd8':
... |
def ParseOptions(argv):
result = optparse.OptionParser()
result.add_option('--compiler',
help='The compiler to use',
choices=COMPILERS)
result.add_option('--compiler-build',
help='Compiler build to use',
choices=COMPILER_BUILDS,
... | The main task of the code is to parse command-line options, validate their combinations (e.g., preventing conflicting flags like --expect-oom with --timeout), and execute corresponding functions (run_all, find_min_xmx, track_time_in_memory) based on the options. It adjusts exit codes for out-of-memory scenarios and ens... | def main(argv):
(options, args) = ParseOptions(argv)
if options.expect_oom and not options.max_memory:
raise Exception(
'You should only use --expect-oom if also specifying --max-memory')
if options.expect_oom and options.timeout:
raise Exception(
'You should not use --timeout when also sp... |
def showBoard(self):
print('\n'.join([''.join(['{:4}'.format(item[0])
for item in row]) for row in self.gameBoard]))
def fourByFour(self):
totalSquares = 0
for i in range(self.maxSize):
for j in range(self.maxSize):
if self.gameBoard[... | This code calculates a fitness score for a board configuration by combining three metrics: 4x4 blocks, wall fragments, and island size differences. It applies weights [3,4,1] to these metrics, sums them, and stores the result in self.fitness. Debugging prints board state and metric details if enabled. | def calculateFitness(self):
self.fitNum += 1
if debug:
print("______________NEW CALC____________")
self.showBoard()
fourByFourBlocks = self.fourByFour()
numFragments = self.wallFragments()
islandSizeDiff = self.islandSize()
rawFit = [fourByFourBloc... |
def resetBoard(self, dimension, coordinates, integers):
self.gameBoard = []
whiteCellsLeft = self.numWhiteCells
for i in range(dimension):
self.gameBoard.append([])
for j in range(dimension):
self.gameBoard[i].append([-1, -1])
for coordinate, integ... | The main task of the code is to initialize a board configuration by placing white cells according to given coordinates and integer values, ensuring valid placement through iterative resets and validation. It calculates the board's fitness after establishing a valid configuration, tracking island counts and constraints ... | def __init__(self, dimension, coordinates, integers, _boardID):
self.fitNum = 0
self.boardID = _boardID
self.numWhiteCells = sum(integers)
self.maxSize = dimension
self.allIslands = set()
self.islandsWithTooFew = set()
self.islandsWithTooMany = set()
self.... |
def findWhiteThatDoesntSplitIsland(self, i, j):
if self.getIslandSize(i, j) == 1:
return -1
visited = set()
queue = deque()
queue.append((i, j))
while queue:
random.shuffle(queue)
curr = queue.pop()
visited.add(curr)
nei... | The function balances island populations by swapping cells between islands with excess ("too many") and deficit ("too few") populations. It iteratively selects random cells from each group, attempts to find valid white/black cells for exchange, and swaps them if valid. If no valid swap is found, it reverts changes. The... | def surplusIslandSwap(self):
if len(self.islandsWithTooMany) == 0 or len(self.islandsWithTooFew) == 0:
return
numMaxIterations = 20
for i in range(numMaxIterations):
tooFew = random.sample(self.islandsWithTooFew, 1)
tooMany = random.sample(self.islandsWithTooM... |
def fourByFour(self):
totalSquares = 0
for i in range(self.maxSize):
for j in range(self.maxSize):
if self.gameBoard[i][j][0] == -1 and self.isSurrounded(i, j):
totalSquares += 1
return totalSquares/4
def neighbors(x, y, dimension):
retArr = []... | The function `swapBlackBlock` identifies and swaps black blocks (value 0) with adjacent white blocks (value -1) under specific conditions: the white block must be surrounded, not adjacent to more than one white block, and part of an "island with too many" white blocks. It randomly selects such a white block, replaces i... | def swapBlackBlock(self):
if self.fourByFour() == 0 or not self.islandsWithTooMany:
return
for i in range(self.maxSize):
for j in range(self.maxSize):
if self.gameBoard[i][j][0] == 0:
idNum = self.gameBoard[i][j][1]
neighbor... |
def neighbors(x, y, dimension):
retArr = []
if x-1 > -1:
retArr.append((x-1, y))
if x+1 < dimension:
retArr.append((x+1, y))
if y-1 > -1:
retArr.append((x, y-1))
if y+1 < dimension:
retArr.append((x, y+1))
return retArr
def notAdjMoreThanOneWhite(self, i, j, idNum... | The main task of the code is to repair disconnected black wall fragments in a game board by swapping a selected black wall segment with a white cell, ensuring the wall becomes connected and improving the board's fitness. It identifies isolated wall fragments, selects the smallest one probabilistically, finds a suitable... | def fixWall(self):
if self.wallFragments == 1:
return
blackWallSum = 0
wallCoordList = []
for i in range(self.maxSize):
for j in range(self.maxSize):
if self.gameBoard[i][j][0] == -1:
blackWallSum += 1
wallCo... |
def getWhitesFromIsland(self, x, y):
if self.gameBoard[x][y][0] <= 0:
self.showBoard()
raise KeyError("Provided loc ", x, y,
" is not a numbered cell - see above board")
queue = [(x, y)]
visited = set()
total = []
while queue:
... | The main task of the code is to regenerate an island by randomly selecting a starting cell, removing its white cells, and replacing them with new cells while adhering to adjacency constraints. It uses a BFS-like approach with random shuffling to explore neighboring cells, ensuring no more than one white cell is adjacen... | def regenIsland(self):
regen = random.sample(self.coor, 1)[0]
toRegen = self.getWhitesFromIsland(regen[0], regen[1])
whiteBudget = len(toRegen)
idNum = self.gameBoard[regen[0]][regen[1]][1]
for coo in toRegen:
self.gameBoard[coo[0]][coo[1]] = [-1, -1]
boardCop... |
def resetBoard(self, dimension, coordinates, integers):
self.gameBoard = []
whiteCellsLeft = self.numWhiteCells
for i in range(dimension):
self.gameBoard.append([])
for j in range(dimension):
self.gameBoard[i].append([-1, -1])
for coordinate, integ... | The main task of the code is to repeatedly reset and generate a valid board configuration using `resetBoard` and `createBoard` until a successful state is achieved, then compute the fitness of the final board configuration via `calculateFitness` to evaluate its effectiveness or validity in the context of the algorithm'... | def shake(self):
whiteCellsLeft = self.resetBoard(self.maxSize, self.coor, self.ints)
while True:
if self.createBoard(whiteCellsLeft):
break
self.resetBoard(self.maxSize, self.coor, self.ints)
self.calculateFitness() |
def has_marker(bitboards, square):
occupied = bitboards[0] | bitboards[1]
if occupied & (1<<square) == (1<<square):
return False
return True
def move(bitboards, move, turn):
#turn 0 = X's turn, turn 1 = O's turn
#Chekcs if there is a marker there already, then adds the move on
move = i... | The code evaluates all possible moves in a game by using the minimax algorithm with alpha-beta pruning to determine the best move. It iterates through each of the 9 positions, checks if a move is valid, simulates the move, calculates its value recursively, and tracks the time and computational nodes used. The move with... | def best_move(bitboards):
global nodes
global total_nodes
total_nodes += nodes
nodes = 0
best_val = -1000
best_move = -1
start_time = time.time()
for i in range(9):
if has_marker(bitboards, i):
cur_nodes = nodes
cur_time= time.time()
bitb... |
def best_move(board):
#accessing nodes variable in multiple function
global nodes
nodes = 0
best_val = -1000
best_move = (-1,-1)
start = time.time()
for b in range(3):
for row in range(3):
for column in range(3):
if board[b][row][column] == " ":
#current nodes, subtract nodes from current nodes
... | The function `make_move` handles a turn in a 3D tic-tac-toe game. If `computer_turn` is True, it selects the best move using `best_move`, updates the board with the computer's symbol, and prints the move. If False, it prompts the player to input their chosen board, converts the square coordinates, and places their "O" ... | def make_move(board, computer_turn):
while True:
if computer_turn:
move = best_move(board)
print_board(board)
print(move)
board[move[0]][move[1]][move[2]] = computer
break
elif not computer_turn:
b = int(input("Enter which board you are playing from, 1, 2, or 3"))
b -= 1
square = square_con... |
def has_marker(bitboards, square):
#returns false if there is a marker, return true if no marker
occupied = bitboards[0] | bitboards[1]
if occupied & (1<<square) == (1<<square):
return False
return True
def move(bitboards, move, turn):
#turn 0 = X's turn, turn 1 = O's turn
#Chekcs if th... | This function determines the optimal move for a player by evaluating all possible moves on a game board using the minimax algorithm with alpha-beta pruning. It iterates through valid positions, simulates each move, evaluates the resulting state recursively, and selects the move with the highest score. Global counters t... | def best_move(bitboards):
global nodes
global move_nodes
best_val = -1000
best_move = -1
for i in range(27):
if has_marker(bitboards, i):
move_nodes = 0
bitboards = move(bitboards, i, 0)
move_val = minimax(bitboards, 5, False, -1000000, 1000000)
... |
def mydbfunc():
mydb = mysql.connector.connect(
host = "phase-2-group2.cnleqhafy7wq.us-east-1.rds.amazonaws.com",
user = "admin",
password = "adminpass",
database = "university"
)
return mydb
def checkIfAdvisor(student_uid):
mydb = mydbfunc()
cursor = mydb.cursor(dictionary=True)
cursor.exe... | The main task of the code is to display or manage an advising hold form for a student based on their status. It checks user authentication, verifies hold status, retrieves student class schedules, and either renders the form with schedule data or processes form submissions to accept/delete holds. The function handles r... | def Advising_Hold_Form(student_uid):
mydb = mydbfunc()
cursor = mydb.cursor(dictionary=True)
if "user_type" not in session:
return redirect("/")
if checkIfAdvisor(student_uid) == "no":
print("not student or advisor")
return redirect("/")
if (advising_Hold_Status(student_uid) != "hold submit... |
def mydbfunc():
mydb = mysql.connector.connect(
host = "phase-2-group2.cnleqhafy7wq.us-east-1.rds.amazonaws.com",
user = "admin",
password = "adminpass",
database = "university"
)
return mydb
def advising_Hold_Status(Student_UID):
mydb = mydbfunc()
cursor = mydb.cursor(dictionary=True)
c... | The main task of the code is to manage a student's academic schedule in a portal, allowing them to view, modify (add/drop), and submit their course selections. It validates user access, retrieves valid semesters, fetches registered classes, organizes them into a time-based schedule, handles dynamic semester/year change... | def Student_Portal_Progress():
mydb = mydbfunc()
cursor = mydb.cursor(dictionary=True)
if "user_type" not in session:
return redirect("/")
if (session["user_type"] != "Student" or advising_Hold_Status(session["uid"]) != "hold in progress"):
return redirect("/")
#GET POSSIBLE SEMESTERS AND YEAR... |
def mydbfunc():
mydb = mysql.connector.connect(
host = "phase-2-group2.cnleqhafy7wq.us-east-1.rds.amazonaws.com",
user = "admin",
password = "adminpass",
database = "university"
)
return mydb
def advising_Hold_Status(Student_UID):
mydb = mydbfunc()
cursor = mydb.cursor(dictionary=True)
c... | This code manages a student portal by authenticating users, checking advising holds, displaying schedules, and handling class registration/drop requests. It fetches valid semesters, builds a time-based schedule from database queries, processes form submissions for class searches, semester changes, and course additions/... | def Student_Portal():
mydb = mydbfunc()
cursor = mydb.cursor(dictionary=True)
# doesn't allow access if not logged in as student
if "user_type" not in session:
return redirect("/")
if session["user_type"] != "Student":
print("user type")
return redirect("/")
ad_hold = advising_Hold_Status(sess... |
def get_object(self, queryset=None):
return self.request.user
def get_profile_form(self):
form_kwargs = {'instance': self.object.profile}
if self.request.method == 'POST':
form_kwargs['data'] = self.request.POST
form_kwargs['files'] = self.request.FILES
return se... | This code handles a POST request by retrieving an object, validating both user and profile forms, and either saving them if valid or returning invalid form errors. | def post(self, request, *args, **kwargs):
self.object = self.get_object()
user_form = self.get_form()
profile_form = self.get_profile_form()
if user_form.is_valid() and profile_form.is_valid():
return self.form_valid(user_form, profile_form)
return self.form_invalid(... |
def check_letter_syntax(n):
if n.find("**") != -1 or n.find("//") != -1:
raise ValueError("Invalid expression")
for elem in n:
if elem in digits or elem in operations or elem in ascii_letters or elem == " " or elem in high_priority_operations:
continue
else:
print... | The code implements a command-line calculator that processes user input to compute the sum of numbers. It handles commands like /help (displaying functionality) and /exit (terminating the program). It evaluates arithmetic expressions, manages variable assignments, and catches errors such as invalid syntax or unknown va... | def run():
while True:
n = input().lstrip(" +")
if n == "/exit":
break
elif n == "/help":
print("The program calculates the sum of numbers")
continue
elif n.startswith("/"):
print("Unknown command")
continue
elif len... |
def debug_print(*args, **kwargs):
if kwargs.get("verbose", None) is None:
kwargs["verbose"] = VERBOSE
if MANAGER_ID is None:
machines.debug_print("* cloudWatcher -", *args, **kwargs)
else:
machines.debug_print("* cloudWatcher > {} -".format(MANAGER_ID), *args, **kwargs)
def reset_by... | The code manages a manager's lifecycle by starting it, executing scripts with specified configurations, monitoring runtime duration, and restarting it if the elapsed time exceeds a threshold. It handles errors during restarts, resets the manager, removes associated machines, and recreates the manager with specified par... | def start_manager(manager, config_file="./config.ini", clouds=json.loads(cw_config["clouds"]), managers=int(cw_config["managers"]), delta=float(cw_config["delta"]), verbose=VERBOSE, very_verbose=VERY_VERBOSE):
start_time = time.time()
manager_name = manager.name
metadata = manager.metadata
while True:... |
def clean_clouds(clouds, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
global conns
connect_clouds(clouds, verbose=verbose)
for cloud in clouds:
conn = conns[cloud]
for sg,info in SECGROUPS_PARADIGMS.items():
... | The main task of the code is to configure cloud environments by creating security groups and keypairs based on predefined templates. It cleans existing resources, connects to specified clouds, and iterates through security group rules (with port ranges or protocols) and keypair configurations, applying them to each clo... | def setup_clouds(clouds, ips=0, *, verbose=VERBOSE):
clean_clouds(clouds, verbose=VERBOSE)
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
global conns
connect_clouds(clouds, verbose=verbose)
for cloud in clouds:
conn = conns[cloud]
... |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | This function retrieves servers from specified cloud providers, optionally filtered by metadata. It connects to clouds, processes metadata filters (applying tokens if provided), and checks each server's metadata against the criteria. If no filters are provided, all servers are returned. If filters exist, only servers m... | def get_servers(by_metadata={}, clouds=None, tokens={}, *, verbose=VERBOSE):
connect_clouds(clouds, verbose=verbose)
clouds = get_clouds(verbose=verbose) if clouds is None else ([clouds] if type(clouds) is str else clouds)
new_metadata = {}
for k, v in by_metadata.items():
new_metadata[apply_to... |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | The main task of the code is to locate and return a server object with the specified name in one or more cloud environments. It connects to the specified cloud(s), iterates through their servers, and returns the first matching server. If no match is found or the cloud is invalid, it returns None after logging a debug m... | def get_server(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
if cloud is None or cloud in get_clouds(verbose=verbose):
clouds = get_clouds(verbose=verbose) if cloud is None else [cloud]
for cloud in clouds:
for server in get_servers(clouds=cloud... |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | This function removes cloud machines either by matching metadata or via a 'sure' flag, using threads. It connects to clouds, filters servers based on metadata checks, and deletes matching servers concurrently, returning results. | def remove_all_machines(by_metadata={}, clouds=None, tokens={}, sleep=int(config["TUNING"]["wait_after_delete"]), max_it=int(config["TUNING"]["max_it_vm_delete"]), *, verbose=VERBOSE, sure = False):
connect_clouds(clouds, verbose=verbose)
clouds = get_clouds(verbose=verbose) if clouds is None else ([clouds] if ... |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | The main task of the code is to execute a given script on multiple virtual machines (servers) across specified cloud providers. It filters servers based on metadata criteria, applies a heuristic for selection, and runs the script in parallel threads, returning the results. The function handles server discovery, metadat... | def exec_script_machines(script, by_metadata={}, clouds=None, tokens={}, count=float("inf"), heuristic="enum", hide=True, timeout_cmd=int(config["TUNING"]["script_connect_timeout"]), max_script_attempts=int(config["TUNING"]["max_it_vm_execute_script"]), sleep_script=int(config["TUNING"]["wait_vm_execute_script"]), max_... |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | The function updates server metadata across specified cloud platforms by either applying general metadata to all servers or filtering servers based on specific metadata criteria, using multithreading for parallel execution. It processes input metadata and tokens to replace placeholders, checks server metadata against f... | def update_machines(metadata, by_metadata={}, clouds=None, tokens={}, sleep=int(config["TUNING"]["wait_after_update"]), max_it=int(config["TUNING"]["max_it_vm_update"]), *, verbose=VERBOSE, sure = False):
connect_clouds(clouds, verbose=verbose)
clouds = get_clouds(verbose=verbose) if clouds is None else ([cloud... |
def apply_tokens_list(script, tokens, server_name=None, cloud=None):
script = script.copy()
for i in range(len(script)):
script[i] = apply_tokens(script[i], tokens, server_name=server_name, cloud=cloud)
return script
def debug_print(*args, **kwargs):
verbose = kwargs.get("verbose", VERBOSE)
... | This function executes a script on a remote server via SSH using Fabric, handling retries, timeouts, and errors. It connects to the specified IP, runs each command in the script list, and returns a report with execution status, errors, and timing. If connection or command failures occur, it retries up to max_script_att... | def exec_script_by_ip(ip, script, user, key_filename, tokens={}, hide=True, timeout_cmd=int(config["TUNING"]["script_connect_timeout"]), max_script_attempts=int(config["TUNING"]["max_it_vm_execute_script"]), sleep_script=int(config["TUNING"]["wait_vm_execute_script"]), max_cmd_attempts=int(config["TUNING"]["max_it_vm_e... |
def debug_print(*args, **kwargs):
if kwargs.get("verbose", None) is None:
kwargs["verbose"] = VERBOSE
if MANAGER_ID is None:
machines.debug_print("* cloudWatcher -", *args, **kwargs)
else:
machines.debug_print("* cloudWatcher > {} -".format(MANAGER_ID), *args, **kwargs)
def reset_by... | The code runs a cloudWatcher manager to monitor virtual machines across specified clouds and types. It periodically launches probes on allocated machines, collects performance results, processes them, and ensures sufficient machine availability. The process iterates for a defined duration or maximum iterations, resetti... | def run(manager_id, clouds=json.loads(cw_config["clouds"]), delta=float(cw_config["delta"]), types=json.loads(cw_config["types"]), count=int(cw_config["count"]), max_it=int(cw_config["max_it"]), wait=int(cw_config["wait"]), wait_it=int(cw_config["wait_it"]), *, verbose=VERBOSE, very_verbose=VERY_VERBOSE):
debug_pr... |
def get_clouds(*, verbose=VERBOSE):
return conns.keys()
def get_server(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
if cloud is None or cloud in get_clouds(verbose=verbose):
clouds = get_clouds(verbose=verbose) if cloud is None else [cloud]
for cloud i... | This function identifies the cloud where a specified server exists by iterating through available clouds, checking each for the server's presence. If found, it returns the corresponding cloud; otherwise, it logs a debug message and returns None. | def get_server_cloud(server_name, *, verbose=VERBOSE):
for cloud in get_clouds(verbose=verbose):
if get_server(server_name, cloud, verbose=verbose):
return cloud
debug_print(f"Server {server_name} not found in any cloud", verbose=verbose)
return None |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | This function retrieves the server type from a server's metadata by connecting to a specified cloud, fetching the server details, and returning the 'type' field from its metadata. If the server isn't found or an error occurs, it returns None after logging the issue if verbose mode is enabled. | def get_server_type(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
server = get_server(server_name, cloud, verbose=verbose)
if server:
try:
return server.metadata["type"]
except Exception as e:
debug_print(f"Error getting server t... |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | The function retrieves the IP address of a specified server by connecting to the given cloud service, fetching the server details, and extracting its IP address. | def get_server_ip(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
server = get_server(server_name, cloud, verbose=verbose)
return get_ip(server) |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | The main task of the code is to remove a server from a specified cloud infrastructure. It connects to the cloud, releases unattached floating IPs, locates the server, and deletes it if found. The function handles cases where the cloud or server is not found, returning appropriate error reports. It uses parameters like ... | def remove_machine(server_name, cloud=None, sleep=int(config["TUNING"]["wait_after_delete"]), max_it=int(config["TUNING"]["max_it_vm_delete"]), *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
if cloud is None:
cloud = get_server_cloud(server_name, verbose=verbose)
if cloud is None:
... |
def get_server_metadata(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
server = get_server(server_name, cloud, verbose=verbose)
if server:
return server.metadata
else:
return {}
def debug_print(*args, **kwargs):
verbose = kwargs.get("verbose", VE... | The function `update_server` updates a server's metadata by iterating up to `max_it` times. It removes specified keys with null/empty values from the server's metadata, then applies the updated metadata. If successful, it returns a success report with timing and iteration details. On errors, it logs exceptions and retu... | def update_server(metadata, conn, server, sleep=int(config["TUNING"]["wait_after_update"]), max_it=int(config["TUNING"]["max_it_vm_update"]), *, verbose=VERBOSE):
errors = []
for i in range(max_it):
try:
old_metadata = get_server_metadata(server.name, verbose=verbose)
to_remove =... |
def get_server_ip(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
server = get_server(server_name, cloud, verbose=verbose)
return get_ip(server)
def debug_print(*args, **kwargs):
verbose = kwargs.get("verbose", VERBOSE)
try:
kwargs.pop("verbose")
exce... | The function `exec_script` executes a specified script on a remote server by retrieving the server's IP and type, resolving credentials and script content, combining token parameters, and delegating execution to `exec_script_by_ip` with error handling for missing configurations or failures. | def exec_script(server_name, script, tokens={}, hide=True, timeout_cmd=int(config["TUNING"]["script_connect_timeout"]), max_script_attempts=int(config["TUNING"]["max_it_vm_execute_script"]), sleep_script=int(config["TUNING"]["wait_vm_execute_script"]), max_cmd_attempts=int(config["TUNING"]["max_it_vm_execute_cmd"]), sl... |
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(... | The main task of the code is to display detailed status information of cloud resources (servers, security groups, keypairs, floating IPs) for specified clouds, filtering servers by metadata matches and summarizing floating IP allocation status. It prints structured output with headers, metadata checks, and resource cou... | def status_clouds(clouds, metadata={}, *, verbose=VERBOSE):
if clouds is not None:
connect_clouds(clouds, verbose=verbose)
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
conn = conns[cloud]
print(f"Cloud {cloud}")
print("="*len(... |
def _applyDefaults(self, data, override_dict=None):
if override_dict is None:
override_dict = {}
whichdefaults = data.get('defaults', 'global')
defaults = copy.deepcopy(self.data.get('defaults',
{}).get(whichdefaults, {}))
if defaults == {} a... | This code processes YAML data to expand and organize Jenkins job configurations, applying defaults, handling templates and groups, and ensuring uniqueness. It iterates through modules to modify data, expands jobs/views with metadata, processes project definitions by resolving job references, merging parameters, and exp... | def expandYaml(self, registry, jobs_glob=None):
changed = True
while changed:
changed = False
for module in registry.modules:
if hasattr(module, 'handle_data'):
if module.handle_data(self.data):
changed = True
f... |
def __getReddit():
return praw.Reddit(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
user_agent=USER_AGENT
)
def __getExistingPostIds(outputDir):
files = os.listdir(outputDir)
# I'm sure anyone knowledgeable on python hates this. I had some weird
# issues and frankly did... | This function fetches top Reddit posts from a random subreddit, filters out existing posts to avoid duplication, and either automatically selects the first post or lets the user choose one. It then retrieves video content from the selected post to generate a video script. | def getContent(outputDir, postOptionCount) -> VideoScript:
reddit = __getReddit()
existingPostIds = __getExistingPostIds(outputDir)
now = int(time.time())
autoSelect = postOptionCount == 0
posts = []
subreddit = random.choice(constants.question_reddits)
for submission in reddit.subreddit(s... |
def __getReddit():
return praw.Reddit(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
user_agent=USER_AGENT
)
def __getExistingPostIds(outputDir):
files = os.listdir(outputDir)
# I'm sure anyone knowledgeable on python hates this. I had some weird
# issues and frankly did... | The function retrieves a Reddit submission's content as a VideoScript, ensuring it hasn't been processed before. It checks if the submission ID exists in the output directory, fetches the submission if not found, and returns its content. | def getContentFromId(outputDir, submissionId) -> VideoScript:
reddit = __getReddit()
existingPostIds = __getExistingPostIds(outputDir)
if (submissionId in existingPostIds):
print("Video already exists!")
exit()
try:
submission = reddit.submission(submissionId)
except:
... |
def sim_SFRlc_F17(Nsamp, dth, zbinedges, SFRbinedges, SFRf_arr, Neff_scale = 1, model = 'Be13'):
'''
Simulate the light cone with F17 Sim fit luminosity function.
Inputs:
=======
Nsamp: number of lightcone to generate
dth: lightcone size dth^2[arcmin]
zbinedges: the redshift bin edges
... | The function generates lightcone simulations for star formation rate (SFR) and intensity maps using specified models (F17/Be13). It calculates true source counts (Ntrue) and predicted intensity distributions (Itrue_all/Itrue_targ) based on input parameters like redshift bins, angular resolution, and line-of-sight const... | def gen_lightcone(Nlc, dth, nu_binedges, z_coords_all,
I_coords_all, z_idx, line_use, line_targ,
muL = [], sigL = [], Neff_scale = 1, model = 'Be13'):
zbinedges = np.arange(0,10 + 0.01,0.01)
SFRbinedges = np.logspace(-3,1,100)
if model == 'F17':
SFRf_arr... |
def title_extract(f):
t = os.path.basename(f)
t = t.rsplit(".", 1)[0]
if re.search('rrg', t, re.IGNORECASE):
return t[re.search('rrg', t, re.IGNORECASE).start():].upper()
if re.search('dfly', t, re.IGNORECASE):
return t[re.search('dfly', t, re.IGNORECASE).start():].upper()
if re.sear... | The code generates line plots comparing stalls and hops data across different network topologies and routing algorithms, using log scale y-axis, and saves the results as a PDF. It processes multiple files, aggregates data, and visualizes trends with seaborn, adjusting text annotations for clarity. | def plot(keys, path, topos, rt_algs):
sns.set_theme(style="whitegrid")
sns.set(font_scale=2)
main_dir = Path(path)
lg = []
for topo in topos:
if topo == "fat_tree_3_48_2":
key = "*" + topo + ".out"
l = list(main_dir.glob(key))
if l != []:
... |
def plotL_selectNcfg(vt, ytitle, metricL, graph_grpL, plotH, dfrm_xformF):
"""
select-and-configure
"""
dataL = []
n_graph_grp = len(graph_grpL)
# if one graph group of length 1, orders is graph then metrics
do_graph_metric = (n_graph_grp == 1) and (len(graph_grpL[0]) == 1)
plotL_tit... | The function `plot_pkg` generates a plot figure by selecting and configuring data based on input parameters, creating subplots, adjusting the layout, and returning the resulting figure for visualization. | def plot_pkg(vt, graph_grpL, metricL, plotH, adjustH):
dataL = plotL_selectNcfg(vt, 'Socket', metricL, graph_grpL, plotH,
dfrm_pkg_xform(graph_grpL))
fig, axesL = plotL_do(dataL, plotH)
plotL_adj(fig, adjustH)
return fig |
def plotL_selectNcfg(vt, ytitle, metricL, graph_grpL, plotH, dfrm_xformF):
"""
select-and-configure
"""
dataL = []
n_graph_grp = len(graph_grpL)
# if one graph group of length 1, orders is graph then metrics
do_graph_metric = (n_graph_grp == 1) and (len(graph_grpL[0]) == 1)
plotL_tit... | The main task of the code is to generate and adjust a plot based on input configurations. It selects/configures data using `plotL_selectNcfg`, creates a figure/axes with `plotL_do`, applies adjustments via `plotL_adj`, and returns the final figure. | def plot_fn(vt, graph_grpL, functionH, metricL, plotH, adjustH):
dataL = plotL_selectNcfg(vt, 'Functions', metricL, graph_grpL, plotH,
dfrm_fn_xform(vt, functionH, graph_grpL))
fig, axesL = plotL_do(dataL, plotH)
plotL_adj(fig, adjustH)
return fig |
def flattenL(L):
#return [x for L_inner in L for x in L_inner ] # flatten
islist = map(lambda x: isinstance(x, list), L)
if (all(islist)):
L1 = functools.reduce(operator.concat, L) # flatten
return flattenL(L1)
else:
return L
def plot_pkg(vt, graph_grpL, metricL, plotH, adjustH)... | The main task of the code is to process and visualize performance metrics from Grappolo experiments on medium and large graphs using different memory modes. It constructs file paths for CSV data, reads and merges datasets via VTuneCSV, and generates plots for hardware events, hotspots, and function-level metrics. The c... | def main_grappolo(makeColL1, makeColL2):
path_pfx = './1grappolo/grappolo-'
#-------------------------------------------------------
# Grappolo, Medium graphs, 192 threads, *all* memory modes
#-------------------------------------------------------
# grappolo-<graph>-<type>-pkg.csv
# grappolo... |
def flattenL(L):
#return [x for L_inner in L for x in L_inner ] # flatten
islist = map(lambda x: isinstance(x, list), L)
if (all(islist)):
L1 = functools.reduce(operator.concat, L) # flatten
return flattenL(L1)
else:
return L
def plot_pkg(vt, graph_grpL, metricL, plotH, adjustH)... | The main task of the code is to analyze performance data from the Ripples application across multiple graph datasets and memory configurations (e.g., DRAM, Optane). It processes VTune CSV files, categorizes function calls, and generates visualizations comparing metrics like hardware events and memory operations. The co... | def main_ripples(makeColL1, makeColL2):
#-------------------------------------------------------
# Ripples, 64 threads, all memory modes
#-------------------------------------------------------
path_pfx = './2ripples/'
# <graph>.imm-<type>.T64-pkg.csv
# <graph>.imm-<type>.T64-fn.csv
grap... |
def makeCol_wallclock(n_threads):
def mk_fn(dfrm, col_src):
dfrm_dst = dfrm[col_src] / n_threads
return dfrm_dst
return mk_fn
def main_grappolo(makeColL1, makeColL2):
path_pfx = './1grappolo/grappolo-'
#-------------------------------------------------------
# Grappolo, M... | The main task of the code is to process performance metrics from hardware events, create derived columns (e.g., memory stall percentages, latency calculations), define grouped metrics for visualization, and generate plots using `main_grappolo` and `main_ripples` functions. It organizes metrics into categories like hots... | def main():
#seaborn.set_style({'font.family': 'serif'})
#seaborn.set(font='Times New Roman') # Cambria not available
#-------------------------------------------------------
#
#-------------------------------------------------------
# cf. 1perf-projects.gitlab/graph-reorder/py-reorder/relay... |
def create_parser():
parser = argparse.ArgumentParser(
prog='golumn',
description='View data based on OPTIONS. Use "-" as FILE to read from stdin.',
usage='%(prog)s [OPTIONS] FILE',
)
parser.add_argument(
'-t', '--title',
dest='title',
metavar='TITLE',
... | The main task of the code is to launch a GUI application (GolumnApp) for processing a file, either from command-line input or stdin. It parses arguments, creates a file if none is provided, initializes the app with the specified file path and title, and starts the application's main loop for interaction. | def main(args=None):
parser = create_parser()
args = parser.parse_args(args)
setup()
# when no file is passed in. Assume use is piping in the data.
if args.filename is None:
args.filename = new_hist_file()
with open(args.filename, 'w+') as dst:
dst.write(sys.stdin.read(... |
def read_data():
dataset = pd.read_csv('/home/mahi/Desktop/iit_bombay/FML/assignment2/dataset/train.csv')
inp = np.array(dataset.drop(columns=['label']))
opt = np.array(dataset['label'])
dev_dataset = pd.read_csv('/home/mahi/Desktop/iit_bombay/FML/assignment2/dataset/dev.csv')
inp_dev = np.array(dat... | The main task of the code is to train a neural network model with specified hyperparameters (e.g., 1 layer, 64 units, learning rate 0.001) on a dataset, apply L2 regularization (λ=5), and save test predictions to a CSV file. It loads training/development/test data, initializes the model and optimizer, trains for 50 epo... | def main():
max_epochs = 50
batch_size = 128
learning_rate = 0.001
num_layers = 1
num_units = 64
lamda = 5 # Regularization Parameter
train_input, train_target, dev_input, dev_target, test_input = read_data()
net = Net(num_layers, num_units)
optimizer = Optimizer(learning_rate)
... |
def get_save_data():
with open(os.path.join(get_save_directory(), file_name)) as file:
data = json.load(file)
if data:
return data
return False
def _save_guid():
guid = services.get_persistence_service().get_save_game_data_proto().guid
if guid:
return guid
else:
... | The function `get_region_id` retrieves a region ID from settings derived from saved data and a generated GUID. If settings are found, it returns the `region_id` value; otherwise, it defaults to `222656`.) | def get_region_id():
save_data = get_save_data()
save_guid = str(_save_guid())
settings = get_settings(save_guid, save_data)
if settings:
return settings['region_id']
else:
return 222656 |
def get_save_data():
with open(os.path.join(get_save_directory(), file_name)) as file:
data = json.load(file)
if data:
return data
return False
def _save_guid():
guid = services.get_persistence_service().get_save_game_data_proto().guid
if guid:
return guid
else:
... | The code extends the original function by retrieving settings using a generated GUID and save file, then returns the original result. | def load_settings(original, self, *args, **kwargs):
result = original(self, *args, **kwargs)
save_file = get_save_data()
save_guid = str(_save_guid())
settings = get_settings(save_guid, save_file)
return result |
def daclen(primes):
return [dac(primes[j])[1] for j in range(len(primes))]
def batchstart(batchsize):
B = len(batchsize)
return [sum(batchsize[:j]) for j in range(B)]
def batchstop(batchsize):
B = len(batchsize)
return [sum(batchsize[:j+1]) for j in range(B)] | The function computes the maximum value of `daclen(primes)` for each batch in `batchsize` by iterating over ranges defined by `batchstart` and `batchstop`, returning a list of these maxima for each batch. | def maxdaclen(primes,batchsize):
B = len(batchsize)
return [max(daclen(primes)[j]
for j in range(batchstart(batchsize)[b],
batchstop(batchsize)[b]))
for b in range(B)] |
def daclen(primes):
return [dac(primes[j])[1] for j in range(len(primes))]
def daccost(n):
return xDBL+xADD+n*xADD
def batchstart(batchsize):
B = len(batchsize)
return [sum(batchsize[:j]) for j in range(B)]
def batchstop(batchsize):
B = len(batchsize)
return [sum(batchsize[:j+1]) for j in range(B)] | The function `eachdac` calculates the sum of `daccost` values for a specific batch of prime numbers. It determines the range of indices for the given batch `b` using `batchstart` and `batchstop`, then iterates over the corresponding elements in `D` (derived from `daclen(primes)`), summing their individual `daccost` con... | def eachdac(primes,batchsize,b):
B = len(batchsize)
D = daclen(primes)
return sum(daccost(D[j])
for j in range(batchstart(batchsize)[b],
batchstop(batchsize)[b])) |
def div(primes):
return inv(primes)+M
def elligator(primes):
return S+M+M+M+S+M+M+sqrt(primes)
def maxdac(primes,batchsize,b):
B = len(batchsize)
M = maxdaclen(primes,batchsize)
return daccost(M[b])
def eachdac(primes,batchsize,b):
B = len(batchsize)
D = daclen(primes)
return sum(daccost(D[j])
... | The code calculates a cumulative value `mults` by summing contributions from multiple operations on primes and batch sizes. It initializes `mults` with results from `div(primes)`, scalar multiplications (e.g., `x['elligator']*elligator(primes)`), and iterates over batches to add terms from `maxdac`, `eachdac`, and `iso... | def mults(x,primes,batchsize):
B = len(batchsize)
mults = 0
mults += div(primes)
mults += x['elligator']*elligator(primes)
mults += x['clear2']*clear2
for b in range(B):
mults += x['maxdac',b]*maxdac(primes,batchsize,b)
mults += x['eachdac',b]*eachdac(primes,batchsize,b)
mults += x['isog',0,b]*i... |
def __entry_flow(self, X):
"""
Implementation of the entry flow part of the Xception model.
:param X:
:return:
"""
# first layer
X = Conv2D(filters=32, kernel_size=(3, 3), strides=(2, 2), padding='valid',
kernel_initializer=random_uniform)(X)
... | This code defines a neural network model with an entry flow, repeated middle flow, exit flow, and classification layers. It constructs a CNN for image classification, using Global Average Pooling, dense layers, and softmax activation to output class probabilities. The model is built using Keras functional API, with cus... | def __call__(self):
X_input = Input(shape=(self.input_shape[0], self.input_shape[1], 3))
# entry part
X = self.__entry_flow(X=X_input)
# middle part
for i in range(8):
X = self.__middle_flow(X=X)
# exit part
X = self.__exit_flow(X=X)
# cla... |
def find_keys(ciphertext, min_keysize, max_keysize):
hamming_dict = {}
for keysize in range(min_keysize, max_keysize):
n = 1
distances = []
# iterates through adjacent chunks of ciphertext, keysize chars apart
# (ex) ciphertext = abcdefghijk, keysize=2: ab|cd, cd|ef, ef|gh ... ... | The code decrypts a base64-encoded XOR-encrypted file by determining the key size, transposing ciphertext blocks, solving for the key via frequency analysis, and applying XOR decryption to recover the plaintext. | def main():
in_file = input('Please input your encoded XORd file (with extension): ')
fh = open(in_file, 'r')
decoded_ciphertext = base64.b64decode(fh.read().encode())
key_sizes = []
keysize = find_keys(decoded_ciphertext, 2, 20)[0][0]
chunks = break_txt(decoded_ciphertext, keysize)
t = tran... |
def compute_sf(s0, psi0, nodes):
# Convert from ECEF to ENU the entity position
enu_x, enu_y, enu_z = pm.ecef2enu(s0[0], s0[1], s0[2],
*lcpo[0:3])
# Compute the first clothoid for the entity
n_enu_x1, n_enu_y1, n_enu_z1 = pm.ecef2enu(nodes[0][0], nodes[0][1],
... | The code predicts potential collisions by evaluating motion primitives (stop/pass) for each scenario in `possible_collisions`. It calculates velocity/time ranges, generates collision trajectories, and selects the most likely collision-causing motion primitive based on jerk and acceleration constraints. The result inclu... | def predict_collision(possible_collisions):
# Container for the initial conditions for the motion primitives of the ego
# vehicle
ego_init = []
# Containers for the collision trajectories
coll_trajs = []
# For each possible collision
for (a_s0, a_v0, a_a0, a_psi0, a_nodes, a_speed_limit, s... |
def get_optimal_train_dataset(conn,
latitude,
longitude,
date,
property_type,
train_size_lb=10,
train_size_ub=20,
... | The function `predict_price` predicts house prices at a given location and date using regression models (RidgeCV, BayesianRidge, TweedieRegressor). It fetches a training dataset from a database, preprocesses it with OSM features, splits data for cross-validation, trains models, evaluates their performance (RMSE), and r... | def predict_price(latitude, longitude, date, property_type, conn,
train_size_lb=10, train_size_ub=20, train_box_width=0.03,
train_box_height=0.03, diff_lb=20, diff_ub=20, verbose=True):
""" Predict the house price for a property at location with
a given latitude-longitude... |
def get_optimal_train_dataset(conn,
latitude,
longitude,
date,
property_type,
train_size_lb=10,
train_size_ub=20,
... | This function predicts house prices for a given location and date using relaxed property type filters. It retrieves and preprocesses training data from a database, trains multiple regression models (RidgeCV, BayesianRidge, Tweedie), evaluates their performance (RMSE), and returns a DataFrame with model names, predicted... | def predict_price_relaxed_property(latitude, longitude, date, property_type, conn,
train_size_lb=10, train_size_ub=20, train_box_width=0.03,
train_box_height=0.03, diff_lb=20, diff_ub=20, verbose=True):
""" Predict the house price for a property ... |
def compute_minimum_distance_between_sensors(self):
sensors = self.map.sensors
for i in range(len(sensors)-1):
for j in range(i + 1, len(sensors)):
path = Path(self.searchAStar(self.map, sensors[i][0], sensors[i][1], sensors[j][0], sensors[j][1], self.screen))
... | The code implements an Ant Colony Optimization (ACO) algorithm to find the shortest path between sensors. It iteratively computes paths for multiple ants, updates pheromone levels by reducing them with a decay rate (rho), and tracks the best path found. After iterations, it returns the optimal path determined by minimi... | def run(self, rho=0.1, iterations=200):
self.compute_minimum_distance_between_sensors()
best_ant = -1
paths = self.minimum_distance_between_sensors
for k in range(iterations):
minim = numpy.inf
for _ in range(self.ant_count): #population of ants
an... |
def _iterate_batch_dims(self, ds):
return _iterate_through_dataset(ds, self.batch_dims)
def _iterate_input_dims(self, ds):
return _iterate_through_dataset(ds, self.input_dims, self.input_overlap)
def _drop_input_dims(ds, input_dims, suffix='_input'):
# remove input_dims coordinates from datasets, re... | This function generates batches from a dataset by iterating over batch dimensions, optionally preloading data, and either concatenating input dimensions into a new dimension or processing them separately. It returns a dictionary mapping indices to batches, enabling efficient data loading for a loader API, though noted ... | def _gen_batches(self) -> dict:
# in the future, we will want to do the batch generation lazily
# going the eager route for now is allowing me to fill out the loader api
# but it is likely to perform poorly.
batches = []
for ds_batch in self._iterate_batch_dims(self.ds):
... |
def fft(signal):
n = next_power_of_2(len(signal))
padded_signal = np.pad(signal, (0, n - len(signal)))
return fftshift(custom_FFT(padded_signal))
def custom_IFFT(X):
N = len(X)
X = [x.conjugate() for x in X]
x = custom_FFT(X)
x = [xi.conjugate() / N for xi in x]
return x
def fftshift(X):... | The code applies a low-pass filter to a signal by transforming it to the frequency domain using FFT, masking frequencies above the cutoff, and converting it back to the time domain with an inverse FFT. It retains low-frequency components while attenuating higher frequencies, effectively smoothing the signal. | def lowpass_filter(signal, cutoff_freq, sampling_rate):
spectrum = fft(signal)
frequencies = np.linspace(-sampling_rate / 2, sampling_rate / 2, len(spectrum))
filtered_spectrum = spectrum * (np.abs(frequencies) <= cutoff_freq)
return np.real(custom_IFFT(fftshift(filtered_spectrum))) |
def fft(signal):
n = next_power_of_2(len(signal))
padded_signal = np.pad(signal, (0, n - len(signal)))
return fftshift(custom_FFT(padded_signal))
def custom_IFFT(X):
N = len(X)
X = [x.conjugate() for x in X]
x = custom_FFT(X)
x = [xi.conjugate() / N for xi in x]
return x
def fftshift(X):... | The code applies a high-pass filter to a signal by transforming it to the frequency domain using FFT, zeroing out frequencies below the specified cutoff, and then converting it back to the time domain with an inverse FFT. | def highpass_filter(signal, cutoff_freq, sampling_rate):
spectrum = fft(signal)
frequencies = np.linspace(-sampling_rate / 2, sampling_rate / 2, len(spectrum))
filtered_spectrum = spectrum * (np.abs(frequencies) >= cutoff_freq)
return np.real(custom_IFFT(fftshift(filtered_spectrum))) |
def generate_signal(t, freqs):
signal = np.zeros_like(t)
for freq in freqs:
signal += np.sin(2 * np.pi * freq * t)
return signal
def lowpass_filter(signal, cutoff_freq, sampling_rate):
spectrum = fft(signal)
frequencies = np.linspace(-sampling_rate / 2, sampling_rate / 2, len(spectrum))
... | The code generates a multitone signal, applies lowpass and highpass filters, computes mean squared errors between original and filtered signals, and visualizes the original, filtered signals with their MSE values in a single plot saved as "signals.png" | def main():
signals_dir = "signals"
if not os.path.exists(signals_dir):
os.makedirs(signals_dir)
sampling_rate = 1000
duration = 1.0
t = np.linspace(0, duration, int(sampling_rate * duration), endpoint=False)
signal = generate_signal(t, [5, 10, 20, 30, 40])
lowpass_signal = lowpass... |
def decrypt_bsgs(C):
S = private_key * C[0]
M = C[1] - S
return bsgs_ecdlp(M)
def encrypt(M):
k = o.random()
K = k * g
C = (k * public_key) + (M * g)
return (K, C)
def add(elem1, elem2):
c11, c12 = elem1
c21, c22 = elem2
return (c11 + c21, c12 + c22) | The code tests the correctness and performance of encryption/decryption functions using the BSGS algorithm. It generates random numbers, encrypts them, decrypts via `decrypt_bsgs`, and verifies results against originals. It also tests encrypted addition, checking if decrypted sums match expected values. Time metrics (m... | def main():
times = []
tests = [[random.getrandbits(random.randint(16, 32))
for i in range(10)] for i in range(SAMPLE_NUMBER)]
for i in range(SAMPLE_NUMBER):
start = time.time()
for test_number, test in enumerate(tests[i]):
res = decrypt_bsgs(encrypt(test))
... |
def gatherLinks(self, link_elements):
list = []
for link in link_elements:
try:
href = link.find_element(
By.TAG_NAME, "a").get_attribute("href")
list.append(href)
except:
print("Unable to get link href!")
... | The code scrapes data from web pages using Selenium by either following links (if provided) or directly extracting elements based on specified class names. It handles dynamic interactions (clicks), extracts text/data, and appends results to a JSON file. Error handling ensures robustness, and the process repeats for eac... | def scrapData(self, link_detail_class, driver, scrap_class_names):
result = {}
with open('data.json', 'a') as f:
f.write('{ "data": [ ')
# Checking if there is a link to enter and gather information
if link_detail_class != "":
# Finding elements with link detail ... |
def goSiteLink(self, link, driver):
driver.set_window_size(1000, 800)
driver.get(link)
def ScrollSite(self, driver):
js = "window.scrollTo(0,document.body.scrollHeight)"
# Execute the scroll order by webdriver
driver.execute_script(js)
# Use while loop to keep scrolling... | The main task of the code is to navigate to a website link, scroll the page to load additional content, and scrape specified data elements using given class names. The function uses a browser driver to access the site, scrolls to trigger dynamic content loading, then extracts data based on provided CSS class names for ... | def seemoreScrollScrap(self, link_detail_class, site_link, driver, scrap_class_names):
self.goSiteLink(site_link, driver)
self.ScrollSite(driver)
self.scrapData(link_detail_class, driver, scrap_class_names) |
def goSiteLink(self, link, driver):
driver.set_window_size(1000, 800)
driver.get(link)
def ScrollSite(self, driver):
js = "window.scrollTo(0,document.body.scrollHeight)"
# Execute the scroll order by webdriver
driver.execute_script(js)
# Use while loop to keep scrolling... | The code's main task is to navigate to a website link, scroll the page to load additional content, and then scrape data using specified HTML class names. The method `seemoreScrollScrap` orchestrates this process by calling three functions: `goSiteLink` to access the site, `ScrollSite` to simulate scrolling, and `scrapD... | def seemoreScrollScrap(self, link_detail_class, site_link, driver, scrap_class_names):
self.goSiteLink(site_link, driver)
self.ScrollSite(driver)
self.scrapData(link_detail_class, driver, scrap_class_names) |
def get_ball_data(self):
"""Retrieves ball data."""
if self.ball_data is None:
ball_data = self.ball_helper(self.ball_df)
ball_data['FrameCount'] = self.df[self.df.columns[0]]
reordered_cols = [ball_data.columns[-1]] + list(ball_data.columns[:-1])
self.bal... | This function combines ball data with either home or away team data based on the specified 'team_type' parameter. It retrieves the corresponding team data, removes the 'FrameCount' column, and merges it with ball data using column-wise concatenation. If 'team_type' is invalid, it raises a ValueError. The result is a co... | def ball_team(self, team_type):
"""Combines ball data with team data based on the specified team type."""
team_type = team_type.lower()
ball_data = self.get_ball_data()
if team_type == 'home':
home_team = self.get_home_team()
home_team.drop(columns='FrameCount', i... |
def get_home_team(self):
"""Retrieves tactical data for the home team."""
if self.home_team_df is None:
self.home_team_df = self.get_team_data('1')
return self.home_team_df
def get_away_team(self):
"""Retrieves tactical data for the away team."""
if self.away_team_df ... | The function combines ball data with home and away team data by dropping the 'FrameCount' column from both teams and concatenating them column-wise into a single DataFrame. | def whole_field(self):
"""Combines ball data with both home and away team data."""
home_team = self.get_home_team()
away_team = self.get_away_team()
ball_data = self.get_ball_data()
home_team.drop(columns='FrameCount', inplace=True)
away_team.drop(columns='FrameCount', in... |
def GMCP_op(z, lam, gamma=3):
'''
z:vector of parameters
lam: tuning parameter of penalty term
gamma: extra tuning parameter. Default is 3.
'''
z_norm = torch.norm(z, p=2)
if (z_norm <= gamma*lam):
return gamma/(gamma-1) * GroupSoftThresh(z, lam)
else:
return z
def GSCAD_... | This function applies concave penalties (MCP, SCAD, LASSO) to a tensor `z` with adjustable lambda, using L2 inner penalty. It scales lambda by √(z.size(0)), selects the corresponding penalty operation, and raises errors for unsupported penalties. L1 inner penalty is not yet implemented. | def ConcaveSoftThresh(z, lam, outer_penalty, inner_penalty):
if inner_penalty == "l2":
lam = lam * math.sqrt(z.size(0))
if outer_penalty == "MCP":
return GMCP_op(z, lam)
elif outer_penalty == "SCAD":
return GSCAD_op(z, lam)
elif outer_penalty == "LASSO":
... |
def getTiming():
currentTime = datetime.datetime.now()
query = "SELECT * FROM 'main'.'prayer_times' WHERE Date = '" + getDate(0) +"';"
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
cursor.execute(query)
timing_status =0
for row in cursor:
for n in range(2,... | The main task of the code is to manage a timing-based event scheduler. It initializes a loop that checks for scheduled events, transitions between states (0: waiting for timing, 1: waiting for event), triggers media playback when the current time exceeds a scheduled event time, and updates status messages. It handles t... | def mainLoop():
print("Prayer Pod Loader")
print ("Version: " + str(program_version))
program_state=0
while True:
if (program_state == 0):
output_trigger=1
temp_time =getTiming()
if (temp_time ==0):
print("get timing error")
ref... |
def __encoder1(self, A, prune_A1, H, layer):
##print('enc1 = ',H)
H = tf.matmul(H, self.W1[layer])
if layer == self.n_layers1 - 1:
return H
self.C1[layer] = self.graph_attention_layer(A, H, self.v1[layer], layer)
if self.alpha == 0:
return tf.sparse.sparse... | The code implements a contrastive learning model with variational autoencoder (VAE) components, combining two encoders (Encoder1/Encoder2), a latent space (via mu/var), and decoders to reconstruct inputs. It computes contrastive loss, KL divergence, reconstruction loss (ZINB/MSE), and weight decay, aggregating them int... | def __call__(self, A1,A2 ,prune_A1,prune_A2, X1,X2):
# Encoder 1
H1 = X1
for layer in range(self.n_layers1):
H1 = self.__encoder1(A1, prune_A1, H1, layer)
if self.nonlinear:
if layer != self.n_layers1 - 1:
H1 = tf.nn.elu(H1)
# ... |
def calculate_stopping_point(self):
if self.model.recommender.recommender_type == 'no_recommend':
recommender_hv = 0
recommender_random = 0
elif self.model.recommender.recommender_type == 'high_value':
recommender_hv = 1
recommender_random = 0
... | The code's main task is to execute a sequence of actions in an agent's environment: calculate stopping points, move the agent, open a video interface, compute average payoff, determine payoff direction, and assess search quality. This step function orchestrates navigation, data processing, reward analysis, and performa... | def step(self):
self.calculate_stopping_point()
self.move()
self.open_video_box()
self.calculate_average_payoff()
self.calculate_payoff_direction()
self.calculate_search_quality() |
def price_sqft(df: pd.DataFrame) -> pd.DataFrame:
"""
Creates price/sqft columns in DataFrame. Must contain 'sale_price',
'sale_price_log10' and 'sqft' in the columns, where the first two names are
self explanatory and 'sqft' is the properties square footage.
Helper for create_stats().
Inputs:
... | The function `create_stats` generates statistical outlier measures from a DataFrame. It applies group-based calculations (e.g., mean, deviation) and additional metrics (e.g., duplicate stats, transaction days, percent change) based on grouping criteria and a `condos` flag. If `condos` is `False`, it first adjusts price... | def create_stats(df: pd.DataFrame, groups: tuple, condos: bool) -> pd.DataFrame:
"""
Create all statistical outlier measures.
Inputs:
df (pd.DataFrame): Dataframe to create statistics from
groups (tuple): grouping for groupby. Usually 'township' and 'class'
Outputs:
df(pd.DataFra... |
def create_stats(df: pd.DataFrame, groups: tuple, condos: bool) -> pd.DataFrame:
"""
Create all statistical outlier measures.
Inputs:
df (pd.DataFrame): Dataframe to create statistics from
groups (tuple): grouping for groupby. Usually 'township' and 'class'
Outputs:
df(pd.DataFra... | The function `go` processes a DataFrame to identify and flag outliers using a sequence of steps: calculating statistics, performing string processing, applying Isolation Forest on specified columns, and classifying outliers based on standard deviation bounds. It handles residential or condo data based on the `condos` f... | def go(
df: pd.DataFrame,
groups: tuple,
iso_forest_cols: list,
dev_bounds: tuple,
condos: bool,
):
"""
This function runs all of our other functions in the correct sequence.
Inputs:
df (pandas dataframe): data used to perform the outlier calculation
groups (tuple): whic... |
def add_bias(self, X):
return np.hstack((X,np.ones((X.shape[0],1))))
def predict_proba(self, X):
Y = np.array([self.predict_estimator(X, theta) for theta in self.thetas]).T
Y /= np.sum(Y, axis=1)[:, np.newaxis]
return Y
def magnitude_gradient(self, X):
X_norm = np.linalg.norm(X, axis=1)
gradMag = np.array([... | The main task of the code is to compute a normalized gradient length by multiplying predicted probabilities with magnitude gradients, summing across features, and scaling the result by the maximum gradient value to ensure values are within [0, 1]. | def expected_gradient_length(self, X):
X = self.add_bias(X)
grads = np.sum(np.multiply(self.predict_proba(X), self.magnitude_gradient(X)), axis=1)
return grads/max(grads) |
def selectUnassignedVariable(csp, assignment):
# Minimum Remaining Value
legalMovesLeftList = []
for t1 in csp.state:
determineLegalMoves(t1, assignment)
if t1.value == 0:
legalMovesLeftList.append([t1,len(t1.legalMoves)])
legalMovesLeftList.sort(key=lambda x:x[1])
if le... | This code implements a backtracking algorithm to solve a Constraint Satisfaction Problem (CSP). It recursively assigns values to unselected variables, checks consistency with current assignments, and explores possible solutions. If a valid assignment completes all 25 variables, it returns the solved CSP. Otherwise, it ... | def backtrack(csp, assignment):
if len(assignment) == 25:
return csp
tile = selectUnassignedVariable(csp, assignment) # tile object
for value in domainValues:
if isConsistent(value, tile, csp, assignment):
# add {var = value} to assignment
assignment[tile] = value
... |
def getTempo(mid, song_id):
if USING is ORIGINAL:
for msg in mid.tracks[0]:
if msg.type == 'set_tempo':
return msg.tempo
raise Exception('set_tempo msg not found')
elif USING is DAISHU:
with open(os.path.join(DAISHUPATH, song_id, 'tempo.txt'), 'r') as f:
... | The main task of the code is to process musical MIDI files by extracting tempo, beat structure, and chord data from song directories, normalize and filter the musical segments, quantize them according to rhythmic parameters, and save the processed results as CSV files in an output directory. It reads metadata from an i... | def main():
os.chdir(POP909PATH)
list_dir = os.listdir()
songs = [x for x in list_dir if os.path.isdir(x)]
meta = {}
try:
with open('index.csv', 'r', encoding='utf-8') as f:
c = csv.DictReader(f)
for line in c:
meta[line['song_id']] = line
except F... |
def makeBozoMove(self, board):
tempBoard = copy.deepcopy(board)
moves = []
pieces = []
move = ""
for r in tempBoard.grid:
for c in r:
if(c.team == self.team and type(c).__name__ != "Blank"): #Creates list of pieces CPU can move
piec... | The `makeMove` method selects a move strategy based on the agent's difficulty level, delegating to either `makeBozoMove`, `makeSmartMove`, or `makeTakeMove` to determine the next action on the given board. | def makeMove(self, board):
if self.difficulty == 0:
return self.makeBozoMove(board)
elif self.difficulty == 1:
return self.makeSmartMove(board)
elif self.difficulty == 2:
return self.makeTakeMove(board) |
def nn_layer(input_tensor, weight_shape, layer_name, relu=True, stride=None):
"""Reusable code for one nn layer
- Bias shape determined using the last dim of the weight shape
- Defaults to using ReLU unless 'relu' is set to false. Uses softmax then.
- Stride used to determine if convolution is necessary... | The code defines a TensorFlow CNN model for image classification or regression based on the `wind_speed` flag. It processes input images through convolutional and fully connected layers, using dropout for regularization. The model is trained on batches of data, with separate loss functions (cross-entropy for classifica... | def main(train, test, wind_speed=False):
tf.reset_default_graph()
sess = tf.InteractiveSession()
# pix*pix is image size; channels is number of channels bundled together
pix = 256
channels = 8 if wind_speed else 4
x = tf.placeholder(tf.float32, shape=[None, pix, pix, channels],
nam... |
def __check_token_tag(self, tag):
"""
Check tag of current token
"""
if self.tokens[self.__pos][1] == tag:
if tag == 'NLINE':
self.__n_line += 1
if self.__temp:
self.valid_cmds.append(self.__temp)
self.__temp... | The main task of the code is to determine if an expression matches one of several specified types (NLINE, common, arithmetic, logical, jump, or label) by checking each corresponding method. If any method returns True, the expression is valid; otherwise, it returns False. | def __expr(self):
"""
expr -> (NLINE | common | arifetic | logical | jump | label)
"""
if not (
self.__check_token_tag('NLINE') or
self.__common() or
self.__arifetic() or
self.__logical() or
self.__jump() or
self.__l... |
def build_words_graph(data):
words = set()
POSS = set()
for dg in data:
for (head, headPOS),rel, (dep, depPOS) in dg.triples():
words.add(head)
words.add(dep)
POSS.add(headPOS)
POSS.add(depPOS)
return words, POSS
def getStringToIdx(words, tags):
... | The code processes training data to build a word graph and mappings, trains a model, evaluates it on test data, calculates performance metrics (partial/cumulative percentages), and visualizes results with a plot comparing the metrics. | def main():
words, POSS = build_words_graph(train_data)
stringToIdx, lenWords, lenTags = getStringToIdx(words, POSS)
w = trainModel(train_data, stringToIdx)
testModel(test_data, w, stringToIdx)
print(partialPercent)
print(percentage)
partial, = plt.plot(range(len(partialPercent)), partialPer... |
def decode_state(encoded_state, spin_dimension, chain_length):
digits = np.array(list(decode_number_iterator(encoded_state, spin_dimension)))
digits.resize(chain_length, refcheck=False)
return list(digits)
def hamiltonian_item1(index, pair, decoded_state, spin_dimension, chain_length):
s = (spin_dimens... | The function computes the total Hamiltonian contribution for a quantum spin system by decoding an encoded state, pairing each spin with its neighbor (including the last with the first), calculating three distinct Hamiltonian terms (item1, item2, item3) for each pair, summing these contributions, and returning their tot... | def hamiltonian_column(encoded_state, spin_dimension, chain_length):
decoded_state = decode_state(encoded_state, spin_dimension, chain_length)
decoded_state_shift = np.roll(decoded_state, -1)
# decoded_state_zip = [ (s0, s1), (s1, s2), ..., (s[n-1], s0) ]
decoded_state_zip = list(zip(decoded_sta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.