dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_latest_vcd_api_version():
resp = requests.get(f'{VCD_API}/versions')
resp.raise_for_status()
versions = [
v.getElementsByTagName('Version')[0].firstChild.data
for v in parseString(resp.text).getElementsByTagName('VersionInfo')
if v.getAttribute('deprecated') == 'false'
]
... | This function creates an IAM user in VMware Cloud Director (VCD) by constructing an XML payload with user attributes (name, enabled status, external type, OAuth provider) and an admin role reference. It sends this data via a POST request to the VCD API, using provided or fetched authentication credentials and API versi... | def import_iam_user(username, version=None, token=None, org_id=None):
if version is None:
version = get_latest_vcd_api_version()
if token is None or org_id is None:
token, org_id = get_vcd_api_session_info(version)
headers = {
'Authorization': f'Bearer {token}',
'Accept': f'a... |
def open_image(self, image_path):
return Image.open(str(image_path)) if image_path is not None else None
def get_dimensions(self, image):
original_width, original_height = image.size
print(
f"Original dimensions: Width: {original_width}, Height: {original_height}"
)
r... | The function applies a sizing strategy to resize input and control images. It converts RGBA images to RGB, determines dimensions based on the strategy (input image, control image, or given values), resizes both images accordingly, and returns adjusted dimensions and images. | def apply_sizing_strategy(
self, sizing_strategy, width, height, control_image=None, image=None
):
image = self.open_image(image)
control_image = self.open_image(control_image)
if image and image.mode == "RGBA":
image = image.convert("RGB")
if control_image and ... |
def getClickedCell(data, event):
x_pos = event.x
y_pos = event.y
col = int(x_pos // data["cellSize"])
row = int(y_pos // data["cellSize"])
return [row, col]
def clickUserBoard(data, row, col):
if data["numberOfUserShips"] == 5:
exit()
else:
clickedCell = [row,col]
if ... | This function handles mouse clicks in a game, checking if a winner exists. If not, it determines the clicked cell and either lets the user place a ship on their board or triggers a game turn if all user ships are placed, updating the game state accordingly. | def mousePressed(data, event, board):
if data["winner"] == None:
[row, col] = getClickedCell(data, event)
if board == "user":
clickUserBoard(data, row, col)
else:
if data["numberOfUserShips"]==5:
runGameTurn(data,row,col) |
def makeModel(data):
data["rows"] = 10
data["cols"] = 10
data["boardSize"] = 500
data["cellSize"] = data["boardSize"]/data["rows"]
data["computerBoardShipNum"] = 5
data["userBoardShipNum"] = 5
data["computerBoard"] = emptyGrid(data["rows"],data["cols"])
data["userBoard"] = emptyGrid(dat... | This code sets up a GUI simulation for a two-player ship placement and guessing game using Tkinter. It creates two windows: one for the user to place ships and another for the computer to make guesses. Event handlers manage keyboard inputs and mouse clicks on canvases, updating the game state and visuals. The simulatio... | def runSimulation(w, h):
data = { }
makeModel(data)
root = Tk()
root.resizable(width=False, height=False) # prevents resizing window
# We need two canvases - one for the user, one for the computer
Label(root, text = "USER BOARD - click cells to place ships on your board.").pack()
userCanva... |
def reset(self):
self.rebootModule()
print("Set Phone Function")
self.setPhoneFunction()
print("Set Phone Function Complete")
def getIMEI(self):
self.ser.write(b"AT+CGSN=1\r\n")
msg = ""
msg = self.ser.read(64).decode('utf-8').strip()
return msg[msg.find("... | The main task of the code is to initialize and configure an NB-IoT device by setting the server port, resetting the device, retrieving and printing debug information (IMEI, firmware version, IMSI if enabled), and attaching the device to the NB-IoT network using the specified port. | def setupDevice(self, serverPort):
self.port = serverPort
print("############ NB-IOT Library #############")
self.reset()
if self.debug:
self.IMEI = self.getIMEI()
print("IMEI : " + self.IMEI)
self.firmwareVersion = self.getFirmwareVersion()
... |
def evaluate_llm_pyG(args):
data = (
ReactionDataset(root=f'dataset/{args.dataset}/', role='reactant', mode=args.mode),
ReactionDataset(root=f'dataset/{args.dataset}/', role='prod', mode=args.mode)
)
identifiers = data_processing.load_identifiers(args)
model = load_model(args)
model... | This code evaluates different machine learning models (MolR_pyG, LocalRetro, Megan) by loading model-specific data, configuring context parameters, initializing the model, and executing evaluation. It handles model-specific evaluation functions, data preprocessing, and context-aware evaluation setups to assess model pe... | def evaluate_llm(args):
if args.model == 'MolR_pyG':
evaluate_llm_pyG(args)
return
elif args.model == 'LocalRetro':
evaluate_llm_LocalRetro(args)
return
elif args.model == 'Megan':
evaluate_llm_Megan(args)
return
data = data_processing.load_data(args)[1]
... |
def _run_action(self, action: int):
"""Runs the specified action from the list of acceptable actions."""
button_press = self.valid_actions[action]
button_release = self.valid_releases[action]
# One of the valid actions is None, only send non-None event
if button_press:
... | This code advances the agent by one step in a reinforcement learning environment. It executes the given action, updates the observation state, checks termination/truncation conditions, calculates the reward based on termination reason, and retrieves additional info. The function returns the new observation, reward, ter... | def step(
self, action: Any
) -> Tuple[Any, SupportsFloat, bool, bool, Dict[str, Any]]:
"""Advances the agent forward one step."""
# Input comand and step pyboy forward
self._run_action(action)
# Update observation data
observation = self._get_observation()
... |
def path_hash(path: str) -> str:
"""
Return the hash of the path as md5
"""
return hashlib.md5(path.encode()).hexdigest()
def get_env_by_path(self, path: str) -> Optional[FullEnvironmentEntry]:
envs = self.environments
path = os.path.normpath(os.path.abspath(path))
for env in env... | This function registers a new environment in the .env_manager folder by creating or updating an EnvironmentEntry with the provided path and Python executable. It checks if the environment already exists; if so, it raises an error unless 'force' is True. The environment's details are then saved, and the updated entry is... | def add_env(
self,
path: str,
py_executable: str,
name: Optional[str] = None,
force: bool = False,
) -> FullEnvironmentEntry:
"""
Register an environment in the .env_manager folder
"""
ENVPICKER_LOGGER.info("Adding environment %s", path)
... |
def words_in_a_folder(path):
"""Total number of words in a folder"""
files_cont = ''
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
fil = open(file_path)
content = fil.read()
files_cont += content
files_cont = re.sub(r'[^\w\s]','',files_cont) #... | This function calculates the probability of each directory in the training data based on word frequencies from a given list (cont_list). It uses Laplace smoothing to estimate word probabilities, multiplies them, and adjusts by the directory's prior probability (number of files in the directory divided by total files). ... | def probability_dict(cont_list, train_data):
x = {}
for dir in os.listdir(train_data):
#print(dir)
words = words_in_a_folder('{}{}'.format(train_data,dir))
b =[]
for element in cont_list:
count = 0
for word in words:
if element == word:
... |
def stop_word(input_words):
from nltk.corpus import stopwords
en_stops = set(stopwords.words('english'))
all_words = input_words
words = list()
for word in all_words:
if word not in en_stops:
words.append(word)
return words
def probability_dict(cont_list, train_data):
... | This function calculates the probability of each test document relative to trained data by processing text files: removing punctuation, normalizing case, eliminating duplicates and stop words, then using a probability dictionary and percentage calculator to determine and return a list of probabilities for each test fil... | def probability(test_data, train_data):
""" find the probability of testing data up on trained data"""
prob_list = list()
for filename in os.listdir(test_data):
print(filename)
print()
file_path = os.path.join(test_data, filename)
fil = open(file_path)
content = fil.r... |
def first_seg(img, label_x, label_y):
"""
Return the segmented image by applying model_seg_heart 2 times
"""
image = model_seg_heart(model_seg_heart(img_to_array(img), 7, label_x, label_y), 7, label_x, label_y)
return image
def cut(img_arrr):
"""
Take the image and isolate the heart
... | The main task of the code is to perform a second segmentation on an image by first applying an initial segmentation, then applying specific border modifications (bd1, bd2) and a cutting operation to refine the segmentation. The function returns both the original segmented image and the processed image after applying th... | def second_seg(img, bd1, bd2, xf, xl, yf, yl, label_x, label_y):
"""
Return the image segmented after first segmentation and applying cut, border1, border2
"""
image = first_seg(img, label_x, label_y)
bd1 = [np.nan for i in range(xf)] + [60 for i in range(xf,xl)] + [np.nan for i in range(xl,20... |
def second_seg(img, bd1, bd2, xf, xl, yf, yl, label_x, label_y):
"""
Return the image segmented after first segmentation and applying cut, border1, border2
"""
image = first_seg(img, label_x, label_y)
bd1 = [np.nan for i in range(xf)] + [60 for i in range(xf,xl)] + [np.nan for i in range(xl,20... | The code adjusts the y_label position to ensure the segmented heart mask has a valid number of pixels (between 1500 and 11999). If the pixel count is out of range and y_label is below 125, it increments y_label by 5 and recursively reprocesses the image until the condition is met, returning the corrected mask and final... | def metric(img, x_label, y_label):
"""
Move the position of the pixel used to select the heart mask if the number of pixels of the image segmented is not within the interval considered
"""
xf, xl = 50, 170
yf, yl = 30, 150
bd1 = [np.nan for i in range(xf)] + [60 for i in range(xf,xl)] + [np.na... |
def read_arduino_update(self, analog_input, interval):
analog_value = analog_input.read()
if type(analog_value) == float:
voltage_value = analog_value * (5.00 / 1.0)
# dataLength = len(Ui_MainWindow.rwdt)
# Ui_MainWindow.Xm[:-dataLength] = Ui_MainWindow.Xm[dataLength:... | The main task of the code is to initiate and manage EMG signal logging by disabling UI controls, updating status indicators, continuously reading Arduino data, calculating sampling rates and RMS values, and dynamically updating real-time data displays (samples, elapsed time, RMS value) until logging stops. It handles b... | def start_button(self):
self.condition = 1
self.startButton.setEnabled(False)
self.stopButton.setEnabled(True)
self.fileSelect_1.setEnabled(False)
self.fileSelect_2.setEnabled(False)
self.fileSelect_3.setEnabled(False)
self.selectButton_1.setEnabled(False)
... |
def labelPositions(self):
allowedPositions = []
# how high should a label be?
generalHight = 15 # px on screen
generalHight = self.ctx.device_to_user_distance(0,generalHight)[1]
# get plasmid view width and height
width, height = self.GetVirtualSize()
# so labels are arranged around the plasmid... | The main task of the code is to render a plasmid diagram using Cairo graphics, including drawing circular plasmid structures, labeling features, and visualizing selection areas. It adjusts canvas scaling, draws inner/outer circles, and conditionally renders plasmid names, features, and selection highlights based on loa... | def DrawCairo(self, ctx, exportSize=False):
''' Function that draws the whole plasmid in every aspect'''
self.ctx = ctx
if exportSize == False:
width, height = self.GetVirtualSize() # set hight and width. Its 100, 100
canvasWidth = self.size[0]
canvasHeight = self.size[1]
ratio = float(canvasHe... |
def pos_to_angle_rad(self, position):
len_dna = float(len(genbank.gb.GetDNA()))
radMult = float(2*math.pi/len_dna)
angle = (position - 0.5 * len_dna) * radMult + math.pi/2
return angle
def set_dna_selection(self, selection):
'''Receives requests for DNA selection and then sends it.'''
assert type... | This function draws a circular DNA selection arc using Cairo, calculating start/finish angles from genomic positions. It handles both direct coordinate input and feature-based selection, determining direction (clockwise/counter-clockwise) for rendering, updating internal state variables, and triggering UI refresh. The ... | def drawCairoSelection(self, start=0, finish=0, feature=False):
# we need:
radius = self.radius
self.selectionDrawing = []
# feature to highlight or drag and drop?
if feature != False:
featurelist = genbank.gb.get_all_feature_positions()
for i in range(0,len(featurelist)):
... |
def HitTest(self):
'''Tests whether the mouse is over any feature or label'''
hit = None
x, y = self.ScreenToClient(wx.GetMousePosition())
# get the mouse positions
x2, y2 = self.ctx.device_to_user(x,y)
for path in self.hittest:
cairoCtx = self.ctx
for i in self.hittest[path]:
# load the p... | This method handles a left mouse button release event to finalize a selection. It checks if the click hits a feature using HitTest(). If so, it highlights the feature and draws a selection using drawCairoSelection(). If no feature is hit, it clears the highlight. Finally, it updates the UI to reflect the selection chan... | def OnLeftUp(self, event):
# remove start point, so we know selection is done:
self.left_down_angle == False
# maybe he hit a feature?
hit = self.HitTest()
if hit != None:
self.HighlightClick = hit
# we hit one, so we need to draw the selection!
# wich feature was hit?
self.drawCairoSelection(0... |
def cartesian2radial(self,x, y):
x=-x # to make it correct
add = math.radians(90)
a = math.atan2(x,y) + 1 * math.pi - add
return a
def drawCairoSelection(self, start=0, finish=0, feature=False):
# we need:
radius = self.radius
self.selectionDrawing = []
# feature to highlight or dr... | This code handles mouse motion events to select DNA regions by calculating angles from mouse positions during left-click drags. It draws selections, updates DNA range selections, and manages visual highlights/hover states. If dragging, it computes start/finish angles for selection; otherwise, it checks for feature high... | def OnMotion(self, event):
'''When mouse is moved with the left button down determine the DNA selection from angle generated at mouse down and mouse move event.'''
if event.Dragging() and event.LeftIsDown() and self.left_down_angle != False:
# we have to make a selection now!
start_angle = self.left_down_a... |
def gini(rows):
"""calculate the gini impurity for each row"""
counts = class_counts(rows)
impurity = 1
for label in counts:
prob = counts[label]/len(rows)
impurity -= prob**2
return impurity
def partition(rows, question):
"""
partion the data set depending on the result of... | The function identifies the optimal feature and value to split data in a decision tree by calculating information gain. It iterates through features, partitions data based on each feature's unique values, computes Gini impurity reduction, and selects the split with maximum gain. The process ensures the best question fo... | def find_best_split(rows):
"""this findds the best question for the node. it iterates over all the features and figures out which results in the
best impurity and information gains from the data"""
best_gain = 0
best_question = None
current_uncertainty = gini(rows)
n_features = len(rows[0]) - 1
... |
def find_best_split(rows):
"""this findds the best question for the node. it iterates over all the features and figures out which results in the
best impurity and information gains from the data"""
best_gain = 0
best_question = None
current_uncertainty = gini(rows)
n_features = len(rows[0]) - 1
... | The main task of the code is to recursively build a decision tree by partitioning data rows based on maximum information gain. It checks for a base case (no gain) to return a leaf node, otherwise splits data, recursively constructs true/false branches, and returns a Decision_Node with the best split question and child ... | def build_tree(rows):
"""Builds the tree.
Rules of recursion: 1) Believe that it works. 2) Start by checking
for the base case (no further information gain). 3) Prepare for
giant stack traces.
"""
# Try partitioing the dataset on each of the unique attribute,
# calculate the information gai... |
def calculate_wins_losses(list_of_dicts, start, end):
"""
Calculates the number of wins and losses for each player that played in a
match in the list_of_dicts from the start index to the end index (inclusive).
Returns a dictionary where each player name is a key and the corresponding
value is a list... | The function assigns "Round number" and "Round name" to each dictionary in the input list, identifying tournament segments and applying specific logic to determine round details. It distinguishes between round-robin and single-elimination formats, considering factors like byes and third-place matches, and uses helper f... | def assign_rounds(list_of_dicts):
"""
Assign rounds to each of the dictionaries in list_of_dicts by adding "Round number"
and "Round name" keys along with the value determined for each
Parameters
----------
list_of_dicts : list of dictionaries
list of dictionaries representing rows of d... |
def PClass(text,vocab,labels,model,lm):
bagOfWords = wordBag(text,vocab,lm)
ourResult = model.predict(np.array([bagOfWords]))[0]
newThresh=0.2
yp = [[i,res]for i,res in enumerate(ourResult) if res>newThresh]
yp.sort(key=lambda x:x[1],reverse=True)
newList=[]
for r in yp:
newList.append(labels[r[0]])
... | This function initializes a model for intent recognition, processes user inputs to determine intents, generates responses using predefined data, and allows users to add new patterns to the model based on feedback. The loop continues until the user quits by typing 'q', at which point it returns 'Model Trained'. | def initialize_model(model,newWords,classes,data,lm):
print(f"{Fore.YELLOW}Initializing Model...")
while True:
newMessage = input(f"{Fore.BLUE}You : ")
print(f"{Style.RESET_ALL}")
if(newMessage=="q"):
return "Model Trained"
intents = PClass(newMessage,newWords,classes... |
def process_data():
print("Processing data...")
f=open('intents.json')
data =json.load(f)
lm = WordNetLemmatizer()
ourClasses=[]
newWords=[]
docPattern=[]
docTag=[]
for intent in data['intents']:
for pattern in intent['patterns']:
ourNewTokens = nltk.word_tokeniz... | The code trains a machine learning model by processing input data, constructing the model architecture, evaluating its performance, saving the updated model locally, and initializing it with processed data, new words, classes, and language model parameters for deployment or further training. | def train():
x,y,newWords,classes,data,lm = process_data()
model = build_model(x,y)
evaluate_model(model, x, y)
save_local_model_update(model)
initialize_model(model,newWords,classes,data,lm) |
def _download(self) -> None:
response = requests.get("https://figshare.com/ndownloader/files/11826395", stream=True)
download_filepath = self.base_folder.joinpath(self._RESOURCES['compress'][0])
total_size = int(response.headers.get('content-length', 0))
with tqdm(total... | This code initializes a dataset handler for the UMAFall fall detection dataset. It configures parameters like sampling rate, window size, and location, then checks if the dataset needs downloading, extraction, or preprocessing. If the split is 'train', it preprocesses the data. Finally, it loads the processed dataset i... | def __init__(
self,
split: str = "train",
sr: int = 20,
window: set = (10, 0.5),
location: list = ["Wrist"],
download: bool = False
) -> None:
super().__init__()
self.download = download
self.location = location
# sampling... |
def create_table(private_config_xml_file):
query_create_table = (
'create table if not exists eva_progress_tracker.clustering_release_tracker('
'taxonomy int4 not null, '
'scientific_name text not null, '
'assembly_accession text not null, '
'release_version int8 not null, '
... | The code processes command-line arguments to create/load a clustering/release tracking table, update RS counts in MongoDB, or perform specified tasks like table creation, data filling, and remapping. It uses a config file, release version, reference directory, and optional taxonomy ID to execute tasks such as table ini... | def main():
parser = argparse.ArgumentParser(description='Create and load the clustering and release tracking table', add_help=False)
parser.add_argument("--private-config-xml-file", help="ex: /path/to/eva-maven-settings.xml", required=True)
parser.add_argument("--release-version", help="version of the rele... |
def calc_support_resistance(h, extmethod = METHOD_NUMDIFF, method=METHOD_NSQUREDLOGN,
window=125, errpct=0.005, hough_scale=0.01, hough_prob_iter=10,
sortError=False, accuracy=1):
if not type(window) is int:
raise ValueError('window must be of type int... | The main task of the code is to test the `calc_support_resistance` function and related plotting utilities by validating their outputs against predefined results for synthetic data and real stock data (S&P 500). It checks consistency across different methods (e.g., naive, Hough-based) and data types (lists, NumPy array... | def test_sup_res(curdir):
data = [0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0]
data = [float(x) for x in data]
result = (([6, 12, 18], [0.0, 0.0], [([6, 12, 18], (0.0, 0.0, 0.0, 0.0, 0.0, 0.0))], [[([6, 12, 18], (0.0, 0.0, 0.0, 0.0, 0.0, 0.0))]]), ([3, 9, 15, 21], [0.0, 3.0], [... |
def load_dataset(self, file_name: str):
filename = self.root_dir/file_name
with open(filename, 'r', encoding="utf-8") as f:
lines = f.readlines()
return lines
def analysing(self, lines: List[str]) -> List[str]:
if self.license_only:
# print("I am here")
... | This code processes a single file by loading its data, filtering it, updating counters for original and filtered line counts, and writing the filtered data back to the same file. | def process_single_file(self, file_name: str):
original_lines = self.load_dataset(file_name=file_name)
filtered_lines = self.analysing(lines=original_lines)
self.num_original += len(original_lines)
self.num_filtered += len(filtered_lines)
self.write_data(filtered_lines, file_name... |
def load_dataset(self, file_name: str):
filename = self.root_dir/file_name
with open(filename, 'r', encoding="utf-8") as f:
lines = f.readlines()
return lines
def analysing(self, lines: List[str]) -> List[str]:
if self.license_only:
# print("I am here")
... | This function processes files by loading datasets, filtering lines, and writing results. It uses multiprocessing Values to track original and filtered line counts. If `license_only` is enabled, it processes non-valid licenses from a queue, updating counters and appending detected entries to a list. | def process_single_file_with_queue(self, filenames: str, position: int,
num_original: multiprocessing.Value,
num_filtered: multiprocessing.Value):
for file_name in tqdm(filenames, position=position, total=len(filenames), colour=pro... |
def solver(arr):
l =[0, 0]
if(not find_empty_location(arr, l)):
return True
row = l[0]
col = l[1]
for num in range(1, 10):
if(check_location_is_safe(arr,
row, col, num)):
arr[row][col]= num
if(so... | The main task of the code is to validate a user's board choice, load a corresponding puzzle board from a file, store it in the doku object, and initiate solving or display. If the choice is invalid, it shows an error and re-prompts for selection. | def submit_board(self):
bo = ['1','2','3','4']
li1= []
if self.choice.get() in bo:
with open("%s.txt" % self.choice.get(),'r') as f:
lines = f.readlines()
for line in lines:
if line[-1] == '\n':
li1.append(li... |
def pred_class_truth_table_to_bool(pred_class):
out_list = []
for entry1 in pred_class:
current_pred = []
for i,entry2 in enumerate(entry1):
if entry2 == True and i == 1:
current_pred.append(1)
if entry2 == True and i == 0:
current_pred.app... | This function adjusts significance levels based on a slider input, uses an ICP model to predict class probabilities and classifications from test data, updates JSON data with results, and generates three plots (p0p1, disease course, pval) for visualization. | def slider_function(slider_value,json_data):
slider_value_significane = 1- (slider_value/100)
x_test = np.array(json_data["x_test"])
age_at_visit_order = json_data["age_at_visit_order"]
colnames = json_data["colnames"]
icp = joblib.load(icp_model_path)
test_pval = icp.predict(x_test)
test_... |
def segregate_direct_data(input_data):
visit_data,relapse_data = [],[]
break_count = 0
current_row_data = []
i = 1
for entry in input_data:
if entry == "break":
break_count += 1
i = 1
continue
if break_count == 0:
if i%2 == 0:
... | The function processes input data by segregating visit and relapse records, parses patient information using provided dates and values, and applies a predictive model to generate outcomes based on the patient dataframe, slider input, and additional JSON parameters. | def direct_predict(dob_value,debut_date,debut_relapse_date,slider_value,json_data,*input_values):
visit_df,relapse_df = segregate_direct_data(input_values)
patient_df = parse_data(dob_value,debut_date,debut_relapse_date,visit_df,relapse_df)
return model_predict(patient_df,slider_value,json_data) |
def segregate_file_data(input_files):
for files in input_files:
if "visit.csv" in files.name:
visit_df = pd.read_csv(files.name)
if "relapse.csv" in files.name:
relapse_df = pd.read_csv(files.name)
return visit_df,relapse_df
def parse_data(dob_value,debut_date,debut_relap... | The function processes uploaded medical files by segregating them into visit and relapse dataframes, parses patient information using input parameters, and applies a predictive model to generate outcomes based on the processed data and additional inputs like slider values and JSON configurations. | def file_predict(dob_value,debut_date,debut_relapse_date,slider_value,json_data,uploaded_files):
visit_df,relapse_df = segregate_file_data(uploaded_files)
patient_df = parse_data(dob_value,debut_date,debut_relapse_date,visit_df,relapse_df)
return model_predict(patient_df,slider_value,json_data) |
def display_menu():
"""
Displays the main menu options to the user.
"""
print("\n=== Receipt Processor System ===")
print("1. Process Receipt")
print("2. Retrieve Points")
print("3. Exit")
def process_receipt_cli():
"""
Handles the process receipt functionality in the CLI.
"""
... | The main task of the code is to run a command-line interface (CLI) program for a receipt processor system. It displays a menu, processes user choices (process receipt, retrieve points, or exit), and executes corresponding functions. The loop continues until the user selects the exit option, ensuring interactive managem... | def main():
"""
Main routine for the CLI program.
"""
f = pyfiglet.figlet_format("Receipt Processor", font="slant", width=20)
print(f)
while True:
display_menu()
choice = input("\nEnter your choice: ")
if choice == '1':
process_receipt_cli()
elif cho... |
def prepare_data(self):
data = load_pickle(self.config.data_path)
return data['train'], data['dev'], data['test'], data['oov']
def add_summary(self, sess):
self.summary_merge = tf.summary.merge_all()
self.file_writer = tf.summary.FileWriter(self.config.summary_dir,
... | This code trains a machine learning model using TensorFlow, implementing early stopping, learning rate decay, and model checkpointing. It loads data, initializes variables, restores pre-trained models if specified, and iterates over epochs to train and evaluate the model on training, validation, and out-of-vocabulary (... | def train(self):
saver = tf.train.Saver()
# early stop
best_score = 0.0
num_epoch_no_improve = 0
# load and split data
train, dev, test, oov = self.prepare_data()
with tf.Session() as sess:
sess.run(self.var_init)
# load trained model
... |
def search_page_urls(query,location):
""" Return a list of search urls for a multi-page search. """
url = make_query_url(query,location)
_,increment,total = get_search_info(url)
num_iters = total // increment
page_urls = [make_query_url(query,location,i*increment)
for i in range(num... | The function `job_search` retrieves job links from Indeed.com based on a query and location by concurrently fetching and parsing job listing pages using multithreading, aggregating results into a list of links. | def job_search(query,location):
""" Return all Indeed.com job links associated
with the given query and location."""
links = []
page_urls = search_page_urls(query,location)
with futures.ThreadPoolExecutor(NUM_THREADS) as ex:
to_do = [ex.submit(lambda url: get_job_links(make_soup(url)),u... |
def job_search(query,location):
""" Return all Indeed.com job links associated
with the given query and location."""
links = []
page_urls = search_page_urls(query,location)
with futures.ThreadPoolExecutor(NUM_THREADS) as ex:
to_do = [ex.submit(lambda url: get_job_links(make_soup(url)),u... | The main task of the code is to search for job links based on a query and location, retrieve job postings from those links, and save the collected postings to a specified output file. The function sequentially performs three steps: fetching job links, extracting job postings from the links, and saving the postings to a... | def main(query,location,outfile):
print("Getting job links...")
links = job_search(query,location)
print("Getting postings...")
postings = get_job_postings(links)
print("{} postings found. Saving...".format(len(postings)))
save_postings(postings,outfile) |
def cnv_scale(src, dst):
dst.x = src[0]
dst.y = src[2]
dst.z = src[1]
return dst
def cnv_translation(src, dst):
# same as src.rotate(Quaternion((1,1,0,0))) # 90 deg CW axis X
# src0 = src.copy()
# q = mathutils.Quaternion((-1, 1, 0, 0))
# q.normalize()
# src0.rotate(q)
# dst.x = ... | This function exports scene objects to a data structure, applying transformation conversions (location, rotation, scale) based on object type and configuration. It skips hidden/unselected objects, assigns IDs/names, handles coordinate system adjustments (Z-up to Y-up), and establishes parent-child relationships. Custom... | def export_all_tobjects(scene, data, cfg):
for obj in scene.objects:
if obj.hide_render or (cfg.option_export_selection and not obj.select):
continue
if cfg.need_update(obj):
tobject = data.tobjects.add()
tobject.id = cfg.id_of(obj)
tobject.name = obj.... |
def export_all_tobjects(scene, data, cfg):
for obj in scene.objects:
if obj.hide_render or (cfg.option_export_selection and not obj.select):
continue
if cfg.need_update(obj):
tobject = data.tobjects.add()
tobject.id = cfg.id_of(obj)
tobject.name = obj.... | The function `export` orchestrates the export of various scene elements by sequentially calling multiple sub-functions. These include exporting objects (`tobjects`), geometries, materials, lights, skeletons, actions, and physics data, all using the provided `scene`, `data`, and `cfg` parameters. Its primary task is to ... | def export(scene, data, cfg):
export_all_tobjects(scene, data, cfg)
export_all_geometries(scene, data, cfg)
export_all_materials(scene, data, cfg)
export_all_lights(scene, data, cfg)
export_all_skeletons(scene, data, cfg)
export_all_actions(scene, data, cfg)
export_all_physics(scene, data, c... |
def create_staffuser_and_set_token_credentials(self):
account_instance = AccountUserTests()
staff_user = account_instance.create_staff_user()
self.set_user_token_credentials(
staff_user.username, account_instance.staffuser1_password)
def create_category(self, category_name, parent=No... | The code tests retrieving a category collection via an API. It creates a staff user, adds a category, then verifies the API returns a 200 OK status, one item (with pagination enabled), and matches the category's name and active status. | def test_get_category_collection(self):
self.create_staffuser_and_set_token_credentials()
self.create_category(self.category1_name,
self.category1_parent, self.category1_is_active)
response = self.get_category_collection()
self.assertEqual(response.status_cod... |
def _mos_update_params(params):
"""Make a complete parameter table for mos"""
if 'nf' not in params: # number of fingers
params['nf'] = 1
if 'nfdmyl' not in params: # number of left-dummy fingers
params['nfdmyl'] = 0
if 'nfdmyr' not in params: # number of right-dummy fingers
p... | This function generates a MOSFET (nmos/pmos/ptap/ntap) layout by assembling boundary cells, dummy transistors, and core structures based on parameters. It creates virtual instances with specified shapes, pitches, and transformations, incorporating routing and pin definitions. The output is a laygo2 VirtualInstance repr... | def mos_generate_func_skywater(devtype, name=None, shape=None, pitch=None, transform='R0', params=None):
"""Generates an instance from the input parameters."""
# Compute parameters
params = _mos_update_params(params)
# Create the base mosfet structure.
nelements = dict()
cursor = [0, 0]
# L... |
def transform_data_with_pipeline(pipeline, x_df, original_column_names=True):
"""
Strips out the model from a pipeline and applies the preprocessing steps to x_df.
:param pipeline: scikit-learn pipeline
:param x_df: x dataframe
:param original_column_names: Boolean of whether to use the original co... | The function `run_omnibus_model_explanation` generates model interpretability analyses for a machine learning pipeline by producing Partial Dependence (PDP), Accumulated Local Effects (ALE), and Individual Conditional Expectation (ICE) plots, calculating permutation and drop-column feature importance, and generating SH... | def run_omnibus_model_explanation(pipeline, x_df, y_test, x_train, y_train, scorer, scorer_string, scoring_type,
model_uid, higher_is_better):
"""
Runs a series of model explainability techniques on the model.
- PDP plots
- ICE plots
- ALE plots
- permutation im... |
def identify_deleted_files(self):
"""
Identify files which meet the following criteria:
- File exists in datastore but not on disk
"""
processable_files = self.get_all_directory_processable_files()
db_files = [(item[0], item[1], item[2]) for item in self.store.get_all()]
... | The code identifies files out of sync between a datastore and disk by detecting deleted (datastore-only), new (disk-only), and updated (content mismatch) files. It then deletes, adds, or updates these files in the datastore, using progress tracking and status updates. The task ensures synchronization by reconciling dis... | def identify_files_out_of_sync(self):
"""
Identify files which meet the following criteria:
- File content in datastore does not match file content on disk
- File is on datastore but doesn't exist on disk
- File is on disk but doesn't exist in datastore
"""
delete... |
def print_time() -> None:
print(f'\n{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}')
def get_realtime_data(sensor: int) -> Optional[Dict[str, Union[float, str]]]:
"""
pull data for one sensor from purpleair.com
"""
response = requests.get(f"https://www.purpleair.com/json?show={sensor}")
... | (The function pulls air quality data from PurpleAir sensors, displays real-time metrics on a terminal or Pi LCD screen, and sends a text alert if AQI exceeds a threshold. It returns a boolean indicating whether the air quality was not bad and text notification was sent.) | def pull_and_show(
params: Dict[str, Any], show_time: bool = True, text: bool = False, pi: bool = False
) -> bool:
"""
Pull the data from purpleair, print to either terminal or Pi's LCD screen
params: params from load_params()
show_time: Print the time before each output
text: Send a text if the... |
def current_colour_array(self):
pos = self.current_frame_place()
if self.colour_parent_array:
array = self.colour_parent_array[pos]
return array
self.colour_parent_array.append(self.colour_array)
array = self.colour_parent_array[pos]
return array
def hide_scrollbar(self,event):
#print(self.curre... | This code deletes a specified button from a color list. If an item is provided, it removes that button; otherwise, it deletes the last button. It updates the UI by destroying the button, removing it from the list, and adjusting the scrollbar. | def delete_color(self, item):
# Find the index of the button in the list
colour_list = self.current_colour_array()
last = colour_list[-1]
# if Button was Pressed delet last pressed button
if item != None:
item.destroy()
colour_list.remove(item)
self.button_id = None
# if Button wasnt... |
def current_colour_array(self):
pos = self.current_frame_place()
if self.colour_parent_array:
array = self.colour_parent_array[pos]
return array
self.colour_parent_array.append(self.colour_array)
array = self.colour_parent_array[pos]
return array
def current_frame_event(self):
frame_place = self.... | This function manages color frame navigation and modification in a palette system. It adds new frames when at the last position with non-empty colors, navigates between frames using 'where' (-1/1), and removes trailing frames if moving back to an empty current frame. It maintains frame array integrity by updating or de... | def _frame(self,frame=None,command = None,where = None):
current_array = self.current_colour_array()
if frame == None:
frame = self.current_frame_event()
if where == None: # when colours i called with where == None no frame will be placed or created
return
if len(self.colour_pallets_frames) == self.... |
def _frame(self,frame=None,command = None,where = None):
current_array = self.current_colour_array()
if frame == None:
frame = self.current_frame_event()
if where == None: # when colours i called with where == None no frame will be placed or created
return
if len(self.colour_pallets_frames) == self.... | This code initializes a color palette interface with navigation buttons, add/remove/edit functionality, and dynamic frame management for color selection, updating a preview image based on user interactions. | def __init__(self,master,right_arrow_image,left_arrow_image,update_preview_image,gradient_length, **kwargs):
super().__init__(master, **kwargs)
self.grid_rowconfigure((0,2),weight=0)
self.grid_rowconfigure((1),weight=1)
self.grid_columnconfigure((0,1,2),weight=0)
self.update_preview_image = update_preview... |
def current_frame_place(self):
place = self.colour_pallets_frames.index(self.current_frame)
return place
def darken_color(self, hex_color, factor=0.7):
# Convert hex color to RGB
rgb_color = tuple(int(hex_color[i:i+2], 16) for i in (1, 3, 5))
# Darken the color by multiplying each component by the factor... | This code adds a color button to a frame, dynamically positions it in a grid layout, and stores it in an array. The button's background is the input color, with a darker hover effect. Clicking it triggers a color change function. The UI updates and adjusts the scrollbar after a delay. | def add_color(self,color):
current_frame = self.current_frame
place = self.current_frame_place()
colour_array = self.colour_parent_array[place]
darker_color = self.darken_color(color)#calls function to make a darker version of color
# Creates button and places it
button = ctk.CTkButton(current_frame, tex... |
def gen_id(row):
state = row['state']
state_abbrev = us_state_to_abbrev[state].lower()
city = row['city']
city_abbrev = city.replace(' ', '').replace('.', '').lower()
if len(city_abbrev) == 0:
if state_abbrev == unknown_location_acronym:
city_abbrev = unknown_location_acronym
... | This function adds missing 'id' fields to each data row by generating them with gen_id(), checks for missing 'name' fields (exiting if found), validates the uniqueness of all 'id's, and rewrites the updated data. | def add_missing_ids():
data = data_builder.read_all_data()
for row in data:
if "id" not in row or len(row["id"]) == 0:
row["id"] = gen_id(row)
print("Added id: " + row["id"])
if "name" not in row:
print(row)
critical_exit("this row is broken with ... |
def add_new_2(matrix):
r = random.randint(0,3)
c = random.randint(0,3)
while(matrix[r][c] != 0):
r = random.randint(0,3)
c = random.randint(0,3)
matrix[r][c] = 2
def get_current_state(matrix):
for i in range(4):
for j in range(4):
if(matrix[i][j])==2048:
... | The main task of the code is to start a 2048-style game where the user controls tile movement on a 4x4 grid. The game initializes with two random '2's, processes directional inputs (W/A/S/D) to merge and shift tiles, adds new '2's after valid moves, and checks game states (continue, win, lose). The loop terminates when... | def start_game():
#Defines the empty 4x4 matrix
matrix = [[0 for i in range(4)] for i in range(4)]
#Commands for the user
print("commands: ")
print("W to move up ")
print("S to move down")
print("D to move right ")
print("A to move left ")
print("Q to quit ")
#Calls the ... |
def build_image_pair_list(image_directory, num_pairs=None, random=False, fraction=1.0, num_per_pair=2,
pattern='warp*.fits'):
"""
Build a list of images to make cutouts from and return list of pairs of images.
:param pattern: Only files matching this patter will be added to the ima... | The main task of the code is to generate square cutouts from image pairs for machine learning tasks, using parameters like cutout size, randomness, and sample counts. It processes image directories, extracts planted source data, and optionally visualizes the brightest cutouts, logging results for debugging and configur... | def main():
""""
This is the main method which runs this module as a Command Line script.
"""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--image-directory', default='./',
help='name of directory containing ima... |
def _eprint(s: str):
print("setuptools-monorepo: " + s, file=sys.stderr)
def _get_repo_root() -> str:
result = _run_command(["git", "rev-parse", "--show-toplevel"])
return result.stdout.decode().strip()
def _discover_scripts(repo_root: str) -> Iterable[Script]:
script_markers = _find_script_markers(repo... | This function executes a specified monorepo script by locating its entrypoint function, validating its existence, argument compatibility, and then invoking it with provided parameters and a distribution object. | def _call_script(dist: setuptools.dist.Distribution, target: str, args: Dict[str, Any]):
_eprint(f"Looking for monorepo script {target}")
repo_root = _get_repo_root()
scripts = _discover_scripts(repo_root)
target_script = next((s for s in scripts if s.name == target), None)
if target_script is Non... |
def bbox_np(array_pts_3d):
# NumPy implementation of bbox
min_x = np.min( array_pts_3d[:, 0] )
min_y = np.min( array_pts_3d[:, 1] )
max_x = np.max( array_pts_3d[:, 0] )
max_y = np.max( array_pts_3d[:, 1] )
bbox = min_x, min_y, max_x, max_y
return bbox
def raster(list_pts_3d, jparams):
'... | The code performs Inverse Distance Weighting (IDW) interpolation on 3D input points to generate a raster output. It calculates distances between raster cells and sample points, applies IDW with a specified power and radius, assigns interpolated values to valid cells within the convex hull, and marks cells outside the h... | def idw_interpolation(list_pts_3d, j_idw):
"""
Function that writes the output raster with IDW
Input:
list_pts_3d: the list of the input points (in 3D)
j_idw: the parameters of the input for "idw"
Output:
returns the value of the area
"""
## PREPARATION #... |
def raster(list_pts_3d, jparams):
'''
RASTER
Input: list of points x, y, z
Output: [(x1,y1), (x2,y2), ...., (xn, yn)] or
[[x1,y1], [x2,y2], ...., [xn, yn]]
'''
#Bbox for raster input, extracting max_x, max_y
bbox_raster = bbox(list_pts_3d)
min_x, min_y, max_x, max_y = bbox_ra... | The function `tin_interpolation` performs linear interpolation on a Triangulated Irregular Network (TIN) to generate a raster grid. It takes 3D input points and TIN parameters, constructs a Delaunay triangulation, and interpolates z-values for each raster cell using barycentric coordinates within the corresponding tria... | def tin_interpolation(list_pts_3d, j_tin):
"""
!!! TO BE COMPLETED !!!
Function that writes the output raster with linear in TIN interpolation
Input:
list_pts_3d: the list of the input points (in 3D)
j_tin: the parameters of the input for "tin"
Output:
retur... |
def bbox_np(array_pts_3d):
# NumPy implementation of bbox
min_x = np.min( array_pts_3d[:, 0] )
min_y = np.min( array_pts_3d[:, 1] )
max_x = np.max( array_pts_3d[:, 0] )
max_y = np.max( array_pts_3d[:, 1] )
bbox = min_x, min_y, max_x, max_y
return bbox
def raster(list_pts_3d, jparams):
'... | The function performs ordinary kriging interpolation on 3D input points to generate a raster output. It calculates distances between raster cells and sample points, applies variogram models, solves linear systems for weights, and assigns interpolated values while handling edge cases like out-of-bounds points or numeric... | def kriging_interpolation(list_pts_3d, j_kriging):
"""
!!! TO BE COMPLETED !!!
Function that writes the output raster with ordinary kriging interpolation
Input:
list_pts_3d: the list of the input points (in 3D)
j_kriging: the parameters of the input for "kriging"
Ou... |
def add_objects(object_class):
object_list = _extract_objects(object_class)
for obj in object_list:
import_objects(out_db, [(object_class, obj)])
def read_translation_file(object_class):
translation_df = pd.read_excel(translation_file, object_class)
translation_df = translation_df.transpose().to... | The function `create_objects` processes and imports objects of a specified class into a database. It reads translation parameters, constructs parameter names and values, and imports them using helper functions. The main task involves preparing and storing object-class-specific parameters and their associated values in ... | def create_objects(object_class):
print("adding objects of class "+object_class)
add_objects(object_class)
to_add = {}
translation_parameters = read_translation_file(object_class)
for i in translation_parameters:
to_add = add_modified_parameter_object(to_add,translation_parameters[i][0],tr... |
def run_cluster(self, flag, size):
self.text_vec = []
self.topic_serial = []
self.topic_cnt = 0
if flag == 1 or flag == 2:
self.text_vec = self.done_data
self.topic_serial = copy.deepcopy(self.done_label)
self.topic_cnt = max(self.topic_serial)
... | The main task of the code is to initialize a clustering environment with dynamic threshold determination using a reinforcement learning agent. It processes input data, computes pseudo-labels, selects actions via an agent to adjust the similarity threshold, and performs clustering based on the flag parameter. The code h... | def __init__(self, sim_threshold, data, flag, label, size, agent, para, sim_init, sim=False, global_step=0):
self.device = torch.device('cuda:0')
self.text_vec = None #
self.topic_serial = None
self.topic_cnt = 0
self.sim_threshold = sim_threshold
self.done_data... |
def getFilename(FILE_NAME, noext=0):
FileFormat='.xls'
if FileFormat in FILE_NAME:
FileName, extension = str(FILE_NAME).split(FileFormat)
return FileName if noext else FileName+FileFormat+extension
else:
return FILE_NAME if noext else FILE_NAME+'.xlsx'
def getsubplots( subplot, pno=0... | The code processes an input Excel file containing plot data, organizes plots and subplots into a structured dictionary, generates new Excel files with processed data, and optionally validates against a manual check file. It tracks progress, handles missing plots, and outputs two Excel files: one with all plots and anot... | def agriplot(FILE_NAME, checkfile=''):
'''
Generates Excel file from Plot data file.
Optionally, Pass the Excel file having manually done Plot sequences in the parameter 'check=' to check with the generated sequences.
'''
#print(vars(sys.modules[__name__])['__package__'])
global FileFullPath
... |
def getFilename(FILE_NAME, noext=0):
FileFormat='.xls'
if FileFormat in FILE_NAME:
FileName, extension = str(FILE_NAME).split(FileFormat)
return FileName if noext else FileName+FileFormat+extension
else:
return FILE_NAME if noext else FILE_NAME+'.xlsx'
def getNumber(cstr): # Get Numb... | The function `agriplot` generates Excel files from agricultural plot data, processing plot and subplot sequences from an input file. It optionally validates generated sequences against a manual check file. The code reads Excel data, organizes plots/subplots into a dictionary, tracks progress via a GUI progress bar, han... | def agriplot(FILE_NAME, checkfile='', cwindow='', args=''):
global Txtbox
'''
Generates Excel file from Plot data file.
Optionally, Pass the Excel file having manually done Plot sequences in the parameter 'check=' to check with the generated sequences.
'''
#print(vars(sys.modules[__name__])['__p... |
def getArg(usagestr='', customarg=''): # Gives arguments & Takes Single Custom Arg. optionally
args = sys.argv[1:] # Exclude Filename from obtained Arguments list
if len(args) < 1:
print(usagestr)
return {}
else:
if len(args) > 2:
if customarg:
if args[1] ... | The main task of the code is to parse and format a list of subplots from user input by generating all possible subplot sequences. It processes comma-separated subplot identifiers, removes brackets, and organizes them numerically. The output lists formatted subplots with indentation and highlights input subplots, ensuri... | def getsubplotscmd():
Usgstr='''
Usage : Pass the Subplots of a Plot separated by comma in any order to get All the Possible Subplots in Sequence
getsubplotscmd Comma-Separated-SubPlots
e.g. getsubplotscmd 6A,6,2C3B,10,7A1,4D5C3B1
'''
argDict=getArg(usagestr=Usgstr, customa... |
def getArg(usagestr='', customarg=''): # Gives arguments & Takes Single Custom Arg. optionally
args = sys.argv[1:] # Exclude Filename from obtained Arguments list
if len(args) < 1:
print(usagestr)
return {}
else:
if len(args) > 2:
if customarg:
if args[1] ... | The function `selectplotscmd` processes input to select plots either by specifying a count ("Total Number of Plots/Last SNo.") or a filename. It retrieves arguments, validates input, and either generates selected plot serial numbers from a count or processes a file to mark plots, outputting results accordingly. | def selectplotscmd():
global FileFullPath, startRow, plotsDF
Usgstr='''
Usage : Takes 'Total Number of Plots/Last SNo.' and Gives the Selected Plots
OR
Takes FileName and Marks the Selected Plots
selectplotscmd Number-of-Plots/Last-SNo OR FILENAME
e.g.... |
def getFilename(FILE_NAME, noext=0):
FileFormat='.xls'
if FileFormat in FILE_NAME:
FileName, extension = str(FILE_NAME).split(FileFormat)
return FileName if noext else FileName+FileFormat+extension
else:
return FILE_NAME if noext else FILE_NAME+'.xlsx'
def agriplot(FILE_NAME, checkfi... | The code defines a function `RunProg()` that executes different agricultural survey programs based on user input. It validates inputs, processes data (e.g., Excel files, plot selections, subplot divisions), generates outputs, and updates GUI elements like status labels and text boxes. The function handles three modes: ... | def RunProg():
global window, cwindow, singleVar, name_entry, stratumVar, osVar, Txtbox, errorMsg, plotsDF, n
plotsDF = pd.DataFrame(columns=['plotNo','subplot','sno','status']); n=0
currentProgram = list(programs.keys())[int(radVal.get())-1]
print('Running ...',list(pr... |
def get_default_device():
if torch.cuda.is_available():
return torch.device('cuda')
# For multi-gpu workstations, PyTorch will use the first available GPU (cuda:0), unless specified otherwise
# (cuda:1).
if torch.backends.mps.is_available():
return torch.device('mos')
return ... | The code trains an MLP on the CIFAR10 dataset using PyTorch, applying image transformations (resizing, grayscale, normalization), loading data with custom caching, and logging training/validation accuracy and model norm via TensorBoard. It uses stochastic gradient descent for optimization over 50 epochs with batched da... | def main(device=get_default_device()):
transforms = [
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
v2.Resize((28, 28), antialias=True),
v2.Grayscale(),
torch.flatten,
]
data_path = '../data'
train_dataset = CIFAR10(root=data_path, train=True, transform=v2... |
def get_default_device():
if torch.cuda.is_available():
return torch.device('cuda')
if torch.backends.mps.is_available():
return torch.device('mps')
return torch.device('cpu')
def get_dataset(data_path: str, train: bool):
initial_transforms = v2.Compose([
v2.ToImage(),
v2... | The code trains a PreResNet-56 model on a dataset (e.g., CIFAR-10) using PyTorch, with GPU optimization. It initializes training/validation loaders, configures a SGD optimizer with Nesterov momentum, and a learning rate scheduler. The model is trained for 500 epochs, saving the best validation-performing checkpoint. Th... | def main(device: torch.device = get_default_device(), data_path: str = './data', models_path: str = "./models"):
os.makedirs(models_path, exist_ok=True)
if device.type == 'cuda':
torch.backends.cudnn.benchmark = True
torch.backends.cuda.matmul.allow_tf32 = True
train_dataset = get_dataset(d... |
def _getVandE(self, lambd):
self.potential = lambd[:self.n_points]
return lambd[:self.n_points], lambd[self.n_points:]
def diagonalize(self, eps=None):
if eps is None:
eps = self.eps_matrix
# Find subspaces and subsets of eps with same l and j (dictionaries)
subspaces... | The code solves a linear system using least-squares with sparse matrix techniques, computes epsilon and potential matrices, diagonalizes the epsilon matrix, shifts the potential, calculates an integral, and writes results to files. It handles precision, iterations, and symmetry in the solution process. (100 words) | def solve(self, max_prec=True, tol=1e-10, max_iter=10000, diag=True, shift=True, cost=None):
# Build sparse matrix
self.A_sparse = csc_matrix(self.A, dtype=float)
# Solve with least-squares
if max_prec:
x, istop, itn, r1norm = lsqr(self.A_sparse, self.b, atol=0., btol=0., con... |
def solve(self, max_prec=True, tol=1e-10, max_iter=10000, diag=True, shift=True, cost=None):
# Build sparse matrix
self.A_sparse = csc_matrix(self.A, dtype=float)
# Solve with least-squares
if max_prec:
x, istop, itn, r1norm = lsqr(self.A_sparse, self.b, atol=0., btol=0., con... | The code computes a potential value `v` by solving a problem (`self.solve()`), retrieving values `v` and `eps` from the solution, and optionally adjusting `v` via `shiftPot(cost)` if `shift=True`. It returns the computed potential `v` after any specified adjustment. | def getPotential(self, shift=True, cost=None):
x = self.solve()
v,eps = self._getVandE(x)
if shift: self.shiftPot(cost)
return v |
def is_logged_in(self):
wd = self.app.wd
return len(wd.find_elements(By.LINK_TEXT, locator.logout)) > 0
def is_logged_in_as(self, username):
wd = self.app.wd
return self.get_logged_user() == username
def logout(self):
wd = self.app.wd
wd.find_element(By.LINK_TEXT, locator... | The main task of the code is to ensure a user is logged in with the specified username and password. It checks if the user is already logged in; if so, it verifies the username. If not, it logs out. Finally, it logs in using the provided credentials, ensuring the session matches the given username and password. | def ensure_login(self, username, password):
wd = self.app.wd
if self.is_logged_in():
if self.is_logged_in_as(username):
return
else:
self.logout()
self.login(username, password) |
def selection(self, state):
poss_next_state = [0]*len(state.children)
pos = 0
for child in state.children:
if(child.num_visits == 0):
return child
else:
if(state.player == 1):
poss_next_state[pos] = ((child... | The main task of the code is to traverse a tree structure starting from a given state. It iteratively selects child nodes until reaching a leaf node (a state with no children). If the leaf node can be expanded, it triggers expansion; otherwise, it performs a rollout using available actions to evaluate the node's value.... | def tree_policy(self, start_state):
current_state = start_state
while(current_state.children):
next_state = self.selection(current_state)
current_state = next_state
if(current_state.rollout):
self.expansion(current_state)
else:
self.rollou... |
def getDirectionAlongPheromone(self, fov: np.ndarray, pheromone, target_direction=None, cell_type=None, erode=False):
if target_direction is None:
target_direction = self.exploreDirection
use_gradient = pheromone != self.currentTrail
if pheromone != 0:
visible_area = fo... | The code implements ant pathfinding using pheromones for navigation. In 'EXPLORE' mode, ants randomly search for food or follow food pheromones; in 'GO_HOME' mode, they follow home pheromones. When encountering obstacles, they adjust direction. Upon finding food, ants switch to returning home, drop it at the nest, and ... | def pheromonePathFinding(self, delta_t):
"""
When searching for food:
When no pheromone present, move with a random wiggle
When returning home:
Get the vector from the current position and home position
move in that straight line
In general:
... |
def showWalls():
for i in range(0,600,wallSize):
screen.blit(wallImage, (i,0))
screen.blit(wallImage, (i,600 - wallSize))
screen.blit(wallImage, (0, i))
screen.blit(wallImage, (600 - wallSize, i))
def collisWall():
if (snake.elements[0][0] > 600 - wallSize or snake.elements[0][0]... | The main task of the code is to handle collision detection in a snake game's second level. It checks if the snake's head collides with its body or the second snake's body, triggering a game-over screen and ending the level if true. The function also manages wall collisions, updates game state, and sets the frame rate (... | def secondLevelMain():
showWalls()
collisWall()
for i in range(1, snake.size):
if snake.elements[0] == snake.elements[i]:
gameOverScreen()
secondLevel = False
if twoSnake:
for i in range(1, snake2.size):
if snake2.elements[0] == snake2.elements[i]:
... |
def showWalls():
for i in range(0,600,wallSize):
screen.blit(wallImage, (i,0))
screen.blit(wallImage, (i,600 - wallSize))
screen.blit(wallImage, (0, i))
screen.blit(wallImage, (600 - wallSize, i))
def collisWall():
if (snake.elements[0][0] > 600 - wallSize or snake.elements[0][0]... | The main task of the code is to manage the third level of a game by checking collisions between snakes and walls, detecting self-collisions for both the primary and secondary snakes, and triggering a game-over screen if collisions occur. It maintains a frame rate of 60 FPS to control game speed. | def thirdLevelMain():
showWalls()
collisWall()
for i in range(1, snake.size):
if snake.elements[0] == snake.elements[i]:
gameOverScreen()
thirdLevel = False
if twoSnake:
for i in range(1, snake2.size):
if snake2.elements[0] == snake2.elements[i]:
... |
def _bytes2str(x):
"""Convert bytes to str, if needed."""
if isinstance(x, bytes):
x = x.decode('utf-8')
return x
def get_random_seq(self,
class_type,
seq_len,
labeling='ordered',
randomly_generate_rare=False,
... | This function generates bursty or non-bursty sequences with embedded few-shot problems, using parameters like shot count, class distribution (common/rare/Zipfian), and probabilities. It yields sequences containing either rare/common classes or Zipfian-distributed examples, combining bursty few-shot segments with non-bu... | def get_bursty_seq(self,
seq_len,
shots,
ways,
p_bursty,
p_bursty_common=0.,
p_bursty_zipfian=0.,
non_bursty_type='common_uniform',
labeling_common='ord... |
def print_parameters(google_api_key, google_engine_id, openai_secret_key, method, r, t, k, q):
"""
print the parameters given by user
:param google_api_key: google_api_key
:param google_engine_id: google_engine_id
:param openai_secret_key: openai_secret_key
:param method: -spanBert
:param r:... | The main task of the code is to iteratively retrieve and extract relations from web search results using Google and OpenAI APIs, employing either SpanBERT or GPT-3 for processing. It generates queries, collects links, extracts data, and filters relations by confidence until at least `k` relations are obtained. The proc... | def main():
"""
main process to call the step 1 to 6
:return: return result tuples X
"""
# if the sys.args are not equal to 0, print error message and exit
if len(sys.argv) != 9:
print(
"Usage: python project.py [-spanbert|-gpt3] <google api key> <google engine id> <openai se... |
def receive_input(query, search_engine, json_api):
'''
Get http response from user input query
:param query: from user input query
:param search_engine: search_engin_key
:param json_api: json api key
:return: user's response
'''
# formate the url
url = "https://www.googleapis.com/cus... | The code's main task is to iteratively refine a search query by expanding it based on API response precision until a target precision threshold is met. It starts by taking user input, queries a search engine, checks the precision of results, and if below a target score, expands the query and repeats. The process exits ... | def main():
print("Please type the search words: ")
query = input().lower()
print("Query: ", query)
while True:
resp = receive_input(query, SEARCH_ENGINE, JSON_API)
if resp.status_code != 200:
print('request failed, please retry!')
exit()
# get items list ... |
def spawnCells(self):
if self.energy >= self.model.spawn_freq:
self.model.currentIDNum += 1
newCell = StemCell(self.model.currentIDNum , self.model)
self.model.schedule.add(newCell)
self.model.space.place_agent(newCell , self.pos)
self.energy = self.en... | The code's main task is to execute a simulation step by spawning cells, handling their movement, and conditionally triggering cell differentiation if the model's "sauce" flag is active. The method orchestrates cell generation, movement logic, and differentiation processes, which are critical for modeling dynamic cellul... | def step(self):
self.spawnCells()
self.movement2()
if self.model.sauce == True:
self.differentiation_tick() |
def setup_environment():
global directory_path, processed_data_file, sequence_length
directory_path = 'stock_data'
processed_data_file = 'processed_data.parquet'
sequence_length = 10
def load_and_prepare_data():
loader = DataLoader(directory_path, processed_data_file)
combined_data = loader.load... | The main task of the code is to train and evaluate machine learning models for stock prediction using historical data, then perform continuous real-time predictions for specific tickers. It loads and prepares data, trains models on selected tickers, evaluates them on test data, and executes real-time predictions for "A... | def main():
setup_environment()
train_data, test_data = load_and_prepare_data()
if train_data is not None:
train_tickers = get_unique_tickers(train_data)
test_tickers = get_unique_tickers(test_data)
# To test otherwise take the defined above (test_tickers).
tickers = ['ARI', ... |
def send_turn(connection, robot, to_send):
assert to_send in [SERVER_TURN_LEFT, SERVER_TURN_RIGHT]
# print("Sending:", to_send)
connection.sendall(to_send)
message = extract_message(connection, robot, "OK")
x, y = check_ok_message(connection, robot, message)
if to_send == SERVER_TURN_LEFT:
... | The function `turn_and_move` navigates a robot to a specified goal coordinate by first determining the direction of movement (x or y axis), rotating the robot to face the correct direction, and then moving it step-by-step along that axis until it reaches the target. It ensures the robot's position remains unchanged dur... | def turn_and_move(x_or_y, connection, robot, goal_coordinates):
if (robot.x, robot.y) == goal_coordinates:
return
x_dir_to_move = 1 if robot.x < goal_coordinates[0] else (-1 if robot.x > goal_coordinates[0] else 0)
y_dir_to_move = 1 if robot.y < goal_coordinates[1] else (-1 if robot.y > goal_coordi... |
def get_selected_headings(self):
headings = []
for index in self.listbox.curselection():
headings.append(self.listbox.get(index))
return headings
def save(self):
self.articles[self.index]["history_section_name"] = self.get_selected_headings()
with open(self.sample_fil... | The method `yes` checks if selected headings exist; if so, it updates the article's label, saves changes, and triggers a search. If no headings are selected, it changes the color. | def yes(self):
if self.get_selected_headings():
self.articles[self.index][self.to_label] = True
self.save()
self.find()
else:
self.change_color() |
def get_selected_headings(self):
headings = []
for index in self.listbox.curselection():
headings.append(self.listbox.get(index))
return headings
def save(self):
self.articles[self.index]["history_section_name"] = self.get_selected_headings()
with open(self.sample_fil... | This method checks if there are no selected headings. If true, it updates the current article's label to False, saves the change, and searches for the next item. If headings exist, it alters the color of an element, likely for visual feedback or state indication. | def no(self):
if not self.get_selected_headings():
self.articles[self.index][self.to_label] = False
self.save()
self.find()
else:
self.change_color() |
def get_selected_headings(self):
headings = []
for index in self.listbox.curselection():
headings.append(self.listbox.get(index))
return headings
def save(self):
self.articles[self.index]["history_section_name"] = self.get_selected_headings()
with open(self.sample_fil... | The function `na` checks if there are no selected headings. If true, it sets a specific article entry to `None`, saves the changes, and triggers a search. If headings are selected, it alters the color. The core tasks involve conditional data modification, saving, searching, and visual state adjustment based on selectio... | def na(self):
if not self.get_selected_headings():
self.articles[self.index][self.to_label] = None
self.save()
self.find()
else:
self.change_color() |
def UT_BITS_IN_BYTES(b):
return (int(b) + 7) // 8
def dict_table_is_comp(table):
return table['flags'] & DICT_TF_COMPACT
def dict_index_get_nth_field(index, pos):
return index['fields'] + pos
def dict_field_get_col(field):
return field['col']
def DATA_BIG_COL(col):
return DATA_BIG_LEN_MTYPE(col['len... | This code calculates and initializes field offsets in a compact record format, handling nullable fields, variable-length data, and external storage flags. It iterates through fields, adjusts offsets based on nullability and data size, and populates the offsets array with computed positions for efficient record storage ... | def rec_init_offsets_comp_ordinary(rec, temp, index, offsets):
i = 0
offs = 0
any_ext = 0
n_null = index['n_nullable']
nulls = rec - 1 if temp else rec - (1 + REC_N_NEW_EXTRA_BYTES)
lens = nulls - UT_BITS_IN_BYTES(n_null)
null_mask = 1
if (temp and dict_table_is_comp(index['table']... |
def rec_offs_comp(offsets):
return offsets[REC_OFFS_HEADER_SIZE] & REC_OFFS_COMPACT
def rec_offs_n_fields(offsets):
return offsets[1];
def rec_get_info_bits(rec, comp):
return rec_get_bit_field_1(
rec, REC_NEW_INFO_BITS if comp else REC_OLD_INFO_BITS,
REC_INFO_BITS_MASK,... | The main task of the code is to convert a record (`rec`) and its offsets (`offsets`) into a formatted string describing the physical record's structure. It checks if the offsets are compatible with the compact format; if not, it returns a placeholder for an old format. Otherwise, it constructs a string with metadata (n... | def rec_to_str(rec, offsets):
if not rec_offs_comp(offsets):
return "TODO: implement old format"
res = (("PHYSICAL RECORD: n_fields {};" +
" compact format; info bits {}\n").format(
rec_offs_n_fields(offsets),
rec_get_info_bits(rec, True)))
res += rec_comp_to_s... |
def page_is_comp(page):
return int(page[PAGE_HEADER + PAGE_N_HEAP]) & 0x80
def rec_get_heap_no_new(rec):
return rec_get_bit_field_2(rec, REC_NEW_HEAP_NO,
REC_HEAP_NO_MASK, REC_HEAP_NO_SHIFT)
def rec_get_next_offs(rec,comp):
field_value = mach_read_from_2(rec - REC_NEXT)
... | This function searches a database page for a record with a specified heap number. It traverses records either in compressed (new) or non-compressed (old) format, checking each record's heap number against the target. If found, it returns the record's address; if reaching the supremum record (end marker) without a match... | def page_find_rec_with_heap_no(page, heap_no):
if page_is_comp(page):
rec = page + PAGE_NEW_INFIMUM
while True:
rec_heap_no = rec_get_heap_no_new(rec)
if rec_heap_no == heap_no:
return rec
elif rec_heap_no == PAGE_HEAP_NO_SUPREMUM :
... |
def rec_offs_make_valid(rec,index,offsets):
offsets[2] = ptr_to_ulint(rec)
offsets[3] = ptr_to_ulint(index)
def dict_table_is_comp(table):
return table['flags'] & DICT_TF_COMPACT
def rec_get_status(rec):
return rec_get_bit_field_1(rec, REC_NEW_STATUS,
REC_NEW_STATUS_MAS... | The function initializes record offsets for a compressed database table, handling different record statuses (infimum, node pointer, ordinary) and field attributes. It calculates byte positions for each field, accounting for nullability, variable-length data, and compression specifics, updating the offsets array with co... | def rec_init_offsets(rec, index, offsets):
i= 0
rec_offs_make_valid(rec, index, offsets)
if (dict_table_is_comp(index['table'])):
status = rec_get_status(rec)
n_node_ptr_field = ULINT_UNDEFINED
if status == REC_STATUS_INFIMUM:
offsets[REC_OFFS_HEADER_SIZE] = REC_N_NEW_E... |
def buf_pool_get(space_id, page_no):
page_id = fold(space_id, page_no >> 6)
f = gdb.selected_frame()
buf_pool_ptr = f.read_var("buf_pool_ptr")
srv_buf_pool_instances = f.read_var("srv_buf_pool_instances")
return buf_pool_ptr[page_id % srv_buf_pool_instances]
def buf_hash_page_get(buf_pool, space_id,... | This function retrieves a specific page from a buffer pool using the provided space ID and page number, then returns the corresponding block data by fetching the page from the hash table and extracting its block. | def buf_page_try_get(space_id, page_no):
buf_pool = buf_pool_get(space_id, page_no)
bpage = buf_hash_page_get(buf_pool, space_id, page_no)
return buf_page_get_block(bpage) |
def dict_table_is_comp(table):
return table['flags'] & DICT_TF_COMPACT
def rec_get_status(rec):
return rec_get_bit_field_1(rec, REC_NEW_STATUS,
REC_NEW_STATUS_MASK, REC_NEW_STATUS_SHIFT)
def dict_index_get_n_fields(index):
return index['n_fields']
def dict_index_get_n_uniqu... | This function computes and initializes record offsets for a database entry based on its status (ordinary, node pointer, infimum/supremum) and table type (compressed or old format). It determines the number of fields, sets offset array properties, and returns the configured offsets for record processing. | def rec_get_offsets(rec,index,offsets,n_fields):
if dict_table_is_comp(index['table']):
status = rec_get_status(rec)
if status == REC_STATUS_ORDINARY:
n = dict_index_get_n_fields(index);
elif status == REC_STATUS_NODE_PTR:
n = dict_index_get_n_unique_in_tree_nonleaf(i... |
def buf_page_try_get(space_id, page_no):
buf_pool = buf_pool_get(space_id, page_no)
bpage = buf_hash_page_get(buf_pool, space_id, page_no)
return buf_page_get_block(bpage)
def buf_block_get_frame(block):
return block["frame"]
def page_find_rec_with_heap_no(page, heap_no):
if page_is_comp(page):
... | This function extracts detailed information about record locks in a database, filtering by space/page numbers and heap_no. It retrieves index/table names, lock type, and constructs a list of record-specific data (heap_no, memory pointers, offsets, and string representations) from the lock map, returning structured meta... | def get_lock_info(lock, space_no = None, page_no = None, heap_no_arg = None):
rec_lock = lock["un_member"]["rec_lock"]
if space_no is not None and rec_lock["space"] != space_no:
return None
if page_no is not None and rec_lock["page_no"] != page_no:
return None
index = lock["index"]
table... |
def read_image_from_dataurl64(dataurl):
image_bytes = base64.b64decode(str(dataurl[dataurl.find(",") + 1:]))
image = np.asarray(Image.open(io.BytesIO(image_bytes)))
return image
def highlight_a_patch(image, row, col, patch_size, width=3, c=[255, 230, 10]):
c = copy.copy(c)
if col < 0:
retur... | The code retrieves and visualizes attention data for a specific token in transformer models (BERT, ViT-32/16, GPT). It processes token positions, highlights image patches, overlays attention maps, and returns attention scores, normalized values, and modified token data with visual annotations for analysis. | def get_attention_by_token(self, token, model):
print(model)
layer = token['layer']
head = token['head']
index = token['index']
# get info for the clicked on token
if model == "bert":
all_token_info = self.token_data_bert['tokens'][index]
offset =... |
def parse_args(args):
docs_tarball_url_default = "https://docs.kicad.org/kicad-doc-HEAD.tar.gz"
parser = argparse.ArgumentParser(description='Build and package KiCad for macOS. Part of kicad-mac-builder.',
epilog="Further details are available in the README file.")
pars... | The main task of the code is to configure the build environment by locating Homebrew-installed `gettext` and `bison` tools, updating the system PATH, and initiating a build process with parsed command-line arguments. It prints setup details, warns about resource requirements, and allows termination via Control-C. | def main():
parsed_args = parse_args(sys.argv[1:])
print_summary(parsed_args)
gettext_path = "{}/bin".format(subprocess.check_output("brew --prefix gettext", shell=True).decode('utf-8').strip())
bison_path = "{}/bin".format(subprocess.check_output("brew --prefix bison", shell=True).decode('utf-8').strip... |
def parse_args(arg_list=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="modify output verbosity",
action="store_true")
parser.add_argument("-q", "--quiet", help="Reduce output",
action="store_true")
subparser... | The main task of the code is to handle command-line arguments for signing or notarizing an app. It adjusts logging verbosity, trims the input path if necessary, and delegates tasks to `handle_signing` or `handle_notarization` based on the subparser name, using parameters like certificate details, entitlements, and Appl... | def main():
args = parse_args()
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
if args.quiet:
logging.getLogger().setLevel(logging.WARNING)
else:
logging.getLogger().setLevel(logging.INFO)
if args.path.endswith(".app/"):
args.path = args.path[:-1]
... |
def calc_angles_per_frame(hand_data, pose):
hand_data = np.array(hand_data)
angles = calc_hand_angle_midpoint(hand_data, pose)
return np.array(angles)
def calc_distance_per_frame(hand_data):
# Loop over the frames in list comprehension, compute distance features for each frame
distance_per_frame = [... | The function `get_wrist_angle_distance` extracts hand features from landmarks by calculating angles, distances, and wrist positions, appending relative fingertip coordinates (for middle/ring fingers) and velocity. It combines these into a feature vector for each frame, enabling gesture or motion analysis. | def get_wrist_angle_distance(lmrks, key, pose = None):
lmrk = lmrks[key] # Get the specified hand
left = key == 'l_hand'
# Replace the Hand model's fingertip coords if possible with the Pose model
# Because the Pose model of Mediapipe is more accurate
# The Pose model only keeps track of the wrist,... |
def check_fleet_edges(ai_settings, aliens, shipSide=""):
"""Respond appropriately if any alien has reached the edge."""
for alien in aliens.sprites():
if alien.check_edges(shipSide):
change_fleet_direction(ai_settings, aliens)
break
def check_aliens_bottom(screen,
... | The function updates alien positions by checking fleet edges and moving aliens. It detects collisions between the ship and aliens or aliens reaching the screen bottom, then triggers the ship_hit function to handle damage, reset alien positions, and manage remaining ship lives. | def update_aliens(ai_settings,
screen,
stats,
aliens,
ship,
bullets,
shipSide="",
bulletsSide=""):
"""
Check if the fleet is at an edge,
and update the position of all aliens in... |
def contact_type(text):
text = text.lower()
if text.find('enter') != -1 or text.find('interior') != -1 or text.find('ingress') == -1:
return 'enter'
elif text.find('leave') != -1 or text.find('left') != -1 or text.find('egress') == -1:
return 'left'
else:
... | The code decodes a tweet by extracting its text, contact type, latitude, longitude, user, and contact time, then writes these details into a CSV row. It handles exceptions by printing errors to stderr. | def decode_tweet(id, tweet):
try:
text = tweet['text']
ctype = contact_type(text)
lat, lng = lat_lng(tweet)
out.writerow([id, tweet['text'], tweet_user(tweet), ctype, lat, lng] + list(contact_time(tweet)))
except Exception as e:
print("decode %... |
def rhosinfi(Lat,Hgt):
U=math.atan(math.tan(rad*Lat)*0.99664719)
rhosfi=0.99664719*math.sin(U)+(Hgt/6378140)*math.sin(Lat*rad)
return rhosfi
def rhocosfi(Lat,Hgt):
U=math.atan(math.tan(rad*Lat)*0.99664719)
rhocfi=math.cos(U)+(Hgt/6378140)*math.cos(Lat*rad)
return rhocfi
d... | The code calculates a specific time value (time[Phase]) by iteratively solving equations involving polynomial coefficients (e), geographic parameters (Long, Lat), and physical constants (Par, DET). It computes adjustments (dx, dy) using trigonometric functions and updates time (T) through iterations. The result incorpo... | def CalculateTime(e,Long,Lat,Par,Phase):
Tau=0
L=0
fuso=0
DET=67
Hgt=10
rsf=rhosinfi(Lat,Hgt)
rcf=rhocosfi(Lat,Hgt)
T=0
for k in range(5):
for rip in range(7):
Xa=e['11']+e['12']*T+e['13']*(T*T)+e['14']*(T*T*T)
... |
def load_traj(self, data_dir: str, pdb: str, psf: str, trajs: List[str], selection: str):
assert (pdb is not None) or (psf is not None), "At least either PDB of PSF should be provided..."
assert trajs is not None, "DCD(s) must be provided"
top = pdb if (pdb is not None) else psf
top = os... | The main task of the code is to initialize a class by loading molecular dynamics (MD) data, including coordinates and temperatures, from specified directories. It processes PDB files, validates them, and loads coordinates using MDAnalysis or mdtraj. The code handles both trajectory-based and directory-based data loadin... | def __init__(self, args: argparse.ArgumentParser, directories: str=None, image_stats: collections.namedtuple=None):
super().__init__()
[setattr(self, key, val) for key, val in args.__dict__.items()]
# self.files_to_pg = list(map(lambda inp: os.path.join(self.data_dir, inp), os.listdir(self.data_... |
def get_rules(nuke=None):
rules = (list(), list())
with open(get_gitignore_path()) as f:
ignore = False
for line in f.readlines():
line = line.strip()
if not line or len(line) <= 0 or line[0] == '#':
if not nuke and line[:7] == '#:gnore':
... | The function `clean` traverses directories, skips `.git` and ignored paths, and removes files/dirs based on rules, with optional forced deletion via the `nuke` flag and verbose output control. | def clean(nuke=False, verbose=False):
for rule in get_rules(nuke=nuke)[0]:
for root, dirs, files in os.walk(getcwd()):
matches = re.findall(r'\.git(?![^\/])', root)
if len(matches) > 0:
continue
if nuke or not is_gnored(root):
rimraf(root, ... |
def track_state(self):
track_state_1 = []
track_state_2 = []
for i in range(0, self.tracker.__len__()):
if self.tracker[i].__len__() == 0: # Check if that arm has been pulled at all and there's a result
track_state_1.append(0) # State 1: If nothing has been pulled, ... | The function initializes a tracker for probabilistic leading arm selection, iterates over tests, and determines arm-pulling strategies based on state checks. It appends states to the tracker, selects random arms when all states are zero, and applies biased or unbiased selection otherwise, finally returning test results... | def build_states_prob_lead(self):
self.tracker = []
print("The status of tracker in prob_lead before instantiation: ", self.tracker.__len__())
for i in range(0, self.num_bands):
self.tracker.append([])
print("The status of tracker in prob_lead after instantiation: ", self.tra... |
def build_states_prob_lead(self):
self.tracker = []
print("The status of tracker in prob_lead before instantiation: ", self.tracker.__len__())
for i in range(0, self.num_bands):
self.tracker.append([])
print("The status of tracker in prob_lead after instantiation: ", self.tra... | The code initializes a class for simulating and analyzing multi-armed bandit problems, setting up parameters like the number of bands, tests, and bias checks. It constructs probability distributions for "lead" and "random" strategies, calculates intervals, and prepares data structures to track arm selections and odds. ... | def __init__(self, num_bands=3, n_tests=10000, bias_check_1 = 0):
self.n_tests = n_tests
self.num_bands = num_bands
self.row = many_bandits(self.num_bands).mab
self.num_r = self.row.__len__()
self.interval = 1 / self.num_r
self.arms_picked = []
self.bias_check_1 ... |
def create_temp_table_name_and_location(self, name = ''):
table_name = 'duck_engine_' + datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(datetime.datetime.now().microsecond)
if name:
table_name = name.replace(".", "_") + '_' + table_name
temp_s3_location = self.temp_results_bucket.strip('/') + '... | This function converts a SQL query result into a temporary AWS Glue table by exporting the query output to a Parquet file in S3, creating a view from the Parquet data, retrieving column metadata, and then constructing a temporary Glue table using the Parquet file and column information. | def query_to_glue_table(self, query):
try:
name, location = self.create_temp_table_name_and_location()
converted_query = f"copy ({query} ) to '{location}/result.parquet'"
cursor = self.get_cursor_with_s3_credentials()
cursor.execute(converted_query)
cursor.execute(f"create view {name} ... |
def log_error(self, err):
pass
def get_cursor_with_s3_credentials(self):
sts = aws_helper.get_thread_safe_client('sts')
roleCreds = aws_helper.retry_api_call(lambda: sts.assume_role(RoleArn=self.iam_role,RoleSessionName=self.iam_role_name))
access_key = roleCreds['Credentials']['AccessKeyId']
secret... | This function executes a Redshift query, waits for completion, creates a temporary Redshift view from S3 parquet data, extracts schema info, generates a temporary Glue table, and returns its name while cleaning up the view. It handles query failures and ensures temporary resources are removed. | def _create_temporary_glue_from_redshift_statement(self, statement, table_name, s3location):
query_id = statement['Id']
redshift_data = aws_helper.get_thread_safe_client('redshift-data')
while True:
result_status = redshift_data.describe_statement(Id=query_id)
if result_status['Status'] == '... |
def _relation_created(self, relation_name: str) -> bool:
"""Returns whether a given Juju relation was crated.
Args:
relation_name (str): Relation name
Returns:
bool: Whether the relation was created.
"""
return bool(self.model.relations[relation_name])
d... | The main task of the code is to configure the NRF service by checking prerequisites like container readiness, database availability, certificate storage, and required relations. It updates the Juju unit status based on these checks, defers events when conditions are unmet, generates configuration files, and activates t... | def _configure_nrf(self, event: EventBase) -> None:
"""Adds pebble layer and manages Juju unit status.
Args:
event: Juju event
"""
if not self._container.can_connect():
self.unit.status = WaitingStatus("Waiting for container to be ready")
event.defer(... |
def _csr_is_stored(self) -> bool:
"""Returns whether CSR is stored in workload."""
return self._container.exists(path=f"{CERTS_DIR_PATH}/{CSR_NAME}")
def _get_stored_csr(self) -> str:
"""Returns stored CSR."""
return str(self._container.pull(path=f"{CERTS_DIR_PATH}/{CSR_NAME}").read())
d... | This method handles certificate availability by verifying container connectivity, ensuring a stored CSR matches the event's CSR, storing the certificate if valid, and configuring the NRF. It defers if connectivity fails, logs warnings for missing CSR, and skips processing if CSR mismatch occurs. | def _on_certificate_available(self, event: CertificateAvailableEvent) -> None:
"""Pushes certificate to workload and configures workload."""
if not self._container.can_connect():
event.defer()
return
if not self._csr_is_stored():
logger.warning("Certificate is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.