dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def complete(self):
if len(self.edges) == len(list(itertools.combinations(self.vertices, 2))):
return True
else:
return False
def completepoly(self):
s = sym.symbols('k')
expr = 1
for i in range(len(self.vertices)):
expr = expr*(s-i)
re... | The code computes the chromatic polynomial of a graph recursively. It checks if the graph is complete or a tree for direct computation. For connected non-tree graphs, it applies deletion-contraction: removing an edge and merging vertices, then subtracting results. For disconnected graphs, it calculates the product of c... | def chromaticPol(self):
if self.complete():
return self.completepoly()
if self.isConnected():
if self.isTree():
return self.chromaticTree()
else:
g1 = copy.deepcopy(self)
g2 = copy.deepcopy(self)
... |
def get_updates(offset=None):
url = URL + "getUpdates?timeout=100"
if offset:
url += "&offset={}".format(offset)
js = get_json_from_url(url)
return js
def get_last_update_id(updates):
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
... | The main task of the code is to continuously poll for updates using a loop, process new updates by updating the last known update ID, and echo all received updates. It checks for updates every 0.5 seconds, ensuring real-time handling of incoming data. | def main():
last_update_id = None
while True:
updates = get_updates(last_update_id)
if len(updates["result"]) > 0:
last_update_id = get_last_update_id(updates) + 1
echo_all(updates)
time.sleep(0.5) |
def get_iam_group_membership():
def get_next_item(Marker):
if Marker is None:
request_params = {
"GroupName": iam_group
}
else:
request_params = {
"GroupName": iam_group,
"Marker": Marker
}
iam_us... | The code synchronizes WireGuard user configurations with IAM group membership by comparing IAM users and existing SSM-stored users. It identifies users to add/remove, updates the WireGuard config, and stores the new configuration in AWS SSM as a secure string. The task ensures SSM user lists align with IAM group member... | def handler(event, context):
iam = get_iam_group_membership()
print("Iam group {} users:{}".format(iam_group, iam))
ssm = get_existing_users()
print("User exist in SSM:{}".format(ssm))
if iam is not None and ssm is not None:
users2add = list(set(iam) - set(ssm))
users2remove = list(s... |
def parseDualPredictions(predictions):
out_1_preds = [ 1 if p >= 0.5 else 0 for p in predictions[0]]
out_2_preds = [ 1 if p >= 0.5 else 0 for p in predictions[1]]
return out_1_preds, out_2_preds
def accuracy(Y, Yhat):
"""
Function for computing accuracy
Y is a vector of the true labels and ... | The function evaluates a model's performance by calculating the accuracy of approval predictions and adjusting it with penalties for fairness gaps. It subtracts scaled parity and equality gaps (related to gender bias) from the accuracy, prioritizing both predictive accuracy and fairness in model outcomes. | def evaluateModel(model):
approval_predictions, gender_predictions = parseDualPredictions(model.predict(Xmat_val))
#return accuracy(Y_approved_val, approval_predictions) - abs(50 - accuracy(Y_gender_val, gender_predictions))
return accuracy(Y_approved_val, approval_predictions) - parityGap(male, female, Xma... |
def getNode(self, chrpair, nodeID):
return self.D[chrpair]["dendrogram"][nodeID]
def getNodeInfo(self, chrpair, nodeID):
return self.D[chrpair]["nodetestinfo"][nodeID]
def getNodeHits(self, chrpair, nodeID):
return [ self.D[chrpair]["hits"][hitID] for hitID in self.getNode(chrpair, nodeID).leaves ]
def getN... | The function calculates a conservation score and related metrics for a genomic node. It retrieves node data, identifies exons in two genomes, assesses covered vs. uncovered exons, and computes a score based on hits and best hits. It returns counts of accounted/uncovered exons, conservation score, and a derived score. | def nodeScore(self, chrpair, nodeID):
node = self.getNode(chrpair, nodeID)
nodeInfo = self.getNodeInfo(chrpair, nodeID)
if nodeInfo is not None:
return (nodeInfo.nA, nodeInfo.nU1, nodeInfo.nU2, node.conservationScore, nodeInfo.score)
#fi
nodeHits = self.getNodeHits(chrpair, nodeID)
((geno... |
def getNodeInfo(self, chrpair, nodeID):
return self.D[chrpair]["nodetestinfo"][nodeID]
def getNodeGenes(self, chrpair, nodeID):
genes1 = []
genes2 = []
hits = self.getNodeHits(chrpair, nodeID)
for h in hits:
genes1.append(self.exonInfo[h.qseqid].proteinid)
genes2.append(self.exonInfo[... | The main task of the code is to test a node's significance by evaluating its conservation score and gene counts. If the node meets criteria (sufficient genes, conservation threshold), it performs a CLT or permutation test to compute a z-score and p-value, updating the node's test information. If the node already exists... | def testNode(self, chrpair, nodeID):
if self.getNodeInfo(chrpair, nodeID) is None:
(genes1, genes2) = self.getNodeGenes(chrpair, nodeID)
nGenes1 = len(genes1)
nGenes2 = len(genes2)
zscore = 0.0
pvalue = 1.0
# If the node doesn't have at least two genes in one genome, ignore i... |
def getNode(self, chrpair, nodeID):
return self.D[chrpair]["dendrogram"][nodeID]
def testNode(self, chrpair, nodeID):
if self.getNodeInfo(chrpair, nodeID) is None:
(genes1, genes2) = self.getNodeGenes(chrpair, nodeID)
nGenes1 = len(genes1)
nGenes2 = len(genes2)
zscore = 0.0
pvalue... | This function traverses a node hierarchy to collect significant genomic clusters. Starting from a given node, it checks significance using z-scores and conservation thresholds. If a node is significant, it adds eligible child nodes to the result list. If not, it recursively processes children. The output is a list of (... | def getSigClustersAtNode(self, chrpair, startNodeID):
nodeList = [ startNodeID ]
sigClusters = []
while len(nodeList) > 0:
nodeID = nodeList.pop()
node = self.getNode(chrpair, nodeID)
self.testNode(chrpair, nodeID)
self.testNode(chrpair, node.child1)
self.testNode(chrpair, n... |
def build_type_map(self) -> None:
"""
Helper function to build a map of GQL types and their indices in self.data
"""
for i, type in enumerate(self.data["types"]):
self.type_map[type["name"]] = i
def build_operation_map(self) -> None:
"""
Helper function to bui... | This function generates a minimal GraphQL schema containing specified operations and their associated types, saving it to a JSON file for testing. It constructs operation type objects (Query/Mutation/Subscription), collects connected types, and exports the filtered schema to the provided file path. | def build_test_schema_with_operations(self, operation_tuples: list, test_schema_path: str) -> None:
"""
:param operation_tuples: list of tuples of (GQL operation type, GQL operation field)
- eg. [("Mutation", "UniqueMutationName"),("Query", "UniqueQueryName")]
:param test_schema_path: ... |
def query_nodes(self, feature: str, hash: str, name: str, verbose: bool = False) -> list:
"""
:param feature: feature to query by: "HASH", "NAME"
:param hash: (Optional) hash to query nodes by
:param name: name to query nodes by
:param verbose: print results
:return: list... | This function checks if a node with the given GQL type name and hash exists. If it does, it updates the node's properties and entities; if not, it creates a new node with the provided GQL type data. The function ensures nodes are either updated or created based on existence, avoiding duplicates while handling graph dat... | def _create_or_update_node(self, gql_type: dict, hash: str) -> int:
"""
:param gql_type: GQL type
:hash: md5 hash of the GQL type
:return: False if error
If node already exists, update node, else, create a new node. Not to be used when linking fields to types.
"""
... |
def open_session(self):
self.session = self.driver.session()
return self.session
def _create_or_update_node(self, gql_type: dict, hash: str) -> int:
"""
:param gql_type: GQL type
:hash: md5 hash of the GQL type
:return: False if error
If node already exists, upda... | The main task of the code is to translate a GraphQL introspection schema into Cypher queries, updating a database with nodes derived from the schema's types. It iterates through each type, generates a hash of its properties, and uses this to create or update corresponding database nodes. The function manages a session,... | def update_db(self, gql_types: list) -> None:
"""
:param gql_types:
GQL schema from Introspection response found in response["__schema"]["types"]
Translate GQL introspection schema to Cypher and updates the db
"""
self.open_session()
for type in gql_types:
... |
def event():
for event in pygame.event.get(): # ====== quit / exit
if (event.type == pygame.QUIT):
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
def menuscreen():
main=True
while main:
... | This code defines a game loop that continuously updates and renders a Pygame interface. It handles events, redraws the screen with menus/instructions, updates interactive buttons, displays labels, maintains a 60 FPS frame rate, and keeps the display updated until the game is quit. | def loop():
global game_on
event()
while True:
screen.fill(0)
menuscreen()
instruction()
buttons.update() # update buttons
buttons.draw(screen)
show_labels() # update labels
clock.tick(6... |
def redrawTheScreen(self):
self.screen.fill(self.myBoardsConfig.coloursLibrary['backGround'])
self.myButtons.buttonConstructor()
self.myCellsConstructor.cellsAndAxisConstructor(self.myButtons.buttonStates[1])
self.myGourdsConstructor.gourdsConstructor(self.myButtons.buttonStates[1])
... | The main task of the code is to execute Phase 3 of a puzzle-solving process, ensuring gourds are correctly ordered and the empty cell is in the proper position. It validates Phase 2 completion, rotates gourds counter-clockwise until the target configuration is achieved, then reverses steps using a footprint stack to fi... | def runPhaseThree(self, buttonState6):
if buttonState6 != 2: # running
self.firstRun = True
return
if self.myButtons.buttonStates[4] != 1:
self.myButtons.buttonStates[6] = 0
print("Phase 2 should be finished first!")
self.redrawTheScreen()
... |
def gourdsSearchingByCoordinate(self, pos):
x, y = pos
# shrink the searching area
x = x - self.offset
y = y - self.offset
x = x / self.widthOfHexCell
y = y / 1.732 / self.widthOfHexCell
x = int(x + 0.5)
y = int(y + 0.5)
return self.gourdsSearchin... | This function handles gourd movement logic when a gourd is clicked. It searches for a gourd based on input coordinates/index, checks for adjacent empty cells, and initiates movement if valid. The mode parameter determines search method: 'm' uses coordinates, else uses index. Returns movement result or -1 if no valid go... | def gourdsClicked(self, pos, mode):
# search Gourds by the given Coordinate
if mode == 'm':
indexOfGourd, xGourd, yGourd = self.gourdsSearchingByCoordinate(pos)
else:
indexOfGourd, xGourd, yGourd = self.gourdsSearchingByIndex(pos[0], pos[1])
if indexOfGourd != -1... |
def cellChecking(self, aCell):
isEmpty = True
gourdsIndexInHCycle = -1
for aGourds in self.myBoardsConfig.gourdsList:
gourdsIndexInHCycle += 1
if (aCell[0] == aGourds[0] and aCell[1] == aGourds[1]):
isEmpty = False
break
elif (a... | This function controls gourd movement by checking their positions against HCycleAux indices. It verifies if a gourd is in the first or second part of a sequence, validates adjacent positions, and triggers actions like clicking the next part or moving along the cycle. The main task is ensuring ordered gourd movement by ... | def gourdsMovementControllerInOrderGenerator(self, HCycleIndex):
isEmpty, indexOfGourds = self.cellChecking(self.HCycleAux[HCycleIndex])
if not isEmpty:
if (self.myBoardsConfig.gourdsList[indexOfGourds][0] == self.HCycleAux[HCycleIndex][0]
and self.myBoardsConfig.gourdsLi... |
def ifThereIsGourdsNotAligned(self):
for gourds in self.myBoardsConfig.gourdsList:
for HCycleCellIndex in range(1, len(self.HCycleAux)):
if (gourds[0] == self.HCycleAux[HCycleCellIndex][0] and gourds[1] == self.HCycleAux[HCycleCellIndex][1]):
if (gourds[2] == self... | The main task of the code is to align gourds within a Hamiltonian cycle by repeatedly identifying empty cells, moving unaligned gourds using a controller, and recording the final empty cell position. The process continues until all gourds are aligned, then generates the final ordered sequence of gourds in the cycle. | def runFinalHCycleOrderGenerator(self):
# move the gourds
while(self.ifThereIsGourdsNotAligned()):
# print (self.HCycleAux[rootIndex + i])
# find the empty cell
rootIndex = -1
for aCell in self.myHamiltonianCycle.hamiltonianCycleStack:
ro... |
def imread(self, image_loc):
return array(imopen(image_loc), dtype='uint8')
def encode(self, frame_list, image_list, bits = 1):
# Initialization of input frames
frame_count = len(frame_list)
frame_shape = [self.check_frame_shape(image_frame.shape) for image_frame in frame_list]
#... | The function encodes images from two directories using a specified bit depth, prepares image lists, processes them through an encoding method, and saves the resulting encoded frames to an output directory, returning the output path. | def encode_image_dir(self, img_dir, en_dir, bits = 2):
# Prepare the image directory into a list of frames
dir_list = [os.path.join(img_dir, loc) for loc in os.listdir(img_dir)]
img_list = [self.imread(path) for path in dir_list]
dir_list = [os.path.join(en_dir, loc) for loc in os.listdi... |
def imread(self, image_loc):
return array(imopen(image_loc), dtype='uint8')
def decode(self, frame_list, bits = 1):
# Initialization of the input frame
pixel_arr = self.flatten(frame_list)
# Extract all the values needed from the pixel array
binary_string = self.extract(pixel_ar... | This function decodes a sequence of images from a directory using specified bits, processes them, and saves the decoded output as JPEG files in a designated directory with "secret" prefix. | def decode_image_dir(self, img_dir, save_dir, bits):
# Prepare the image directory into a list of frames
dir_list = [os.path.join(img_dir, loc) for loc in os.listdir(img_dir)]
img_list = [self.imread(path) for path in dir_list]
result = self.decode(img_list, bits)
self.save_fram... |
def discover_dlt_files(self: Self, path: str) -> list:
# If path is relative, make it absolute
if not os.path.isabs(path):
path = os.path.join(os.getcwd(), path)
# Get all files in path and subdirectories
files = []
for dirpath, dirnames, filenames in os.walk(path):
... | This function converts discovered Dolt files into CSV format, associates them with cleaned table names, and optionally adds these CSV files to a project's .gitignore file to prevent version control tracking. It processes each file by extracting its base name, generating a corresponding CSV name, and ensuring the CSV is... | def get_dolt_files(self: Self, path: str, add_to_gitignore: bool = False) -> None:
dolt_files = self.discover_dlt_files(path)
for file in dolt_files:
file_name = os.path.basename(file)
table_name = self.__clean_file_name(file_name)
csv_name = table_name + ".csv"
... |
def to_destination(destination: DestinationConfigType) -> TransformationDestination:
if isinstance(destination, DestinationConfig):
return TransformationDestination(destination.type.value)
elif isinstance(destination, RawDestinationConfig):
return TransformationDestination.raw(
desti... | The function `to_transformation` creates a `Transformation` object using provided configuration parameters. It maps fields like name, external ID, destination, conflict mode, and authentication credentials from the `config` input, converting them via helper functions. It integrates dataset IDs via the client, sets visi... | def to_transformation(
client: CogniteClient,
conf_path: str,
config: TransformationConfig,
cluster: str = "europe-west1-1",
) -> Transformation:
return Transformation(
name=config.name,
external_id=config.external_id,
destination=to_destination(config.destination),
c... |
def get_symbol(self, response):
"""
Return symbol associated
"""
start_i = response.request.url.rfind('/')
end_i = response.request.url.rfind('.')
return response.request.url[start_i+1:end_i]
def extract_low_price(self, response):
"""
Return extracted low ... | This code parses financial data from a response by extracting key metrics like stock symbol, price ranges, shares, volume, and book value. It populates a Fundamentals object with these values and yields it, handling exceptions by printing errors. Some extraction methods are commented out or pending normalization. | def parse(self, response):
try:
fundamentals = Fundamentals()
fundamentals['symbol'] = self.get_symbol(response)
self.symbol = fundamentals['symbol']
fundamentals['low_price'] = self.extract_low_price(response)
fundamentals['high_price'] = self.extract... |
def dataset_preprocessing(self,**kwargs):
begin_time = time()
self.dataset = self.load_dataset_name()
logHandler.info(self.dataset)
self.dataset_dir = self.load_dataset_dir()
self.load_dataset_forward()
self.feature_pool_create(**kwargs)
end_time = time()
... | The code's main task is to preprocess, clean, and split data using three methods (`dataset_preprocessing`, `clean_data`, `split_data_r`), all accepting customizable parameters via `**kwargs` to prepare datasets for machine learning tasks. | def preload_data(self,**kwargs):
self.dataset_preprocessing(**kwargs)
self.clean_data(**kwargs)
self.split_data_r(**kwargs) |
def read_input() -> list[str]:
with open('input.txt') as f:
lines = f.readlines()
return [line.strip() for line in lines]
def has_adjacent_special_char(lines: list[str], line_index: int, char_index: int) -> bool:
line_limit = len(lines)
char_limit = len(lines[0])
for offset in adjacent_cha... | The main task of the code is to process input lines, identify numeric characters adjacent to special characters or specific neighbors, calculate their positional decimal values, and accumulate the sum of these values. It iterates through each character, checks conditions for relevance (adjacent special characters or ri... | def main():
lines = read_input()
sum_ = 0
previous_char_relevant = False
for line_index, line in enumerate(lines):
for char_index, c in enumerate(line):
print(f'line={line_index} char={char_index} c={c}'
f' has_adjacent_special_char={has_adjacent_special_char(line... |
def songsentimentselect(artistname, songname):
query = "SELECT sentiment FROM songsentiment WHERE artistname='{0}' AND songname='{1}'".format(
artistname, songname)
cursor = conn.cursor()
cursor.execute(query)
data = cursor.fetchone()
if data != None:
print("Song query successful")
... | The main task of the code is to provide a menu-driven interface for querying sentiment analysis. It allows users to select between analyzing sentiment by song or album, inputting artist and song/album names, and displays results using functions `songsentimentselect` or `albumsentimentselect`. The loop restarts after ea... | def mainmenu():
option = input('''Select an option.
[0]: Sentiment by song
[1]: Sentiment by album\n''')
if option == "0":
artistname = input("Enter artist name: ")
songname = input("Enter song name: ")
result = songsentimentselect(artistname, songname)
p... |
def parse_props(self, el, props):
d = {}
for p in props:
conv = lambda x: x
if isinstance(p, tuple):
conv = p[1]
p = p[0]
pel = el.find(p)
if pel is not None:
d[p] = conv("" if pel.text is None else pel.text)... | This function processes an XML element to extract and transform account-related data. It parses specified fields, renames keys, adds metadata like type and order number, then inserts the transformed data into a database table, replacing existing entries if they conflict. | def handle_account(self, el, orderno):
props = ["uuid", "name", "currencyCode", ("isRetired", as_bool), "updatedAt", "id"]
fields = self.parse_props(el, props)
ren(fields, "currencyCode", "currency")
ren(fields, "id", "_xmlid")
fields["type"] = "account"
fields["_order"] ... |
def parse_props(self, el, props):
d = {}
for p in props:
conv = lambda x: x
if isinstance(p, tuple):
conv = p[1]
p = p[0]
pel = el.find(p)
if pel is not None:
d[p] = conv("" if pel.text is None else pel.text)... | This code processes a portfolio element from an XML input, extracts and transforms specific fields (like uuid, name, isRetired, etc.), inserts the data into a database table named "account" with a "portfolio" type, and handles additional attributes. It ensures data consistency by replacing existing entries and maps XML... | def handle_portfolio(self, el, orderno):
props = ["uuid", "name", ("isRetired", as_bool), "updatedAt", "id"]
fields = self.parse_props(el, props)
ren(fields, "id", "_xmlid")
acc = el.find("referenceAccount")
fields["referenceAccount"] = self.uuid(acc)
fields["type"] = "po... |
def availablePositions(self):
positions = []
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if self.board[i, j] == 0:
positions.append((i, j)) # need to be tuple
return positions
def updateState(self, position):
self.board[positio... | This code simulates a turn-based game between two players (p1 and p2) for a specified number of rounds. It alternates players taking actions on a board, updates game states, checks for win/draw conditions, and resets the game when ending. If a player wins or the game draws, rewards are assigned, and all components are ... | def play(self, rounds=sys.maxsize):
for i in range(rounds):
if i % 1000 == 0:
print("Rounds {}".format(i))
while not self.isEnd:
# Player 1
positions = self.availablePositions()
p1_action = self.p1.chooseAction(positions, se... |
def construct_tree(data, target, features):
if len(set(data[target])) == 1:
return data[target].iloc[0]
if not features:
return data[target].mode().iloc[0]
best_feature = max(features, key=lambda f: information_gain(data, f, target))
tree = {best_feature: {}}
for value, subset in dat... | The main task of the code is to load the "playtennis.csv" dataset, split it into features and the target variable "Play Tennis," construct a decision tree using the `construct_tree` function, print the generated tree structure, and calculate the prediction accuracy of the tree on the dataset. The code demonstrates buil... | def main():
# Load dataset from playtennis.csv
df = pd.read_csv("C:\playtennis.csv")
# Extract target and features
target_column = "Play Tennis"
features = set(df.columns) - {target_column}
# Construct the decision tree
tree = construct_tree(df, target=target_column, features=features)
#... |
def quiesce(self, alpha, beta, depth, from_move, from_piece, to_move, to_piece, pre_score, check):
if depth == 0 or check == True:
score_board = self.evaluate_board()
else:
score_board = self.eval_board(pre_score, from_move, from_piece, to_move, to_piece, tables, pieces)
... | This code implements the alpha-beta pruning algorithm with move ordering and quiescence search for game tree evaluation. It recursively explores possible moves, alternating between maximizing and minimizing players, while pruning branches that cannot influence the final decision. The function returns the best evaluatio... | def alphabeta(self, alpha, beta, depth, maximizingPlayer):
if depth == 0 :
return self.quiesce(alpha, beta, 0, 0, None, 0, None, 0, False)
sorted_moved = self.sort_moves(maximizingPlayer)
if maximizingPlayer:
maxEval = -9999
for move in sorted_moved:
... |
def calculate_interaction_matrix(self,atomic_coordinates, model_parameters):
'''Returns the electron-electron interaction energy matrix for an input list of atomic coordinates.
Parameters
----------
atomic_coordinates : np.array
an array that contains the coordinates of atom... | The main task of the code is to compute and return five key components in a quantum chemistry calculation: the interaction matrix, chi tensor, Hamiltonian matrix, density matrix, and nuclear repulsion energy. These are derived from atomic coordinates and model parameters using specialized calculation methods. The Hamil... | def kernel(self):
'''Generations interaction matrix, chi tensor, density matrix, hamiltonian matrix, and n-n repulsion energy from
given parameters and returns them.
Returns
-------
interaction_matrix: np.array
chi_tensor: np.array
hamiltonian_matrix: np... |
def _checkJson(json_db):
subimages = json_db.get('subimages')
if subimages is None:
_error('Error in spriteforhtml.create.create_sprites: property "subimages" is missing')
requiredKeys = [ 'filename']
for subimage in subimages:
for key in requiredKeys:
if subimage.get(key) is None:
_error... | The main task of the code is to generate a sprite image and corresponding CSS from a structured JSON database. It processes subimage data, checks for overlaps, arranges subimages, creates a transparent sprite canvas, pastes subimages onto it, generates CSS background-position rules, and saves the resulting sprite and C... | def create_from_memory(json_db, rootDir='.'):
"""
Create sprites from a json object
See full description at top of this file
"""
_checkJson(json_db)
_openSubimages(json_db, rootDir)
error, msg = checkOverlapping(json_db['subimages'])
if error:
_error(msg)
sortSubimages(json_db)
_setCssSelector... |
def calculate_coef(self):
"""
This function calculates the regression coefficients based on the given data
Inputs:
data: a pandas dataframe on which you would like to perform regression analysis
Returns:
The beta coefficient of regression
"""
x_transpose =... | The code compares a custom regression model with the StatsModels OLS regression by fitting both, then prints summary statistics, coefficients, R-squared, and adjusted R-squared values from both methods to evaluate performance and validate results. | def compare(self):
"""
Compares our regression model with the StatsModels regression model
"""
regressor = sm.OLS(self.y,self.x)
fitted_regressor = regressor.fit()
summary = fitted_regressor.summary()
print(summary)
results_own = self.calculate_coef()
... |
def gradient_descent(self):
"""
Runs Gradient descent on the model and updates the weights.
:return: None
"""
# start = time.time()
sum_of_W = np.zeros((self.range_of_rows[-1], len(self.feature_names)))
X_array = self.working_dataframe[self.feature_names].to_nump... | The code implements gradient descent training for a model, iterating up to a specified limit. It tracks cost and iteration history, prints updates periodically, and checks for cost convergence to potentially halt early. It handles keyboard interrupts by saving results and reporting accuracy, then finalizes training wit... | def run_trainer(self):
self.range_of_rows = range(self.m + 1)
should_continue = True
prev_iteration_cost = 0
self.iterations_finished = 0
cost_history = []
iterations_history = []
try:
while should_continue and self.iterations_finished < self.iteration... |
def clear_db(c):
c.execute('DROP TABLE IF EXISTS USERS')
c.execute('DROP TABLE IF EXISTS POSTS')
c.execute('DROP TABLE IF EXISTS COMMENTS')
def create_tables(c):
c.execute('CREATE TABLE USERS(\
id INTEGER PRIMARY KEY,\
username text,\
name text,\
password text,\
e... | This code generates an SQLite database by connecting to 'test.sqlite3', clearing existing data, creating tables, inserting an anonymous user, generating additional users and 200 posts, then committing and closing the connection. | def gen_db():
# connect
conn = sqlite3.connect(os.path.join('test.sqlite3'))
c = conn.cursor()
clear_db(c)
create_tables(c)
# Create anon user
c.execute('INSERT INTO USERS VALUES(1,"Anon","Anon","password","njskz@example.com","","",0)')
# create rest
users = gen_users(c)
gen_p... |
def options():
p = optparse.OptionParser(usage=help_msg)
p.add_option('--in_map_dir', '-i', default='./map.csv',
help='This is a mandatory option. It is recommended to use with the map.csv')
p.add_option('--in_data_dir', '-u', default='',
help='This is an optional option. I... | The main task of the code is to process map and trajectory data by reading files from specified directories, parsing structured data with predefined headers, and generating visualizations based on display modes, time periods, and sampling rates. It prepares input data for rendering dynamic maps or trajectories using de... | def main():
in_map_dir, in_data_dir, display_modes_list, time_period, sampling_rate = options()
map_filename = os.path.basename(in_map_dir)
data_filename = os.path.basename(in_data_dir)
display_filename = data_filename if data_filename != "" else map_filename
map_header_dict = {'road_id': int,
... |
def card_preprocess(cards):
# cards is a list of [{'rank':_, 'type':_}]
cards = [[single_rank[cards[i]['rank']], card_code[cards[i]['type']]] for i in range(len(cards))]
cards.sort()
return cards
def best_hand_to_list(cards, revealed_cards):
player_best_hand = list(best_hand(cards, revealed_cards))
... | The code processes game history to determine opponents' win/draw/loss outcomes, then updates global probability tables (table1, table2, table3) by analyzing possible card combinations and betting patterns. It learns opponent behavior by simulating valid card hands that align with historical results, categorizing scenar... | def opponent_model(history, handid, me, num_players):
global table1, table2, table3
# array determining NA, winning, drawing or losing for each player
res_list = [0 for i in range(num_players - 1)]
learn_list = []
# learning from history
# guess opponent cards
for i in range(len(history) - 1... |
def opponent_model(history, handid, me, num_players):
global table1, table2, table3
# array determining NA, winning, drawing or losing for each player
res_list = [0 for i in range(num_players - 1)]
learn_list = []
# learning from history
# guess opponent cards
for i in range(len(history) - 1... | The code determines the optimal action (fold, call, raise) in a poker-like game by analyzing the current game state, player history, and calculated probabilities. It evaluates opponents' betting patterns, chip ratios, and win/loss/draw probabilities using historical data and common cards. Thresholds are adjusted based ... | def potential(game_state):
global actions, past_chips, past_bets, pids, pid_toid, prev_common_cards
state = game_state['state']
history = game_state['history']
# first check if history contains win
num_players = len(state['players'])
me = state['players'][state['me']]['id']
if pids == []:
... |
def solr():
solr = pysolr.Solr('http://localhost:8983/solr/tweets', timeout=10)
results = solr.search("*:*", rows=100)
return results
def get_tweets_results(data,svbag,forest,tfidf):
l = []
for i in data:
temp = get_type(classifyRecord(i['tweet'][0],svbag, forest, tfidf))
l.appe... | The code's main task is to classify text data using pre-trained machine learning models (SVM, Random Forest, TF-IDF). It loads models from files, retrieves data via Solr, applies classification to the data, and renders results in a template. A sample text is tested for demonstration, and the classified outcomes are dis... | def classification(request):
#svbag,forest,tfidf = data_preprocess()
#t = classifyRecord('One country addressing the COVID 19 crisis with competence. BBC News - Coronavirus in South Korea: How \'trace, test and treat\' may be saving lives https://t.co/3Y3blkbsqJ', svbag, forest, tfidf)
#print(t)
#return... |
def set_log_level(parsed_args):
logger = logging.getLogger()
if parsed_args.verbose:
logger.setLevel(logging.INFO)
else:
logger.setLevel(logging.WARNING)
def load_config(config_file):
try:
return toml.load(config_file)
except Exception as e:
logging.error('[main] Coul... | The main task of the code is to parse command-line arguments, configure logging, and execute specified actions ('meter', 'simulator', or 'plot') using a configuration file. It handles help requests, version displays, and invalid actions by printing appropriate messages or errors. | def main():
parser = ArgParser()
parsed_args = parser.parse()
set_log_level(parsed_args)
if parsed_args.help:
parser.print_help()
elif parsed_args.version:
parser.print_version(__version__)
elif parsed_args.action:
config = load_config(parsed_args.config)
if parse... |
def trainAndChooseGenes(X, y, gene_name_list=None, gene_num=100, dict_digit_group={}, output_prefix='.', **kargs):
'''
Only kargs with `feature_selection__` prefix will be taken into acount and all others will be dropped.
'''
kargs = copy.deepcopy(kargs)
for k in list(kargs.keys()):
kargs[k... | The function `crossValidation` performs k-fold cross-validation with gene selection and normalization, evaluating a predictor's performance. It iteratively splits data, selects relevant genes for each fold, applies normalization if specified, trains the predictor, and predicts on test sets. Results are aggregated, filt... | def crossValidation(X, y_list, predictor, output_prefix_predictor, k_cross_validation, random_state=None, output_path=None, do_normalize_after_loc=None, **kargs):
'''
Not simply a `cross_val_predict` here any more since 20200519.
A pipeline containing (1) choose genes (2) evaluate on test part will replace... |
def inverseDict(dict_to_reverse):
dict_reversed = {}
for k, v in dict_to_reverse.items():
if v not in dict_reversed:
dict_reversed[v] = k
else:
raise Exception('Duplicate value while inversing dict! ')
return dict_reversed
def createNewPredictorInstance(**kargs):
... | The function `classifyUsingSklearn` trains or loads a machine learning classifier (e.g., SVM, DNN) to classify input data `X` with labels `y_list`. It handles feature engineering (polynomial features), data splitting, cross-validation, normalization, and model evaluation. If `load_predictor` is provided, it loads a pre... | def classifyUsingSklearn(X, y_list, training_part_scale=0.75, k_cross_validation=None, V_times_cv=None, dict_digit_to_group=None,
featurer=False, polynomial=1, interaction_only=False, plot=False, random_state=None,
load_predictor=None, do_normalize=False, path_chosen_genes="", ... |
def generateFeaturesAndLabels(path_feature_df, path_group, path_chosen_genes="", return_gene_list=False, transpose=False, \
do_normalize="Normalizer(norm='l1')", do_normalize_after_loc="Normalizer(norm='l1')", do_exp_if_negative=False, **kargs):
'''
do_normalize: a initiated Normalizer from sklearn.preproc... | The function classifies data using features from a DataFrame and group labels, converting labels to digital/binary formats. It trains a classifier (via `classifyUsingSklearn`), supports cross-validation, and saves results. Key tasks: load data, preprocess labels, train/test models, and output predictions/analysis to a ... | def classifyUsingDFAndGroupTxt(path_df, path_group, path_chosen_genes="", training_part_scale=0.75, k_cross_validation=None, V_times_cv=None, which_is_1=None,
plot=False, random_state=None, load_predictor=None, load_dict_digit_to_group=None, output_dir=".", **kargs):
X, groups = ... |
def match_torch(self, tag_k, loc_k, val_k):
match = lambda x: self.match_by_tag_torch(x)
return list(map(match, zip(tag_k, loc_k, val_k)))
def top_k_torch(self, det, tag):
# det = torch.Tensor(det, requires_grad=False)
# tag = torch.Tensor(tag, requires_grad=False)
det = self.nm... | The code parses and refines pose estimation results by matching top detections, adjusting keypoints, calculating confidence scores, and refining joint positions. If enabled, it iterates through detections to refine keypoints using tags, handling multi-person scenarios. The output includes refined detections and their a... | def parse(self, det, tag, adjust=True, refine=True):
ans = self.match_torch(**self.top_k_torch(det, tag))
if adjust:
ans = self.adjust_torch(ans, det)
scores = [i[:, 2].mean() for i in ans[0]]
if refine:
# for each image
for i in range(len(ans)):
... |
def bbox_area(bbox):
"""
Area of a bounding box (a rectangles).
Args:
bbox (:class:`np.ndarray`): rectangle in the form (x_min, y_min, x_max, y_max)
Returns:
float: Bounding box area.
"""
x1, y1, x2, y2 = bbox
dx = x2 - x1
dy = y2 - y1
return dx * dy
def oks_iou(g... | This function computes two similarity matrices between two sets of bounding boxes and poses. It calculates bounding box IoU (result_bbox) for pairwise box comparisons and pose similarity using OKS-IoU (result_pose), which incorporates area normalization. Both matrices are (N,M) arrays where N and M are the sizes of the... | def compute_similarity_matrices(bboxes_a, bboxes_b, poses_a, poses_b):
assert len(bboxes_a) == len(poses_a) and len(bboxes_b) == len(poses_b)
result_bbox = np.zeros((len(bboxes_a), len(bboxes_b)), dtype=np.float32)
result_pose = np.zeros((len(poses_a), len(poses_b)), dtype=np.float32)
for i, (bbox_a, ... |
def move_south(movement_dict, amount):
movement_dict['north'] -= amount
return movement_dict
def move_west(movement_dict, amount):
movement_dict['east'] -= amount
return movement_dict
def move_forward_by_waypoint(movement_dict, waypoint_dict, amount):
movement_dict['north'] += waypoint_dict['north']... | The code parses ship movement instructions using a waypoint system. It tracks the ship's movement by adjusting the waypoint's position (north/east) based on commands (N, S, E, W, L, R) and applies rotations or forward movements. The final movement_dict accumulates the total displacement in north and east directions aft... | def parse_movement_with_waypoint(ship_instructions):
waypoint_dict = defaultdict(int)
waypoint_dict['north'] = 1
waypoint_dict['east'] = 10
movement_dict = defaultdict(int)
movement_dict['north'] = 0
movement_dict['east'] = 0
for instruction in ship_instructions:
if instruction[0] =... |
def data_merge_annotation(self, write_path='./data/merged/'):
print('starting to merge sample for different medical data center:')
name = f'sepsis_merged_{self.args.merge_time_window}_{self.args.sample_time_window}_' \
f'{self.args.threshold_missing}.csv'
if not os.path.exists(wri... | The code initializes a class to process a dataset by reading CSV data, merging annotations, splitting into internal/external centers, and generating labeled datasets for each center using specified parameters. | def __init__(self, args):
self.args = args
self.data = pd.read_csv(args.read_path)
self.sepsis_merge = self.data_merge_annotation()
self.sepsis_internal_center, self.sepsis_external_center = self.data_center_select()
self.sepsis_dataset_internal = self.get_labeled_data(self.sepsi... |
def menu_image():
menu_image=pygame.image.load('misc/menu.jpg')
menu_image=pygame.transform.scale(menu_image,(800, 600))
menu_bound=menu_image.get_rect()
menu_bound=menu_bound.move((0,0))
screen.blit(menu_image,menu_bound)
def menu_text(text,x,y):
font=pygame.font.Font('misc/blackjack.otf',70)... | The code creates a main menu with two buttons for different game modes using Pygame. It detects mouse clicks on buttons to trigger game initialization with specific parameters, allowing users to select between "Tic Tac Toe" and "Open Field Tic Tac Toe." The menu handles quitting, escaping, and passing parameters to sta... | def menu():
running=True
click=False
while running:
# screen.fill((10,0,0))
pygame.display.set_caption('Main Menu')
menu_image()
menu_text('Main Menu',250,100)
option = pygame.mouse.get_pos()
game1=pygame.Rect(290,250,200,50)
game2=pygame.Rect(250,3... |
def sample(self):
"""
This method should randomly sample the free space, and returns a viable point
Args:
Returns:
(x, y) (float float): a tuple representing the sampled point
"""
already_exists = True
is_obstacle = True
while already_exist... | The main task of the code is to implement the RRT* (Rapidly-exploring Random Tree) algorithm for path planning in a robot navigation system. It uses odometry data to dynamically build a tree of nodes, expanding towards a randomly sampled goal area while avoiding collisions. The algorithm iteratively selects random poin... | def odom_callback(self, odometry_info):
"""
The pose callback when subscribed to particle filter's inferred pose
Here is where the main RRT loop happens
Args:
pose_msg (PoseStamped): incoming message from subscribed topic
Returns:
"""
self.car_odom ... |
def posx(k):
return np.tile(np.arange(-k,k+1,1), (2*k+1,1))
def prob(k, initc00, initc01, initc10, initc11, initposx, initposy):
c = recursion(k)
probn00 = np.square(np.abs(initc00*(c[0]+c[4]+c[8]+c[12])+initc01*(c[1]+c[5]+c[9]+c[13])+initc10*(c[2]+c[6]+c[10]+c[14])+initc11*(c[3]+c[7]+c[11]+c[15])))
pro... | This function calculates the variance of a position variable `posx` at time step `k` by computing the expected value of the squared position (via integration with a probability distribution) and subtracting the square of the mean position. It uses initial parameters to define the probability distribution and mean funct... | def varposx(k, initc00, initc01, initc10, initc11, initposx, initposy):
posxsquared = np.square(posx(k))
s = np.multiply(posxsquared,prob(k, initc00, initc01, initc10, initc11, initposx, initposy))
return np.sum(s) - meanposx(k, initc00, initc01, initc10, initc11, initposx, initposy)**2 |
def posy(k):
return np.transpose([np.flip(np.arange(-k,k+1,1))]*(2*k+1))
def prob(k, initc00, initc01, initc10, initc11, initposx, initposy):
c = recursion(k)
probn00 = np.square(np.abs(initc00*(c[0]+c[4]+c[8]+c[12])+initc01*(c[1]+c[5]+c[9]+c[13])+initc10*(c[2]+c[6]+c[10]+c[14])+initc11*(c[3]+c[7]+c[11]+c[1... | The function calculates the variance of posy(k) by computing the expected value of its square (E[X²]) through multiplication with a probability term and summing, then subtracting the square of the mean of posy(k) (E[X]²), following the variance formula Var(X) = E[X²] - (E[X])². | def varposy(k, initc00, initc01, initc10, initc11, initposx, initposy):
posysquared = np.square(posy(k))
s = np.multiply(posysquared,prob(k, initc00, initc01, initc10, initc11, initposx, initposy))
return np.sum(s) - meanposy(k, initc00, initc01, initc10, initc11, initposx, initposy)**2 |
def random_neighbor(self, previous_position, current_position, visits):
x1, y1 = previous_position
x2, y2 = current_position
x_delta = x2 - x1
y_delta = y2 - y1
assert abs(x_delta) in (0, 1) and abs(y_delta) in (0, 1) and abs(x_delta) != abs(y_delta)
if y_delta == 1:
... | This function generates a maze-like level with randomly placed obstacles (Rock/Web), a start position, and an exit. It uses a randomized depth-first approach to populate the map, ensuring connectivity and boundary conditions, then converts unvisited cells to walls. The result is a Controller object initialized with the... | def generate_level(self):
level_map = {}
start_position = random.randrange(1, self.width - 1), random.randrange(1, self.height - 1)
level_map[start_position] = Void
visited = {start_position: 1}
position = start_position
x, y = position
previous_position = random.... |
def look(self, direction=0, refresh=False):
position = self.next_position(direction)
if not refresh and position in self.level_map:
return self.level_map[position]
self.turn(direction)
seen = look()
self.level_map[position] = seen
return seen
def iter_unvisite... | This code navigates an agent through a maze-like environment, prioritizing movement toward unvisited positions based on whether it's carrying a rock. It avoids obstacles like voids and walls, handles rocks and webs, and attempts to escape via an exit. The agent moves, turns, drops, or takes items as needed, returning i... | def run(self):
while True:
self.look()
if self.carrying_rock:
preferences = (Exit, Web, Void, Rock, Unknown, None)
else:
preferences = (Exit, Void, Rock, Unknown, None)
unvisited = set(self.iter_unvisited(preferences))
... |
def package_response(error: bool, message, gps_coordinates="0.0,0.0"):
data = {
'error': error,
'message': message,
'gps_coordinates': gps_coordinates
}
return data
def complete_mission_and_return_distance_from_home(drone: drone_models.Drone) -> int:
try:
delivery = drone... | The main task of the code is to retrieve the next destination coordinates for a drone based on its current status and mission parameters. It first validates the drone's existence using an access key, calculates the distance from home, and then determines the next mission coordinates. The function returns a JSON respons... | def get_next_destination(request, drone_token):
try:
drone = drone_models.Drone.objects.get(access_key=drone_token)
except drone_models.Drone.DoesNotExist:
message = f"Drone does not exist."
log.error(message)
return JsonResponse(package_response(True, message))
distance_from... |
def _checkpid(self):
if self.pid != os.getpid():
self.disconnect()
self.__init__(self.patterns,
self.max_connections_per_pattern,
self.connection_class)
def make_connection(self):
"""Create a new connection"""
if self._c... | The main task of the code is to retrieve a connection from a connection pool. It first attempts to pop an existing connection from the `available_connections` list using a pattern index. If no connections are available, it creates a new one via `make_connection()`. The obtained connection is then added to `in_use_conne... | def get_connection(self, command_name, *keys, **options):
"""Get a connection from the pool"""
self._checkpid()
try:
connection = self._available_connections[self._pattern_idx].pop()
except IndexError:
connection = self.make_connection()
self._in_use_conne... |
def calcHeight(self,node):
if not node:
return -1
return node.height
def settleViolation(self,data, node):
balance = self.calcBalance(node)
# case 1 -> left left heavy situation
if balance > 1 and node.leftChild.data:
print("left left heavy situation")
... | This function inserts a new node with given data into a binary tree recursively. It adjusts the height of the current node and ensures tree balance by calling `settleViolation` after insertion, typical in self-balancing trees like AVL trees. | def insertNode(self,data, node):
if not node:
return Node(data)
if data < node.data:
node.leftChild = self.insertNode(data, node.leftChild)
else:
node.rightChild = self.insertNode(data, node.rightChild)
node.height = max(self.calcHeight(node.leftChil... |
def get_image_url(self, style):
'''
INPUT:
background-image: url("images/ny.jpg");
OUTPUT:
images/ny.jpg
returns image url path from CSS style string
'''
if style is None:
return None
style = style.split("(")[-1]
... | This code scrapes specific date-related data (e.g., day, Tamil month, star, thithi, festivals) from a webpage using XPath and BeautifulSoup, stores it in a dictionary, inserts it into a SQL database, and navigates to the next page for further scraping. Error handling logs failures during data extraction. | def __scrape_cell(self, year, month, date):
date_cell = {
'pday' : None,
'ptamil_month' : None,
'ptamil_star' : None,
'pthithi_name' : None,
'pthithi_img' : None,
'special_day' : None,
'spe... |
def __wait_loading(self):
self.logger.debug("...")
skip = 0
while True:
time.sleep(0.3)
if not self.driver.find_element_by_xpath(LOADING_FRAME).is_displayed():
skip += 1
if skip >= 3:
return
def number_of_days_in_month(se... | The code scrapes data for each day of a specified year by iterating through months (1-12), submitting each month's form, waiting for page load, and scraping daily cells. It uses Selenium to input the year, select months via dropdown, click submit, and extract data for each day in the month, closing frames after each sc... | def __scrape_year(self, year):
self.logger.debug(f"Starting scrapping year '{year}'")
wait = WebDriverWait(self.driver, 10)
# setting year field
wait.until(EC.presence_of_element_located((By.XPATH, YEAR_FIELD))).send_keys(str(year))
select = Select(self.driver.find_element_b... |
def block_inside(self):
tiles = self.current_block.get_cell_positions()
for tile in tiles:
if self.grid.is_inside(tile.row,tile.column) == False:
return False
return True
def block_fits(self): #locking the block on the grid if the cells below the block is already fil... | The main task of the code is to attempt moving the current block down by 1 unit. If the block is no longer within bounds or fails to fit in its new position, it reverts the move and locks the block in place. This ensures valid block movement and proper locking when downward movement is obstructed. | def move_down(self):
self.current_block.move(1,0)
if self.block_inside() == False or self.block_fits()== False:
self.current_block.move(-1,0)
self.lock_block() |
def acct_param():
acct_ref = Btoi(Txn.application_args[1])
return return_string(
Seq(
aa := AccountParam.authAddr(acct_ref),
mb := AccountParam.minBalance(acct_ref),
b := AccountParam.balance(acct_ref),
Concat(
Bytes("Auth addr: '"),
... | The code defines an approval function for a smart contract, routing transactions based on application arguments and on_completion types. It checks the first application argument against predefined selectors (e.g., `acct_param`, `bsqrt`, `gitxn`, `budget_pad`), executing corresponding functions and returning results. It... | def approval():
# Define our abi handlers, route based on method selector defined above
handlers = [
[
Txn.application_args[0] == acct_param_selector,
Return(Seq(acct_param(), Int(1))),
],
[
Txn.application_args[0] == bsqrt_selector,
Return... |
def database_exists(self, name):
with self.cursor as c:
c.execute(f"SELECT DATNAME FROM PG_DATABASE WHERE DATNAME='{name}';")
results = [res[0] for res in c.fetchall()]
if len(results) > 0:
return True
else:
return False
ret... | The main task of the code is to create or update static templates for an agency by checking if its database exists, creating it if not, and then generating static sample tables using provided table structures and a reload flag to control data refresh. This ensures consistent template setup for the agency's data process... | def create_static_templates_for_agency(self, agency_name, tables, reload=False):
if not self.database_exists(agency_name):
self.create_database(agency_name)
self.build_static_samples_tables(database=agency_name,tables=tables,reload=reload) |
def __check_image_dimensions(self, img: torch.Tensor) -> None:
"""Checks if the dimensions of the input image are in the right format!
Args:
img (torch.Tensor): rgb input image
Raises:
ValueError: If shape of ``img`` is incorrect
ValueError: if order of axes... | The code computes a saliency map using Itti's method by first applying linear filtering to extract color, intensity, and orientation features. It then calculates center-surround differences for each feature type, combines them across scales, normalizes the results, and finally performs a linear combination to generate ... | def saliency_map(self, img: torch.Tensor) -> torch.Tensor:
"""Calculates the Saliency map using the Itti's method.
For that purpose the subfunctions of this class will be used, to first calculate the features, then the center-surround differences,
which are followed by the across-scale... |
def getInputFromExportedCSV(fname: str, inputdir: str):
"""
- takes a file name and opens it
- reads it to a list and returns that list of data
input_data - list holding the data read from the file
fname - name of csv file being read from
inputdir - directory name of the input files
"""
... | The main task of the code is to process CSV order data, generate PDF bundles with cover pages and indexes, split data into volumes, and merge them into final PDFs, while logging progress. It reads input CSVs, creates output directories, handles statement/draft flags, and converts DOCX covers to PDFs for each bundle vol... | def main():
# data of all bundles - comes from order.csv
master_data = []
with open("src/order.csv", "r") as order:
reader = csv.reader(order)
for r in reader:
master_data.append(r)
print("master data", master_data)
for i in range(len(master_data)):
bundle = ma... |
def is_valid_position(self, position: Position) -> bool:
row_is_valid: bool = (position.row >= 0 and position.row < self.N_ROWS)
col_is_valid: bool = (position.col >= 0 and position.col < self.N_COLS)
return (row_is_valid and col_is_valid)
def tile_at_position(self, position: Position) -> Tile:
... | This code applies a move to a game board by expanding a region of a specified color using a breadth-first search (BFS) approach. It duplicates the current blob, iterates through tiles to check their valid neighbors of the same color, adds qualifying tiles to a new blob and queue, and updates the blob's color once all n... | def make_move(self, move_color: Color) -> None:
"""
Applies a move to the Board, using the given `move_color`.
Approach / Steps:
(1) make a duplicate current Blob as the "new" Blob so we can make modifications to it
(2) make a second duplicate Blob but tr... |
def load_strategems():
strategems = {}
for file_name in os.listdir('strategems'):
with open(f'strategems/{file_name}', 'r') as f:
strategem = json.load(f)
strategems[file_name] = strategem
return strategems
def get_strategem_embeddings(strategems, model):
strategem_embedd... | The code plays a chess game using an AI that selects moves based on precomputed strategem embeddings, tracks game states, move durations, and player actions, and appends this data to a DataFrame for analysis. It alternates between human and AI turns, checks game outcomes (checkmate, draw, resignation), and saves result... | def play_game():
model = SentenceTransformer('all-MiniLM-L6-v2')
# Initialize board
board = chess.Board()
# Load strategems from JSON files
strategems = load_strategems()
# Initialize a dictionary to store the embeddings of the strategems
strategem_embeddings = {}
# Convert each strat... |
def load_game_data():
try:
with open('game_data.json', 'r') as f:
return pd.read_json(f, lines=True) # Specify `lines=True` to read JSON records as lines
except FileNotFoundError:
return pd.DataFrame(columns=['state_embeddings', 'move_embeddings', 'move_durations', 'board_positions'... | The code simulates a chess game where a human and AI (using OpenAI) alternate moves. It records board states, move embeddings (via SentenceTransformer), move durations, and piece movements. Game outcomes (checkmate, draw, resignation) are tracked, and all data is stored in a DataFrame for analysis. | def play_game():
model = SentenceTransformer('all-MiniLM-L6-v2')
board = chess.Board()
previous_state_embeddings = []
previous_move_embeddings = []
move_durations = []
board_positions = []
moved_pieces = []
game_result = None # variable to hold game result
# Load existing game data... |
def _add_tunnel_local_endpoint(self, tunnel_name, listen_port):
if self.opt_use_tmux or self.opt_use_systemd:
self.tunnel_local_endpoint[tunnel_name] = "127.0.0.1:{}".format(listen_port)
elif self.podman_user:
self.add_expose(listen_port)
self.tunnel_local_endpoint[tu... | This function configures a multiplexed Trojan client tunnel by creating a local endpoint, setting up a muxer with specified size, and adding multiple client instances. Each client uses unique ports within the mux range, sharing tunnel parameters like password, remote address, target port, and optional SSL SNI. It enabl... | def add_trojan_client_mux(self, tunnel_name, mux_size, listen_port, tunnel_password, remote_addr, target_port, ssl_sni=None):
self._add_tunnel_local_endpoint(tunnel_name, listen_port)
self.add_muxer(listen_port, listen_port+1, mux_size)
for mux_idx in range(mux_size):
self._do_add_tr... |
def show_header(self):
'''Prints the header of the menu'''
print("------------------------ BLACKJACK MENU ------------------------ (type 'back' to return from command)")
print(f"Current players: {self.get_names()}")
print("---")
print("add player(1), remove player(2), add funds(3... | The code displays a menu of commands, loops to accept user input, and redirects to corresponding functions like adding/removing players or starting a blackjack round. It ensures at least one player exists before starting the game and exits on command '0'. | def display_menu(self):
'''Displays users command options, and redirects user to designated function'''
menu = True
while menu:
os.system("clear")
self.show_header()
user_input = input("command: ")
if user_input == '1':
self.prompt_a... |
def get_key(messages):
return hashlib.sha256(json.dumps(messages, sort_keys=True).encode()).hexdigest()
def parse_response(response, messages, **kwargs):
n = kwargs.get('n', 1)
stream = kwargs.get('stream', False)
if stream:
return parse_stream(response, messages, n=n)
results = []
for ... | The function `complete` generates responses using OpenAI's ChatCompletion API, with optional caching. It checks if a cached result exists for the given `messages` key; if not, it sends the request to the specified model, applies temperature settings, and parses the response. The result is returned, either from cache or... | def complete(messages=None, model='gpt-4', temperature=0, use_cache=False, **kwargs):
if use_cache:
key = get_key(messages)
if key in cache:
return cache.get(key)
response = openai.ChatCompletion.create(
messages=messages,
model=model,
temperature=temperature,... |
def _join_lobby(self, desired_name):
tries = 50
while tries:
if tries < 50:
print('Failed to connect. Retrying...')
tries -= 1
try:
code, res = self._make_request(
'/players',
data = {'name': desired_name, 'persistent': self.persistent}
)
if ... | The code's main task is to play a game by joining a lobby, creating a bot via a factory, and repeatedly sending moves generated by the bot until the game ends. It handles server connection issues by reconnecting and restarting the process, ensuring continuous gameplay with error logging and recovery. | def play(self, bot_factory, desired_name):
"""
Parameters
----------
bot_factory : callable(state : BoardData, assigned_name : string) -> Bot
A class constructor or factory that returns an instance of Bot
desired_name : string
The prefered name of the bot. Will be used unless taken b... |
def terminal(self):
# The game is finished when either the human or the ai board has no seeds left
flag_1 = flag_2 = False
for i in range(1, 7):
if(sum(self.array[1:7]) == 0):
flag_1 = True
elif(sum(self.array[7:]) == 0):
flag_2 = True
return flag_1 or flag_2... | This function implements the Max player's turn in the Minimax algorithm with Alpha-Beta pruning, recursively evaluating accessible game states to determine the optimal move. It checks terminal states, applies depth limits, iterates over all reachable states, and updates the maximum value while pruning irrelevant branch... | def max_value_2_ABP(self, depth=0, maxDepth=5, alpha=float('-inf'), beta=float('inf')):
# Check if a state is terminal
if self.terminal():
return (self.state_value(), self)
# Otherwise check if maximum depth of DFS iteration is reached
elif(depth == maxDepth):
return (self.utility(), self)
... |
def terminal(self):
# The game is finished when either the human or the ai board has no seeds left
flag_1 = flag_2 = False
for i in range(1, 7):
if(sum(self.array[1:7]) == 0):
flag_1 = True
elif(sum(self.array[7:]) == 0):
flag_2 = True
return flag_1 or flag_2... | This function implements the minimax algorithm with alpha-beta pruning to determine the minimum value for the current player (H) in a game tree search. It recursively evaluates all accessible states, considering depth constraints, and optimizes the search by pruning branches that cannot influence the final decision, th... | def min_value_2_ABP(self, depth=0, maxDepth=5, alpha=-100000, beta=100000):
# Check if a state is termina
if self.terminal():
return (self.state_value(), self)
# Otherwise check if maximum depth of DFS iteration is reached
elif(depth == maxDepth):
return (self.utility(), self)
depth +=... |
def format_or(clause):
result_set = set()
if (clause.p2 == None):
return clause
all_variables = clause.p1.get_variables_wn() | clause.p2.get_variables_wn() #Get all variables in the or clause (as tuples)
while(len(all_variables)!= 0): #For all variables
i = all_variables.pop()
... | The code transforms a logical clause into a conjunction (AND) of multiple OR clauses. It processes each OR clause tuple by converting variable literals (with negation if needed) into formulas, combines them with OR operations, and then aggregates all OR results with AND operations. The main task is to standardize the c... | def format_and(clause):
if (clause.formula_type == 'Or'):
return format_or(clause)
or_clauses = clause.get_or_clauses() #Get the sets of or clauses tuples
result_clause = []
while (len(or_clauses)!=0): #For all or clause tuples
or_clause_tupples = or_clauses.pop()
or_clause = []... |
def define_chemical_system():
# Construct the chemical system with its phases and species
db = Database('supcrt98.xml')
editor = ChemicalEditor(db)
db = Database('supcrt98.xml')
editor = ChemicalEditor(db)
editor.addAqueousPhase('H2O(l) H+ OH- Na+ Cl- NO3- CO2(aq)')
# editor.addMineral... | The code simulates reactive transport by defining a chemical system, initial/boundary conditions, and partitioning species. It initializes mesh cell states, uses an equilibrium solver, and iterates through transport and chemical reactions over time steps. The loop updates states, progresses time, and outputs results wi... | def simulate():
# Construct the chemical system with its phases and species
system = define_chemical_system()
# Define the initial condition of the reactive transport modeling problem
state_ic = define_initial_condition(system)
# Define the boundary condition of the reactive transport modeling pro... |
def define_chemical_system():
# Construct the chemical system with its phases and species
db = Database('supcrt98.xml')
editor = ChemicalEditor(db)
editor.addAqueousPhaseWithElements('H N O Na Cl') .setChemicalModelPitzerHMW() .setActivityModelDrummondCO2()
system = ChemicalSyst... | The code simulates reactive transport by integrating chemical reactions and species transport. It initializes a chemical system, sets initial/boundary conditions, partitions fluid/solid species, and sets up mesh cells. Using an equilibrium solver, it iteratively computes transport and chemical reactions across time ste... | def simulate():
# Construct the chemical system with its phases and species
system = define_chemical_system()
# Define the initial condition of the reactive transport modeling problem
state_ic = define_initial_condition(system)
# Define the boundary condition of the reactive transport modeling pro... |
def _chunk_rock(self, parameters, raw_rock):
domain_nx = parameters["rock_simulation"]["simulation_rock_nx"]
domain_ny = parameters["rock_simulation"]["simulation_rock_ny"]
chunked_subdomain_num_x = parameters["sediment_deposition"]["chunked_subdomain_num_x"]
chunked_subdomain_num_y = pa... | The code deposits sediment into a simulated rock by scaling the rock data to 0-255, chunking it into subdomains, randomly selecting subdomains for sediment deposition, combining them into a sediment-bearing domain, saving the result as a file, generating a visual output, and cleaning temporary directories if specified. | def deposit(self, simulation_rock, parameters):
parameters["work_dir"] = os.path.abspath(parameters["work_dir"])
parameters["sediment_deposition"]["sediment_bearing_rock_file"] = os.path.abspath(
parameters["sediment_deposition"]["sediment_bearing_rock_file"])
# transform simulation ... |
def nms(dets, scores, thresh, max_dets=1000):
"""Non-maximum suppression.
Args:
dets: [N, 4]
scores: [N,]
thresh: iou threshold. Float
max_dets: int.
"""
y1 = dets[:, 0]
x1 = dets[:, 1]
y2 = dets[:, 2]
x2 = dets[:, 3]
areas = (x2 - x1) * (y2 - y1)
order = sco... | The main task of the code is to detect objects in an image based on specified categories using a pre-trained model. It processes detection outputs, filters valid boxes, computes object scores via text-visual embeddings, ranks results, and returns detected objects with their coordinates and scores. It optionally visuali... | def detect(
self,
image_path,
category_names,
detection_path='./detections',
vild_params=None,
plot_on=False,
prompt_swaps=[("block", "cube")],
):
category_name_string = ";".join(category_names)
#################################################... |
def get_name_list(sql_dir):
name_list = list()
for key in sql_dir:
if key["againstName"] not in name_list:
name_list.append(key["againstName"])
return name_list
def outcome_dict(sql_dir, name_list=0):
if type(name_list) is not list:
name_list = get_name_list(sql_dir)
out... | The main task of the code is to retrieve and compile user outcome data from an SQL directory. It gathers a list of keys (user identifiers), corresponding outcome values, and percentage statistics. The function returns four elements: the outcome dictionary, key list, aggregated value list, and percentage dictionary for ... | def outcomePerUser(sql_dir):
value_list = list()
key_list = get_name_list(sql_dir)
outcome_dicts = outcome_dict(sql_dir)
percentage_dict = percentageDict(sql_dir)
for key in outcome_dicts:
value_list.append(outcome_dicts[key])
return outcome_dicts, key_list, value_list, percentage_dic... |
def _wrap_candidates(raw_candidates):
"""
Group the raw candidate iterable by each candidate's group key,
and attach id and timestamp to each wrapped candidate. Create a
generator which returns groups of wrapped candidates.
"""
# The raw candidates should be in order:
# assert raw_candidates... | The main task of the code is to search for the optimal path by grouping candidates into states, selecting winners from each state, and reconstructing a reversed sequence of candidates' bodies as the final path. It iteratively yields segments of the path, ensuring the last segment is included after processing all winner... | def offline_search(self, candidates):
"""
Search for the best path among `candidates`. Candidates will be
grouped into states by each candidate's group key.
It generates a path, a sequence of winners that are chosen
from their states respectively.
"""
groups = _w... |
def neighbours(game_state, loc, filter=None):
"""
list<list<dict>>, list<int>, function -> list<list<int>>
"""
x, y = loc
res = [[x-1, y-1], [x, y-1], [x+1, y-1],
[x-1, y], [x+1, y],
[x-1, y+1], [x, y+1], [x+1, y+1]]
loc = fixLoc(loc)
res = [loc for loc in res if inB... | This function automatically reveals neighboring cells in a game state when the number of flagged mines around a cell matches the cell's indicated mine count, thereby safely uncovering all unflagged adjacent cells. | def auto(game_state, loc):
"""
list<list<dict>>, list<int> -> list<list<dict>>
modifies game_state and returns modified game_state after auto is invoked
on the cell
:param game_state: game state as defined in generator.py
:param loc: the (x, y) location of the cell you want to invoke auto on
... |
def VarD(self, t):
res = self.ED_sq(t) - self.ED(t)**2
return res
def EM_sq(self, t):
S_t_FFB = self.strategy[t, 2]
res = (3 - 2 * S_t_FFB + S_t_FFB**2) / 3
return res
def EDc(self, t):
if t in self.EDc_cache: return self.EDc_cache[t]
if t == 23: return self.ED(2... | This function calculates the variance component VarDc for time t recursively. If t=23, it directly returns VarD(23). Otherwise, it uses a strategy matrix: if strategy[t,2] is 0, it sums VarD(t) and VarDc(t+1). Otherwise, it combines VarD(t) with terms involving EM_sq, EDc, EM, a_t, and VarM, applying addition/subtracti... | def VarDc(self, t):
if t == 23: return self.VarD(23)
if self.strategy[t, 2] == 0:
res = self.VarD(t) + self.VarDc(t+1)
else:
part1 = self.VarD(t)
part2 = self.EM_sq(t) * (self.VarDc(t+1) + self.EDc(t+1)**2)
part3 = (self.EM(t) * self.EDc(t+1))**2
... |
def close_serial(self):
if self.serial.isOpen():
self.server.remove_reader(self.serial)
self.serial.close()
def close_client(self):
if self.client:
self.server.remove_reader(self.client)
self.client.close()
self.client = None
def close_server(s... | This function reconfigures serial and TCP settings based on a new config. It skips changes if no differences exist. For serial, it closes the port if changed and updates attributes. For TCP, it restarts client/server if the address changed, or adjusts socket options otherwise. It logs all configuration changes and upda... | def reconfig(self, config):
if self.config == config:
name = self.config['serial']['port']
logging.info('reconfig %r: no changes, so skip it', name)
return
old_ser, new_ser = self.config['serial'], config['serial']
if old_ser != new_ser:
if old_ser... |
def filter_cols(dataframe: pd.DataFrame) -> tuple:
"""
Filter unwanted columns from our nba dataframe for our linear regression model
Args:
df -> The nba dataframe
Returns:
tuple containing (nba player stats, nba player win shares)
"""
# Columns we want to r... | The main task of the code is to perform linear regression analysis on NBA player statistics to predict wins, using various feature transformations (PCA, standardization, MinMax scaling) and determine the optimal number of PCA dimensions needed to retain 95% of the original data's variance. It prepares multiple datasets... | def main() -> None:
"""
Main functionality of our linear regression
"""
# Gather the necessary features
nba_stats, nba_ws = filter_cols(get_nba_df(from_year=2000))
nba_pca = apply_pca(nba_stats.fillna(0), dimensions=5)
std_nba = apply_scaling(nba_stats.fillna(0))
mm_nba = apply_scali... |
def populateMissingRow(self, board):
for r, row in enumerate(board):
if row.count('.') == 1:
value = 45 - self.stringSum(row)
c = row.index('.')
board[r][c] = str(value)
def populateMissingCol(self, board):
for c in range(9):
... | The main task of the code is to iteratively fill in a Sudoku board by repeatedly applying row, column, and 3x3 grid population methods, along with identifying unique values in subsets, until the board stabilizes with no further changes. This loop continues until the board state stops evolving between iterations. | def autoFillIn(self, board):
prevBoard = None
while prevBoard != board:
prevBoard = copy.deepcopy(board)
self.populateMissingRow(board)
self.populateMissingCol(board)
self.populateMissing3x3Grid(board)
self.findUniquesInSubset(board) |
def autoFillIn(self, board):
prevBoard = None
while prevBoard != board:
prevBoard = copy.deepcopy(board)
self.populateMissingRow(board)
self.populateMissingCol(board)
self.populateMissing3x3Grid(board)
self.findUniquesInSubset(board)
def printB... | The code solves a Sudoku puzzle by modifying the board in-place through auto-filling obvious numbers, performing trial-and-error backtracking, and verifying the solution. It prints the board at key steps to track progress, ensuring the final board adheres to Sudoku rules. | def solveSudoku(self, board) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.autoFillIn(board)
self.printBoard(board)
self.trialAndError(board)
self.printBoard(board)
self.checkBoard(board, done=True) |
def HRA(self):
return (0.18*(Employee.sal))
def DA(self):
return (0.1*(Employee.sal))
def Gross(self):
return ((Employee.sal)+self.HRA()+self.DA())
def Net(self):
return (0.9*self.Gross()) | The main task of the code is to display an employee's details, including ID, name, salary, and calculated components like HRA, DA, Gross Salary, and Net Salary. It prints these values by invoking instance methods (HRA(), DA(), Gross(), Net()) to compute the respective salary components and formats the output for clarit... | def display(self):
print("The details of employee are: ")
print("ID:",Employee.ID)
print("Name:",Employee.name)
print("Salary:",Employee.sal)
print("HRA:",self.HRA())
print("DA:",self.DA())
print("Gross Salary:",self.Gross())
print("Net Salary:",self.Net()... |
def buildargparser():
# desc = 'dedup files across branches in a mergerfs pool'
# usage = 'mergerfs.dedup [<options>] <dir>'
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
'dir',
type=str,
nargs='?',
default=None,
help='starting directory',... | The main task of the code is to calculate and report total deduplication savings in a mergerfs directory by scanning files, applying user-defined include/exclude filters, and using specified deduplication rules. It handles command-line arguments, validates the mergerfs directory, processes files recursively, accumulate... | def main():
sys.stdout = io.TextIOWrapper(
sys.stdout.buffer,
encoding='utf8',
errors='backslashreplace',
line_buffering=True,
)
sys.stderr = io.TextIOWrapper(
sys.stderr.buffer,
encoding='utf8',
errors='backslashreplace',
line_buffering=True,
... |
def update_conn_status(address):
if interrupt_thread(address):
return
modify_conn_states(address) # Create connection status
Thread(target=deletion_thread, args=(address)).start()
return
def get_conn_state(address, key):
try:
CONN_STATES[address]['SEMAPHORE'].acquire()
result... | This function processes incoming packets by verifying their structure, managing connection states, performing Diffie-Hellman key exchange, authentication, and command execution. It checks packet flags (SYN, AUTH, CRP), handles errors like corrupted data or invalid sequences, and sends appropriate responses. If valid, i... | def handle_packet(server, packet, address, args, config, no_auth=False):
# Update connection status
update_conn_status(address)
# Unpack received packet
unpacked_tuple = verify_and_unpack(packet, args)
key = get_conn_state(address, 'KEY')
(recv_flags, recv_seq, unpacked) = unpacked_tuple
if ... |
def init_map(self):
'''Intialize the map before each search
'''
self.found = False
self.vertices = []
self.vertices.append(self.start)
def sample(self, goal_bias=0.05, c_best=0):
'''Sample a random point in the area
arguments:
goal_bias - the possibili... | The code implements the RRT (Rapidly-exploring Random Tree) algorithm to find a path from a start to a goal point. It samples random points up to `n_pts` times, extending nodes toward these points while checking for goal reachability. If a path is found, it outputs the number of steps and path length; otherwise, it rep... | def RRT(self, n_pts=1000):
'''RRT main search function
arguments:
n_pts - number of points try to sample,
not the number of final sampled points
In each step, extend a new node if possible, and check if reached the goal
'''
# Remove previous resul... |
def init_map(self):
'''Intialize the map before each search
'''
self.found = False
self.vertices = []
self.vertices.append(self.start)
def sample(self, goal_bias=0.05, c_best=0):
'''Sample a random point in the area
arguments:
goal_bias - the possibili... | The main task of the code is to implement the RRT* (Rapidly-exploring Random Tree star) algorithm for path planning. It samples points, extends nodes toward them, and rewires the tree to optimize the path. The function iterates up to `n_pts` times, checking for a valid path from start to goal. If found, it outputs the ... | def RRT_star(self, n_pts=1000, neighbor_size=10):
'''RRT* search function
arguments:
n_pts - number of points try to sample,
not the number of final sampled points
neighbor_size - the neighbor distance
In each step, extend a new node if possible, and ... |
def init_map(self):
'''Intialize the map before each search
'''
self.found = False
self.vertices = []
self.vertices.append(self.start)
def path_cost(self, start_node, end_node):
'''Compute path cost starting from start node to end node
arguments:
start... | The main task of the code is to implement the Informed RRT* algorithm for path planning. It iteratively samples points, extends nodes toward them, and rewires the graph to optimize paths. Once a valid path is found, it constrains future sampling within an ellipsoid around the current best path, reducing search space. T... | def informed_RRT_star(self, n_pts=1000, neighbor_size=20):
'''Informed RRT* search function
arguments:
n_pts - number of points try to sample,
not the number of final sampled points
neighbor_size - the neighbor distance
In each step, extend a new node... |
def _cut_highest_btw_edge(self, edge_btw_tuple_list):
"""
remove edges with highest betweenness and also update the self.edges
:param edge_btw_tuple_list: need to be a [sorted] list, sorted by value
:return:
"""
# this is the edge you need to cut
temp_value = 0
... | The code iteratively identifies communities by removing edges with the highest betweenness, computing modularity at each step, and stopping when modularity no longer improves. It returns the optimal community structure sorted by size and node indices. | def extractCommunities(self):
"""
extract communities from butch of edge pairs
:return:
"""
max_modularity = float("-inf")
# reuse the betweenness dict
if len(self.betweenness_result_tuple_list) > 0:
# cut edges with highest betweenness
sel... |
def vedro_cfg(self) -> None:
self._generate_by_template(
file_path=self.__FILE_VEDRO_CFG,
template_name=self.__TEMPLATE_VEDRO_CFG
)
def config(self) -> None:
self._generate_by_template(
file_path=self.__FILE_CONFIG,
template_name=self.__TEMPLATE_CO... | The main task of the code is to orchestrate the initialization and configuration of multiple system components by sequentially invoking methods like `vedro_cfg`, `config`, `interfaces`, `contexts`, `helpers`, and `scenarios`, ensuring all necessary setup steps are executed in a structured manner. | def all(self) -> None:
self.vedro_cfg()
self.config()
self.interfaces()
self.contexts()
self.helpers()
self.scenarios() |
def load_prepare_data(conn):
cursor=conn.cursor()
cursor.execute("""
SELECT
c.name AS client_name,
e.exercise AS exercise_name,
td.weight,
td.sets,
td.reps
FROM training_data td
LEFT JOIN client c ON td.client_id = c.id
... | The main task of the code is to generate AI-driven workout prescriptions by selecting exercises, predicting training parameters (weight/sets/reps) using a machine learning model, allowing user modifications, and storing the data in a database. It handles input validation, similarity-based exercise recommendations, data... | def exercise_selector(conn, name):
if 'modifications' not in st.session_state:
st.session_state.modifications = None
if 'exercise_selector' not in st.session_state:
st.session_state.exercise_selector = False
if 'modified_df' not in st.session_state:
st.session_state.modified_df = ... |
def clear(self):
for i in range(9):
for j in range(9):
self.board.data[i][j].config(state=NORMAL)
self.board.data[i][j].delete(0, 'end')
self.board.data[i][j].configure(fg='black')
self.board.data[i][j].configure(bg='white')
sel... | The main task of the code is to generate a Sudoku puzzle by creating a valid solution board, randomly removing numbers to create missing cells, and updating the UI to display the puzzle with pre-filled digits in blue. It ensures the board is solvable, disables pre-filled cells, and returns a deep copy of the solution b... | def generate(self, solutionBoard):
solutionBoard = [[0 for _ in range(9)] for _ in range(9)]
self.clear()
for i in range(9):
for j in range(9):
self.board.data[i][j].configure(state=NORMAL)
missing_number = random.randint(1, 64)
for k in range(0, 9, 3... |
def get_type(self,L1,L2,epsilon):
type=-1;
if Criterion1(L1,L2,epsilon):
if Criterion2_1(L1,L2,epsilon):
type=self.COLLINEAR;
else:
type=self.DISTANT;
else:
if Criterion2_2(L1,L2,epsilon):
type=self.INTERSECTED;
... | This function calculates a value 'a' based on the geometric relationship between two lines (L1, L2) and a given epsilon. It determines the type of relationship (collinear, distant, intersected, skewed) using `get_type`, then computes 'a' via vector operations: cross products, norms, and reciprocal products, returning 0... | def get_a(self,L1,L2,epsilon):
a = 0
criterion,type = self.get_type(L1,L2,epsilon);
if type ==self.COLLINEAR:
a = 0
elif type == self.DISTANT:
alpha = self.get_alpha(L1,L2);
a = norm(cross(self.L1.z_hat,cos(alpha)*self.L2.v-self.L1.v))
elif typ... |
def get_type(self,L1,L2,epsilon):
type=-1;
if Criterion1(L1,L2,epsilon):
if Criterion2_1(L1,L2,epsilon):
type=self.COLLINEAR;
else:
type=self.DISTANT;
else:
if Criterion2_2(L1,L2,epsilon):
type=self.INTERSECTED;
... | The code initializes a class to analyze the spatial relationship between two lines (L1, L2), determining their type (collinear, intersected, skewed, etc.) and computing parameters like alpha, n, a, and t-values for further geometric processing, using an epsilon threshold for precision. | def __init__(self, L1, L2,epsilon):
self.L1 = L1
self.L2 = L2
self.COLLINEAR = 0
self.DISTANT = 1
self.INTERSECTED = 2
self.SKEWED = 3
self.epsilon = epsilon;
self.criterion,self.type=self.get_type(L1,L2,epsilon)
self.alpha = self.get_alpha(L1,L2)
... |
def detect_with_thresholds():
"""
Detect anomalies of historical data based on user-given thresholds.
Compare stored values with user-given thresholds and
identify values as anomalous when they are beyond the thresholds.
:return: detected anomalies with anomaly detection parameters
"""
json... | This function detects anomalies in historical data using either user-specified thresholds or a generalized ESD test. It returns detected anomalies with parameters and a 200 OK response if successful, selecting detection method based on the 'thresholds' request argument. | def detect_anomaly():
"""
Detect anomalies of historical data based on generalized ESD test or on user-given thresholds.
:return: detected anomalies with anomaly detection parameters and a 200 OK response if intended action is successful
"""
thresholds = request.args.get('thresholds')
if thres... |
def extract(data_type, date, accuracy, freq=False):
"""
Extract data from a database.
"""
try:
conn = get_db_connection()
cur = conn.cursor()
cur.execute(f"SELECT aggregation_mode, aggregation_interval"
f" FROM {TABLE} WHERE data_type = '{data_type}'")
... | This function predicts missing values in time series data using the Freedman-Diaconis Estimator, validating input parameters, extracting/preprocessing data, cleaning anomalies, and returning structured prediction results with metadata including date, aggregation mode, and accuracy level. | def predict_with_freedman_diaconis_estimator():
"""
Predict with Freedman Diaconis Estimator.
:return: a prediction with prediction parameters
"""
json = request.get_json()
data_type = json['type']
date = json['date']
accuracy = json['accuracy']
if (data_type is None) or (date is N... |
def extract(data_type, date, accuracy, freq=False):
"""
Extract data from a database.
"""
try:
conn = get_db_connection()
cur = conn.cursor()
cur.execute(f"SELECT aggregation_mode, aggregation_interval"
f" FROM {TABLE} WHERE data_type = '{data_type}'")
... | The function performs time series forecasting using Exponential Smoothing. It extracts and preprocesses data based on input parameters, trains a damped exponential smoothing model, predicts missing values up to a specified end date, and returns a formatted prediction with metadata. The process includes validation, logg... | def predict_with_exponential_smoothing():
"""
Predict with Exponential Smoothing.
:return: a prediction with prediction parameters
"""
json = request.get_json()
data_type = json['type']
date = json['date']
accuracy = json['accuracy']
if (data_type is None) or (date is None) or (acc... |
def extract(data_type, date, accuracy, freq=False):
"""
Extract data from a database.
"""
try:
conn = get_db_connection()
cur = conn.cursor()
cur.execute(f"SELECT aggregation_mode, aggregation_interval"
f" FROM {TABLE} WHERE data_type = '{data_type}'")
... | The function uses Prophet to forecast future data values for a specified date and type, leveraging input parameters like accuracy. It validates inputs, extracts/transforms historical data, trains a Prophet model, predicts missing values, and returns a structured prediction with details like date, type, and forecasted v... | def predict_with_prophet():
"""
Predict with Prophet.
:return: a prediction with prediction parameters
"""
json = request.get_json()
data_type = json['type']
date = json['date']
accuracy = json['accuracy']
if (data_type is None) or (date is None) or (accuracy is None):
abor... |
def predict_with_exponential_smoothing():
"""
Predict with Exponential Smoothing.
:return: a prediction with prediction parameters
"""
json = request.get_json()
data_type = json['type']
date = json['date']
accuracy = json['accuracy']
if (data_type is None) or (date is None) or (acc... | The main task of the code is to perform time-series predictions using one of three models—Exponential Smoothing, Prophet, or Freedman Diaconis Estimator—based on the 'predictionModel' parameter from the request. It returns the prediction results along with a 200 OK status code to indicate successful execution. | def predict():
"""
Predict with Freedman Diaconis Estimator, Exponential Smoothing or Prophet.
:return: a prediction with prediction parameters and a 200 OK response if intended action is successful
"""
prediction_model = request.args.get('predictionModel')
if prediction_model == 'ExponentialS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.