dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def apply_zoom_lines(self,zoom_delta,mouse_x,mouse_y):
self.lines_start_x,self.lines_start_y = self.recalculate_list_zoom_positions(zoom_delta,mouse_x,mouse_y,self.num_lines,self.lines_start_x,self.lines_start_y) #calculate zoom for start of line
self.lines_end_x,self.lines_end_y = self.recalculate_list... | The main task of the code is to apply a zoom transformation to multiple graphical elements (lines, compound lines, nodes, and pie nodes) based on a zoom delta and mouse coordinates, ensuring lines are rendered before nodes to maintain visual hierarchy with nodes appearing on top. | def apply_zoom_all(self,zoom_delta,mouse_x,mouse_y):
#we wish to render lines before nodes so nodes appear on top
self.apply_zoom_lines(zoom_delta,mouse_x,mouse_y) #zoom the lines
self.apply_zoom_compound_lines(zoom_delta,mouse_x,mouse_y) #zoom the compound lines
self.apply_zoom_nodes(zo... |
def download(self):
log("downloading", important=True)
self.index()
self.chems()
def process(self):
pages = self.pages["chems"]
lp = len(pages)
log("processing %s chemical pages"%(lp,), important=True)
for i in range(lp):
self.chemicals.append(Chem(self.chemcodes[i], pages[i]).data)
def save(self):
l... | The code initializes a NIOSH scraper by creating necessary directories, setting up data structures for storing scraped information (pages, chemical codes, and chemicals), and executing download, processing, and saving operations to organize and store the scraped data. | def __init__(self):
log("initializing niosh scraper")
for p in [NDIR, INDEX, CHEMS]:
if not os.path.isdir(p):
mkdir(p)
self.pages = {
"index": [],
"chems": []
}
self.chemcodes = []
self.chemicals = []
self.download()
self.process()
self.save()
log("scrape complete") |
def swapem(self):
self.translation = self._swap(self.fragment, self.swappers)
def log(self, *msg):
self.loud and print(*msg)
def bottomsup(self):
h = self.translation
flag = nextlast(h, self.flaggers)
while flag:
self.log("transing", flag, h[:100])
h = trans(h, flag, flags=self.flaggers, styles=self.sty... | The code's main task is to process a translation through a sequence of operations: swapping elements (`swapem`), logging the initial state, applying bottom-up processing (`bottomsup`), logging again, cleaning up the translation (`cleanup`), logging the final state, and returning the processed translation. The method tr... | def translate(self):
self.swapem()
self.log("\n======================\n", "prebot", self.translation[:200], "\n======================\n")
self.bottomsup()
self.log("\n======================\n", "preclean", self.translation[:200], "\n======================\n")
self.cleanup()
self.log("\n=====================... |
def trans(h, flag, rules=None):
rules = rules or flags[flag]
sflag = rules.get("start", "<%s>"%(flag,))
seflag = rules.get("startend")
esflag = rules.get("endstart")
eflag = rules.get("end", "</%s>"%(flag,))
tex = rules.get("tex")
while sflag in h:
start = getstart(h, sflag)
startend = seflag and h.index(sef... | This function processes a string `h` by replacing specified patterns with their corresponding values, then applies formatting steps including table translation, block-to-table conversion, header fixing, and cleanup to transform and structure the input into a properly formatted table output. | def h2l(h, depth=0):
for swap in swaps:
h = h.replace(swap, swaps[swap])
h = trans(h, "table", TABLE_FLAGS)
h = b2t(h)
h = fixhead(h, depth)
h = cleanup(h)
return h |
def pretex(doc, fname, fontonly=False):
fcfg = config.ctman.font
pname = os.path.join("build", "%s.tex"%(fname,))
if not fontonly and doc.logo:
iname = symage(doc.logo.path)
ff = getattr(doc, "font", None) or fcfg.family
fontdesc = ff and FONTFAM%(ff, ff) or ""
write(fontonly and fontdesc or read("tex/pre.tex")... | The function exports a document by generating a filename from the document's name, processing content based on its type, writing it to a Markdown file, converting it to PDF using a specified tool, and returning build status information including success/failure messages and file paths. It handles filename formatting, c... | def export(doc, data=None):
fname = doc.name.replace(" ", "_").replace("(",
"").replace(")", "").replace("/", "")
if doc.polytype == "document":
if doc.pretty_filenames:
fname = "%s_r%s"%(fname, doc.revision)
else:
fname = "_".join(str(datetime.datetime.now()).split(".")[0].split(" "))
data = "\\newpage... |
def extract(self, f, start=None, t="</div>", unquote=True):
s = self.getstart(f, start) + len(f)
bit = self.page[s : self.page.index(t, s)]
if unquote and '"' in bit:
bit = bit.split('"')[1]
return bit.strip()
def classification(self):
previtem = self.page.find("Lower Explosive Limit")
if previtem == -1:... | This code scrapes data from a webpage by extracting elements like name, classification, and various card types (CARDS, TCARDS, HCARDS, BCARDS). It populates a dictionary (`self.data`) with parsed information using methods like `extract`, `classification`, and `card/tcard`, handling different HTML structures and key for... | def scrape(self):
self.data["name"] = self.extract("<h1>", t="<")
log("%s %s"%(self.code, self.data["name"]), important=True)
self.data["classification"] = self.classification()
for name, flag in list(CARDS.items()):
self.data[name] = self.card(flag)
for name in TCARDS:
self.data[name] = self.tcard(name... |
def init(nodes, utilities, mainNode, decisionNum, evidencies):
#comment out for test inputs from file:
with fileinput.input() as stdin:
#with open(r'input1.txt') as stdin:
nodesNum = int(stdin.readline().rstrip())
for node in range(nodesNum):
raw_string = stdin.readline().rstrip... | The main task of the code is to perform a probabilistic decision-making process by initializing a model structure, querying relevant information from nodes based on evidences, and determining the optimal decision by evaluating utilities. It uses `init` to set up the model, `felsorolas_kerdezes` to gather query results,... | def main():
nodes = []
utilities = {}
mainNode = 0
decisionNum = 0
evidencies = []
nodes, utilities, mainNode, decisionNum, evidencies = init(nodes, utilities, mainNode, decisionNum, evidencies)
#calculate
Q = felsorolas_kerdezes(nodes[mainNode], evidencies, nodes)
for p in Q:
... |
def checkStates():
if isCrash == True:
print('Exit MotionCommanderHelper due to CRASH')
sys.exit(1)
def executeInstruction(instruction, MotionCommander, sleepTime, messageQueue):
print("MotionCommander." + instruction)
if (instruction.find("up") != -1) or (instruction.find("down") != -1... | The code's main task is to control a drone to follow a predefined path using a list of instructions, then return along the same path. It checks battery status, executes movement commands, handles early termination if the battery is low, and ensures the drone turns around to face its original direction before signaling ... | def goOutAndComeBackAlongSamePath(listOfGoOutInstructions, SyncCrazyflie, MotionCommander, sleepTime, messageQueue):
checkStates()
if isBatteryLow == False:
MotionCommander.take_off(0.3, 2.0)
time.sleep(sleepTime)
MotionCommander.down(0.1)
time.sleep(sleepTime)
listOfIns... |
def switchLeftRightUpDownForwardBackAndMovedistance(stringToReplaceIn):
if stringToReplaceIn.find("left") != -1:
return stringToReplaceIn.replace("left", "right")
if stringToReplaceIn.find("right") != -1:
return stringToReplaceIn.replace("right", "left")
if stringToReplaceIn.find("up") != -... | The function executes a reverse movement along the same path by adjusting the instruction's direction, ensuring flight height is within range, then triggering the motion command and pausing for a specified duration. | def executeCombackInReverseSamePathInstruction(instruction, MotionCommander, sleepTime, messageQueue):
print("MotionCommander." + switchLeftRightUpDownForwardBackAndMovedistance(instruction))
if (instruction.find("up") != -1) or (instruction.find("down") != -1):
instruction = getFlightHeightInRange... |
def checkStates():
if isCrash == True:
print('Exit MotionCommanderHelper due to CRASH')
sys.exit(1)
def executeInstruction(instruction, MotionCommander, sleepTime, messageQueue):
print("MotionCommander." + instruction)
if (instruction.find("up") != -1) or (instruction.find("down") != -1... | The function navigates a drone using provided instructions, checks battery status, and executes movements. If the battery isn't low, it ascends, performs tasks, and reverses the path to return. It handles interruptions due to low battery, logs the stopping point, and resumes reverse navigation from that point. The proc... | def goOutAndComeBackInReverseAlongSamePath(listOfGoOutInstructions, SyncCrazyflie, MotionCommander, sleepTime, messageQueue):
checkStates()
if isBatteryLow == False:
MotionCommander.take_off(0.3, 2.0)
time.sleep(sleepTime)
MotionCommander.down(0.1)
time.sleep(sleepTime)
... |
def __InEnableSaved(self, OP = False):
self.btnSave.setEnabled(OP)
self.btnDelete.setEnabled(OP)
self.btnConnect.setEnabled(OP)
self.cbStartTime.setEnabled(OP)
self.cbEndTime.setEnabled(OP)
self.sbEndTime.setEnabled(OP)
self.rbSeconds.setEnabled(OP)
self.r... | This code initializes a GUI application with a system tray icon, loads a UI from a .ui file, sets up a SQLite database, configures a table widget to display RPC entries, connects buttons and controls to their respective functions, and sets window properties like size, position, and flags. It handles RPC data retrieval,... | def __init__(self):
super(frmMain, self).__init__()
uic.loadUi('{0}/ui/frmMain.ui'.format(DIR_APP), self)
initial_sqlite(DIR_APP)
self.CONNECTED = False
self.CONNECTED_index = -1
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(icon_app(DIR_APP))
... |
def __resetRPC(self):
self.cbStartTime.setChecked(False)
self.cbEndTime.setChecked(False)
self.sbEndTime.setValue(180)
self.rbSeconds.setChecked(True)
self.rbMinutes.setChecked(False)
self.rbHours.setChecked(False)
self.edtClientID.setText('')
self.cbLarge... | This code creates a new PRC entry by prompting the user for a name, saving it to a database with default values, updating a table widget with the new entry, adjusting column sizes, and enabling UI features. It resets the RPC, inserts data into the database, populates the table with the new record, and loads the RPC con... | def __new(self):
txtRPCSaved, okPressed = QInputDialog.getText(self, '{0} ( {1} )'.format(APP_TITLE, APP_VERSION), 'Enter the name of the PRC :', QLineEdit.Normal, '')
if okPressed and txtRPCSaved != '':
self.__resetRPC()
RPC_DATA = {'name': txtRPCSaved,
'starttime': ... |
def __save(self):
index=(self.twSaved.selectionModel().currentIndex())
value=index.sibling(index.row(),0).data()
if self.rbSeconds.isChecked():
ENDTIMETYPE = 0
elif self.rbMinutes.isChecked():
ENDTIMETYPE = 1
elif self.rbHours.isChecked():
END... | The main task of the code is to handle RPC connection/disconnection logic, updating UI elements (icons, tooltips, button states) based on connection status, validating client ID input, and synchronizing table widget entries with connection state changes. It enables/disables controls, displays error messages, and manage... | def __connect(self):
CLIENT_ID = self.edtClientID.text()
if self.CONNECTED is False:
if len(CLIENT_ID) > 5:
try:
self.__save()
self.__updateRPCDiscord()
self.CONNECTED = True
ICON_ONLINE = icon_on... |
def load_obj(filename):
fobj = open(filename, "r").read()
file_list = fobj.split("\n")
for i in range(len(file_list)):
file_list[i] = file_list[i].strip(" ")
i = 0
while i < len(file_list):
line = file_list[i]
if line[0] == "#":
file_list.remove(line)
e... | This code initializes a 3D object with vertex and face arrays, loading from a file if unspecified. It sets properties like camera, color, and position, projects 2D coordinates, generates lighting colors, and translates the object based on its center. | def __init__(self, vertex_array= None , face_array = None,camera = rs.Camera(),face_color = None,
filename = "",name="def",remove= True):
"""(numpy.ndarray(N x 3), np.ndarray(M x 4))
^ (x,y,z) ^(a squarre shape)
example of vertex array:
[[-1. 0. 0.]
[ 0. ... |
def initializeSerial(deviceLoc):
port = serial.Serial(
port=deviceLoc,
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 1
)
return port;
def waitForResponse(portname, timeoutSec = 10):
response = []
done = 0
error = 0
numSec = 0
... | The code controls hardware axes (Z and R) to perform a scanning measurement task. It parses command-line arguments for axis positions, integration time, and calibration files, initializes serial devices, homes the Z-axis, sets digipot values, and iteratively moves axes to collect sensor data. Measurements are saved to ... | def main(argv):
# Default Values
zStart = 0
zSteps = 1
zDelta = 0
rSteps = 1
rDelta = 0
digipotStart = 175
digipotDelta = -1
digipotSteps = 1
intTime = 30
intChunk = 5
deviceSerialStepper = '/dev/ttyACM0'
deviceSerialImager = '/dev/ttyUSB0'
# Parse command line arguments
parser = argparse.Argumen... |
def resolve_data_path(config):
legal_entities_path = Path(config['data']['external_data_path']) / Path(config['data']['legal_entities'])
legal_entities = get_legal_entities(legal_entities_path)
chinese_data_path = Path(config['data']['external_data_path']) / Path(config['data']['chinese_data'])
toponyms... | The main task of the code is to preprocess text by normalizing case, removing punctuation, digits, parentheses, and extra spaces, while filtering out legal entities, toponyms, and stopwords to clean and standardize the input text for further NLP tasks. | def preprocess(text, config=None, legal_entities=None, stopwords=None, toponyms=None):
if config:
legal_entities, toponyms, stopwords = resolve_data_path(config)
text = unidecode(text)
text = text.lower()
text = re.sub(f"[{string.punctuation}]+", ' ', text)
text = re.sub(r'(?<=\b\w)\s*(?=\w... |
def check_collisions(self):
"""Check collisions that affect gameplay"""
#See if any projectile in the projectile group hit any zombie in the zombie group
collision_dict = pygame.sprite.groupcollide(self.projectile_group, self.zombie_group, True, False)
if collision_dict:
for ... | The main task of the code is to update the game state by decrementing the round time every second, checking collisions, adding zombies, verifying round completion, and determining game over conditions. It uses a frame counter to track time progression and triggers actions like zombie spawning and status checks to maint... | def update(self):
"""Update the game"""
#Update the round time every second
self.frame_count += 1
if self.frame_count % FPS == 0:
self.round_time -= 1
self.frame_count = 0
self.check_collisions()
self.add_zombie()
self.check_round_completi... |
def transaction_cost(file):
costs = {}
with open(file) as f:
for line in f.readlines():
line = line.split(',')
costs[int(line[0])] = float(line[2])
return costs
def load_graph(file, costs):
g = Graph()
with open(file) as f:
for line in f.readlines():
... | The code reads command-line arguments for graph and costs files, loads the graph with transaction costs, computes the longest path, and prints it. | def main():
if len(sys.argv) != 3:
sys.stderr.write("Usage:\n python %s graph_file costs_file\n" % sys.argv[0])
exit(-1)
else:
graph_file = sys.argv[1]
costs_file = sys.argv[2]
costs = transaction_cost(costs_file)
graph = load_graph(graph_file, costs)
pri... |
def requestPeriodicals() -> bytes:
periodicals_request = ei.GetPeriodicalsRequest(
current_client_version = defaults.current_client_version,
user_id = defaults.user_id,
rinfo = defaults.rinfo()
)
data = { 'data' : utils.encode(periodicals_request) }
return r... | The main task of the code is to fetch current event and contract data via an API, decode the response, and conditionally update local files with either event or contract information based on command-line arguments. It uses `requestPeriodicals()` to retrieve data, decodes it using `utils.decode()`, and triggers `updateE... | def main():
# api request to get current events
periodicals_response = requestPeriodicals()
periodicals = utils.decode(
ei.PeriodicalsResponse(), periodicals_response)
if "events" in sys.argv:
updateEvents(periodicals.events.events, defaults.event_file)
if "contracts" in sys.argv:
... |
def prepare_illustration_list():
prepare()
urls = []
# Process the first page
logging.info("Processing page 1")
content = get_url_content(NAVIGATE_BASE_URL)
urls.extend(find_illust_urls(content))
for page in range(2, PAGES + 1):
logging.info(f"Processing page {page}")
url = f... | The main task of the code is to execute different functions based on the value of the 'task' variable. If 'task' is "prepare_illustration_list", it prepares a list of illustrations; if "download_illustrations", it downloads them; and if "check_failed_downloads", it checks for failed downloads. The function acts as a di... | def main():
if task == "prepare_illustration_list":
prepare_illustration_list()
elif task == "download_illustrations":
download_illustrations()
elif task == "check_failed_downloads":
check_failed_downloads() |
def roulette(self, population: list[list[int]]) -> list[int]:
costs = [self.cost(pop) for pop in population]
worst = self.cost(self.worst(population))
diff = [(worst-c) for c in costs]
# print(logs)
max = sum([c for c in diff])
# print(max)
selection_probs = [c/ma... | The code implements an evolutionary algorithm loop that evolves a population over a specified number of iterations. It uses roulette selection, PMX crossover (with probability `px`), and inverse mutation (with probability `pm`) to generate new individuals. After each iteration, it tracks the best, worst, and mean fitne... | def alg_loop(self, iterations: int, tour_size: int, px: float, pm: float) -> tuple[int, list[int]]:
t = 0
population = self.population
f = open('test.csv', 'a')
while (t < iterations):
new_population = []
while (len(new_population) < self.population_size)... |
def plot_bondwise_comparison(self, sigma, threshold):
'''
*** included in generate_all_plots ***
create a plot for the 'bondwise' scoring method, but still using derivatives
Parameters
----------
sigma : float
Filter roll-off frequency expre... | The code generates multiple visualizations (plots) based on input parameters `sigma` and `threshold`, with optional `score_process` ('bondwise' or 'unified'). It creates bond-wise plots (comparison, cluster pairs, reference distances) only if `score_process` is 'bondwise', and always generates plots comparing regular/F... | def generate_all_plots(self, sigma, threshold, score_process='bondwise'):
'''
Parameters
----------
sigma : float
Filter roll-off frequency expressed in wavenumbers.
threshold : float
Value is multiplied by sigma and is a threshold to identify extrema in t... |
def plot_mesh(self):
if self.mesh_actor is not None:
return
self.mesh_actor = self.pl.add_mesh(
self.grid.clip_box(self.clip_box, invert=False),
show_edges=True,
# style="wireframe",
opacity=0.1,
smooth_shading=... | This method generates multiple plots based on flags and conditions: it plots mesh if enabled, updates epsilon if needed, and renders sources, monitors, boundaries, and field components when their respective flags are active. It ensures simulation initialization before plotting field components. | def _plot_all(self):
print("Called plot_all")
if self.show_mesh and mp.am_master():
self.plot_mesh()
print("Plotting epsilon")
if (not self.initialized) or self.update_epsilon:
self.plot_epsilon()
if self.plot_sources_flag:
self.plot_... |
def Q_1(conn, execution_time):
new_conn = load_database(conn)
cursor = new_conn.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """SELECT player_name, avg(statsbomb_xg) AS average_xGscore
FROM Shot s LEFT OUTER JOIN Even... | The code `run_queries(conn)` executes ten sequential database queries (Q_1 to Q_10) using a connection object, tracking each query's execution time in a list. After processing all queries, it prints each recorded time from the list. The primary task is to run a series of queries and log/print their individual execution... | def run_queries(conn):
execution_time = [0,0,0,0,0,0,0,0,0,0]
conn = Q_1(conn, execution_time)
conn = Q_2(conn, execution_time)
conn = Q_3(conn, execution_time)
conn = Q_4(conn, execution_time)
conn = Q_5(conn, execution_time)
conn = Q_6(conn, execution_time)
conn = Q_7(conn, execution... |
def get_name():
"""
Receives the name of the group or the singer
entered by the user
"""
step1 = 'What the name of the singer/group? (Enter a name)'
print(step1)
name_artist = input(">>> ")
token = get_token()
result = search_for_artist(token, name_artist)
return token, result
de... | The main task of the code is to create an interactive menu-driven program that retrieves and provides music-related information about a user's favorite artist. It prompts for an artist name, then offers options to explore their top songs, albums, or specific album tracks, with loops for repeated interactions. The progr... | def main():
"""
The main function of the program
Unites all parts of program and makes it work
"""
start_message = "Hey! Would you like to find out some information about\
your favourite singer?"
print(start_message)
token, result = get_name()
if not check_input1(result):
return... |
def get_sadf(logP, minSL, constant, lags, span):
endPoints = range(span, logP.shape[0] + 1)
sadf = pd.DataFrame(columns=['sadf'])
if not isinstance(logP, pd.DataFrame):
logP = logP.to_frame()
for end in endPoints:
out = get_bsadf(logP[end-span:end], minSL, constant, lags)
t, gsad... | The code detects trading signals for a given market using structural break analysis (SADF) on Binance data. It evaluates price trends, triggers a signal if thresholds are crossed, and loads pre-trained models to predict trade direction (long/short) and size. Confidence scores and statistical calculations determine bet ... | def detect_signal(client, market):
data = get_binance_data(client, dict[market])[:-1]
log_price = np.log(data.close)
sadf = get_sadf(log_price, minSL=100, constant='ct', lags=2, span=500)
signal = False
sPos, sNeg, h = 0, 0, 1
diff = sadf.diff()
for i in diff.index[1:]:
sPos, sNeg ... |
def preprocess(self, Xtrain, Ytrain):
self.C = list(set(Ytrain)) # classes
self.L = len(self.C) # number of classes
self.Q = cost_matrix(self.L) # misclassification cost matrix
Ytrain = np.array([self.C.index(x) for x in Ytrain]) # convert class vari... | The code performs a machine learning pipeline: preprocessing training data, training a model, conducting joint feature selection and classification on test data, and generating evaluation metrics. It calculates accuracy, average selected features, their standard deviation, and records training/testing times. The result... | def run(self, data):
# preprocessing
self.preprocess(data['Xtrain'], data['Ytrain'])
# training
train_time = self.fit()
# joint feature selection and classification
predictions, n_feat, fs_and_c_time = self.predict(data['Xtest'])
... |
def get_email():
while True:
email = input("Enter your email: ")
# Basic email format validation using regular expression
if re.match(r"[^@]+@[^@]+\.[^@]+", email):
return email
else:
print("Invalid email. Please enter a valid email.")
def get_password():
... | The function retrieves user email and password, generates a key, stores the credentials securely, and returns the loaded credentials for authentication or further processing. | def get_user_credentials() -> tuple:
email: str = get_email()
password: str = get_password()
create_key()
store_credentials(email, password)
return load_credentials() |
def cred_unstored() -> None:
with open(CRED_PATH, "r") as mail_file:
mail_stored: dict = json.load(mail_file)
os.environ[CRED_ENV] = mail_stored.get(CRED_ENV, "")
def load_credentials() -> tuple:
retrieved_encrypted_credentials: str = os.environ.get(CRED_ENV)
credentials: tuple = decrypt_credent... | The main task of the code is to retrieve credentials by attempting to load them from a file (CRED_KEY_PATH). If the file is not found, it switches to retrieving user-provided credentials. It handles PermissionErrors separately and prints general errors for other exceptions, ensuring credential retrieval with fallback m... | def credentials() -> tuple:
try:
with open(CRED_KEY_PATH, 'r') as file:
cred_unstored()
return load_credentials()
except FileNotFoundError:
return get_user_credentials()
except PermissionError:
handlePermissionError()
except Exception as e:
print("... |
def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pyg... | The code defines a game loop that continuously checks for user input, updates the player's ship movement, manages bullet behavior, and redraws the screen to create real-time gameplay. The loop runs indefinitely, ensuring responsive interaction and dynamic visual updates for the game. | def run_game(self):
"""Start the main loop for the game."""
while True:
# Watch for keyboard and mouse events.
self._check_events()
self.ship.update()
self._update_bullets()
self._update_screen() |
def _check_fleet_edges(self):
"""Respond appropriately if any aliens have reached an edge."""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""Respond to the ship being hit by an a... | The code updates alien positions, checks for collisions between the ship and aliens, and detects if aliens reach the screen's bottom. It first checks if the alien fleet hits an edge, updates alien positions, triggers a collision response if the ship is hit, and verifies if aliens have moved beyond the screen's lower bo... | def _update_aliens(self):
"""Check is the fleet is at an edge, then update the positions of all aliens in the fleet."""
self._check_fleet_edges()
self.aliens.update()
# Look for alien-ship collisions.
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._s... |
def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pyg... | The main task of the code is to start and maintain the game loop, continuously handling keyboard/mouse events, updating the player's ship, bullets, and aliens, and redrawing the screen to create real-time gameplay. | def run_game(self):
"""Start the main loop for the game."""
while True:
# Watch for keyboard and mouse events.
self._check_events()
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen() |
def findNewCentroids_new(initial_centroids, data_array):
clusters = assignSamplesToClusters(initial_centroids, data_array);
new_centroid_array = [];
for k,v in clusters.items():
if len(v) == 0:
new_centroid = k
else:
new_centroid = findMean(v);
new_centroid_ar... | The code performs K-means clustering by iteratively updating centroids until convergence. It calculates clusters and new centroids, checks if the change between iterations is minimal, and stops when centroids stabilize. The function returns the number of iterations and prints final centroids and loss. | def run_k_means_new(n, initial_centroids, sample_data):
iter_count = 0
while True:
iter_count += 1
# print("{0}".format(initial_centroids))
clusters, new_centroids = findNewCentroids_new(initial_centroids, sample_data);
# find the difference between initial and new centriods. If ... |
def parse_domain(self, domainfile):
"""Parses a PDDL domain file."""
with open(domainfile) as dfile:
dfile_array = self._get_file_as_array(dfile)
# Deal with front/end define, problem, :domain
if dfile_array[0:4] != ['(', 'define', '(', 'domain']:
print(
... | This code initializes a parser for domain and problem files in a planning system. It sets up data structures to store domain requirements, types, predicates, actions, and problem-specific elements like initial state and goals. If parsing is enabled, it reads and processes the provided domain and problem files, extracti... | def __init__(self, domainfile, problemfile, parse=True):
self.domain = '' # String
self.requirements = set() # [String]
self.type_list = set() # {String}
self.type_list.add('object')
self.types = {} # Key = supertype_name, Value = type
self.predicates = [] # [Predica... |
def display_grid():
print("\n")
print(grid[0] + " | " + grid[1] + " | " + grid[2] + " 1 | 2 | 3")
print(grid[3] + " | " + grid[4] + " | " + grid[5] + " 4 | 5 | 6")
print(grid[6] + " | " + grid[7] + " | " + grid[8] + " 7 | 8 | 9")
print("\n")
def handle_turn(player):
print(player + "'... | The code defines a function `play_game()` that initializes a game loop to handle player turns, checks for game-over conditions (win or tie), and displays the result. It alternates between players, processes each turn, and determines the winner or declares a tie once the game ends. | def play_game():
display_grid()
while game_running:
handle_turn(cur_player)
check_if_game_over()
flip_player()
if winner == "X" or winner == "O":
print(winner + " Won")
elif winner is None:
print("Tie") |
def analyze_samples(self,
method: XAIMethodsDict,
kind: str,
samples: TensorNumpy,
normalize: AnalysisNormalizeDict = {'bool_':True, 'kind': 'Sum'},
Analyze: OptionalList[AnalyzerBase] = None,
**kwargs: Dict
) -> TensorNumpy:
a... | The main task of the code is to perform an analysis on provided samples using a specified method and parameters. It checks for required attributes, initializes normalization if missing, selects an analysis approach based on the 'kind' parameter, computes results, and returns both the analysis tensor and computed statis... | def quick_analyze(self) -> tuple[TensorNumpy, AnalysisStatsDict]:
if self.model is not None and self.method is not None and self.kind is not None and self.samples is not None and bool(self.kwargs):
if self.normalize is None:
self.normalize = {'bool_': False, 'kind': ''}
if self.kind == 'letzgus':
... |
def clear_saved_token(self) -> None:
with dbm.open(KEY_DB.as_posix(), "c") as db:
if self.app_id in db:
del db[self.app_id]
def fetch_api_token(self) -> dict:
backend = BackendApplicationClient(client_id=self.app_id)
oauth = OAuth2Session(client=backend)
try:
... | The code's main task is to reset the authentication state by clearing saved tokens, fetching a new API token, saving it, and creating a client using the updated token. This ensures the client uses the latest credentials, typically for re-authentication or token refresh processes. | def reset(self):
self.clear_saved_token()
token = self.fetch_api_token()
self.token_saver(token)
self.client = self.create_client_for_token(token) |
def load_saved_token(self) -> dict:
with dbm.open(KEY_DB.as_posix(), "c") as db:
_token = db[self.app_id]
token = json.loads(self.decrypt(_token))
return token
def fetch_api_token(self) -> dict:
backend = BackendApplicationClient(client_id=self.app_id)
oauth = OAuth2S... | The code initializes a client by loading a saved token or fetching a new one if it's unavailable, then creates a client using the token. It handles token retrieval and storage, ensuring the client is properly configured with valid credentials. | def __init__(self, app_id: str, app_secret: str):
self.app_id = app_id
self.app_secret = app_secret
try:
token = self.load_saved_token()
except KeyError:
token = self.fetch_api_token()
self.token_saver(token)
self.client = self.create_client_fo... |
def conv_block(self, bottom, name, shape, strides=[1,1,1,1], padding="SAME",
has_bias=False, add_relu=True, add_bn=True, eps=1.0e-5):
"""Create a block composed of multiple layers:
a conv layer
a batch normalization layer
an activation layer
Args:
... | This code constructs a lightweight face detection model by processing an input image through a series of convolutional layers, residual blocks, and pooling operations. It generates a score tensor for face detection by combining features from different network depths, using padding, upsampling, and residual connections ... | def tiny_face(self, image):
"""Create a tiny face model.
Args:
image: an input image.
Returns:
a score tensor
"""
img = tf.pad(image, [[0, 0], [3, 3], [3, 3], [0, 0]], "CONSTANT")
conv = self.conv_block(img, 'conv1', shape=[7, 7, 3, 64], strides=[1,... |
def pause_menu(surf, score):
print("paused")
saved = copy.copy(surf)
selec = Selector(250, 4,
["continue", do_nothing],
["back to menu", do_nothing],
["quit", do_nothing])
paused = True
while paused:
for event in pygame.event.g... | This code implements a shooter game where the player controls a character to shoot enemies, with dynamic difficulty adjustment, bullet mechanics, collision detection, and score tracking. It initializes game elements, handles user input, spawns enemies, updates game state, and renders visuals, returning the player's sco... | def shooter_game(surf, user_shooter: ShooterDatabase):
pygame.init()
ADDENEMY = pygame.USEREVENT + 3
pygame.time.set_timer(ADDENEMY, 2250)
difficulty = 1
change_difficulty = pygame.USEREVENT + 4
pygame.time.set_timer(change_difficulty, 25000)
recharge_time = user_shooter.recharge_speed[u... |
def get_params(ckpt_path):
"""Get params checkpoint."""
with tf.io.gfile.GFile(ckpt_path, "rb") as f:
data = f.read()
values = np.load(io.BytesIO(data))
params = recover_tree(*zip(*values.items()))
params = params["opt"]["target"]
return params
def modify_jax_params(jax_params):
modi... | The main task of the code is to convert pre-trained JAX model parameters into TensorFlow format by aligning variable names, mapping JAX weights to corresponding TF variables, and transferring them into a TensorFlow model for compatibility with TensorFlow workflows. | def port_jax_params(configs: dict, ckpt_path: str) -> Tuple[dict, tf.keras.Model]:
# Initialize TF Model.
print("Initializing model.")
tf_model = Model(**configs)
# Obtain a mapping of the TF variable names and their values.
tf_model_variables = tf_model.variables
tf_model_variables_dict = {}
... |
def make_shape_even(image):
"""Pad the image to have even shapes."""
height, width = image.shape[0], image.shape[1]
padh = 1 if height % 2 != 0 else 0
padw = 1 if width % 2 != 0 else 0
image = tf.pad(image, [(0, padh), (0, padw), (0, 0)], mode="REFLECT")
return image
def mod_padding_symmetric(im... | The code processes input images through a model (e.g., MAXIM) for tasks like super-resolution, handling dynamic resizing, geometric ensembling, and target comparisons. It normalizes images, adjusts resolutions, predicts outputs, computes PSNR scores, and saves results. The function supports multi-scale outputs, model r... | def _process_file(i):
print(f"Processing {i + 1} / {num_images}...")
input_file = input_filenames[i]
input_img = np.asarray(Image.open(input_file).convert("RGB"), np.float32) / 255.0
if FLAGS.has_target:
target_file = target_filenames[i]
target_img = (
... |
def moveship(self, input):
"""
moves ship
"""
if self._animator is None:
if self._ship is not None and input.is_key_down('left'):
self._ship.x -= SHIP_MOVEMENT
self._ship.x = max(self._ship.x, SHIP_WIDTH/2)
if self._ship is not None... | This code updates the game state by moving the ship, aliens, and bolts, checking if aliens have crossed the defense line, removing aliens, and determining victory when all aliens are eliminated. | def update(self, input, dt):
"""
updates the wave to move ship aliens and bolts
"""
list = []
for x in range(len(self._aliens[0])):
for y in range(len(self._aliens)):
if self._aliens[y][x] is not None:
list.append(self._aliens[y][x]... |
def is_recycler_move_legal(self, x1, y1, x2, y2):
last_card_x1 = self.last_card_placed.get_first_cell().get_x_coordinate()
last_card_y1 = self.last_card_placed.get_first_cell().get_y_coordinate()
last_card_x2 = self.last_card_placed.get_second_cell().get_x_coordinate()
last_card_y2 = sel... | This function attempts to move two cards from their current positions to a new location by checking legal move conditions, removing the original cards, and placing the final card. If successful, it updates the game state; otherwise, it reverts changes and returns False. | def move_card(self, rotation, first_cell, second_cell, final_card):
x1 = first_cell.get_x_coordinate()
y1 = first_cell.get_y_coordinate()
x2 = second_cell.get_x_coordinate()
y2 = second_cell.get_y_coordinate()
if self.is_recycler_move_legal(x1, y1, x2, y2) is False:
r... |
def get_char_probs(texts, predictions, tokenizer):
results = [np.zeros(len(t)) for t in texts]
for i, (text, prediction) in enumerate(zip(texts, predictions)):
encoded = tokenizer(text,
add_special_tokens=True,
return_offsets_mapping=True)
... | The function determines the optimal threshold (0.2–0.8) to maximize scoring accuracy by iteratively evaluating predictions against labels. It processes validation texts to compute character-level probabilities, generates predictions for each threshold, and compares them to ground-truth labels. The threshold yielding th... | def get_result(valid_folds, predictions, CFG):
max_score = 0
max_th = 0.2
valid_texts = valid_folds['pn_history'].values
char_probs = get_char_probs(valid_texts, predictions, CFG.tokenizer)
valid_labels = create_labels_for_scoring(valid_folds)
for th in [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]:
... |
def prepareBatch(self, name: str):
"""
prepare the batch for insertion to the database
@param name: the feed name
"""
self.batches[name].index = self.batches[name]['url']
self.batches[name].index.name = 'url'
del self.batches[name]['url']
self.batches[nam... | (The function inserts a batch of data into a database, checking its size before insertion if specified. If the batch is ready or size validation is skipped, it prepares the batch, logs the insertion attempt, and uses SQLAlchemy's `to_sql` to append data. On failure (e.g., database errors), it retries the insertion with... | def insertBatch(self, name: str, sizeCheck: bool = True, retry: bool = False) -> None:
"""
insert batch into database if batch is ready or batchCheck is false
:param name: feed name
:param batchCheck: should the batch be checked for size?
:return:
"""
if sizeChec... |
def compare_before_writing_file(self):
"""
A utility method that checks if there are offsets for each of the
columns.
Returns
-------
bool
True if the sizes of offsets and column names are equal and
False otherwise.
"""
if ... | The method creates a fixed-width file by writing random data if the number of columns matches their corresponding offsets. It raises an exception and aborts if there's a mismatch between column counts and offsets, ensuring data integrity before file creation. | def create_fixed_width_file(self):
"""
Method to create a fixed width file.
Raises
------
Exception
if there is a mismatch between the number of columns and their
corresponding offsets.
Returns
-------
None.
"""
... |
def maskBarra(mask):
a = 32-mask
mask = '1'*mask + '0'*a
out = ''
for i in range(32):
out+=mask[i]
if i%8==7 and i>0:
out+='.'
return convertirDecimal(out[:-1])
def direccionRed(ip,mask=None):
claseip = claseIp(ip)
ip = convertirBinario(ip)
if not(mask):
... | The main task of the code is to generate subnets from a given IP address by dividing it into a specified number of subnetworks (subnets). It calculates subnet addresses, host ranges, and mask details, ensuring the number of subnets is a power of two. The function outputs each subnet's address and host count in a format... | def subRedes(ip:str,cantidad:int,mask:str=None,maskbarra:int=None):
"""
:params ip: Direccion IP
:param cantidad: Cantidad de redes
:param mask: mascara a usar
:param maskbarra: mascara en formato barra ej: 22
"""
if maskbarra:
mask = maskBarra(maskbarra)
data = direccionRed(ip,... |
def lift(self, scores_source, scores_target, nodes_features_matrix_proj, edge_index):
"""
Lifts i.e. duplicates certain vectors depending on the edge index.
One of the tensor dims goes from N -> E (that's where the "lift" comes from).
"""
src_nodes_index = edge_index[self.src_no... | The code implements a graph attention network (GAT) layer. It projects node features, computes attention scores via edge-based scoring functions, applies softmax for normalization, aggregates neighbor features with learned attention weights, and incorporates residual connections. The process updates node representation... | def forward(self, data):
### Step 1: Linear Projection + regularization
in_nodes_features, edge_index = data # unpack data
num_of_nodes = in_nodes_features.shape[self.nodes_dim]
assert edge_index.shape[0] == 2, f'Expected edge index with shape=(2,E) got {edge_index.shape}'
# sh... |
def extract_prefixes(json_data):
"""Extract prefixes from JSON-LD data."""
prefixes = {}
def add_prefix(uri):
prefix = uri.rsplit('#', 1)[0] + '#' if '#' in uri else uri.rsplit('/', 1)[0] + '/'
if prefix not in prefixes.values():
prefixes[f"p{len(prefixes)}"] = prefix
d... | The code generates an OWL ontology from JSON-LD data by extracting prefixes, processing entities, consolidating classes, and writing Turtle-formatted output. It consolidates properties, resolves URIs with prefixes, and defines classes and object properties with domains/ranges. The result is saved as 'Ontology.ttl', inc... | def generate_ontology(jsonld_data_list):
classes = set()
properties = {}
defined_entities = {} # Keep track of defined entities and their types
all_prefixes = {}
# Process JSON-LD data
for json_data in jsonld_data_list:
prefixes = extract_prefixes(json_data)
all_prefixes.update... |
def get_stl10_train_unlabeled_embedding_dataset(transform=None):
return torch.utils.data.ConcatDataset([
get_stl10_train_embedding_dataset(transform),
get_stl10_unlabeled_embedding_dataset(transform)
])
def get_stl10_test_embedding_dataset(transform=None):
return EmbeddingDatasetWrapper(
... | The function trains a student model for zero-shot classification on STL10 using precomputed embeddings. It initializes datasets if not provided, creates a classification model with specified architecture, and trains it with parameters like learning rate, batch size, and temperature. The model leverages CLIP text embedd... | def train_student_zero_shot(
f_name,
output_dir: str,
arch: str,
temperature: float=1.,
train_dataset = None,
test_dataset = None
):
if train_dataset is None:
train_dataset = get_stl10_train_unlabeled_embedding_dataset()
if test_dataset is None:
... |
def get_stl10_train_unlabeled_embedding_dataset(transform=None):
return torch.utils.data.ConcatDataset([
get_stl10_train_embedding_dataset(transform),
get_stl10_unlabeled_embedding_dataset(transform)
])
def get_stl10_test_embedding_dataset(transform=None):
return EmbeddingDatasetWrapper(
... | The main task of the code is to train a student embedding model using STL-10 datasets for unlabeled training and test data. It leverages CLIP-generated text embeddings, with optional weighting of loss based on nearest-neighbor embedding distances. The model architecture is specified by 'arch', trained for 50 epochs wit... | def train_embedding_text(output_dir: str, arch: str, train_dataset=None,
test_dataset=None, weight_by_nearest_embedding=False, nearest_embedding_weight_std=1.):
if train_dataset is None:
train_dataset = get_stl10_train_unlabeled_embedding_dataset()
if test_dataset is None:
test_dataset =... |
def get_stl10_train_unlabeled_embedding_dataset(transform=None):
return torch.utils.data.ConcatDataset([
get_stl10_train_embedding_dataset(transform),
get_stl10_unlabeled_embedding_dataset(transform)
])
def get_stl10_test_embedding_dataset(transform=None):
return EmbeddingDatasetWrapper(
... | The function trains a student classification model using a pre-trained linear probe on STL10 embeddings for CIFAR10 labels. It loads a probe model from a checkpoint, configures a specified architecture, and trains it with given hyperparameters like learning rate, batch size, and temperature, using either provided or de... | def train_student_linear_probe(
f_name,
output_dir: str,
arch: str,
temperature: float=1.,
train_dataset = None,
test_dataset=None
):
if train_dataset is None:
train_dataset = get_stl10_train_unlabeled_embedding_dataset()
if test_dataset is None:
... |
def train_student_zero_shot(
f_name,
output_dir: str,
arch: str,
temperature: float=1.,
train_dataset = None,
test_dataset = None
):
if train_dataset is None:
train_dataset = get_stl10_train_unlabeled_embedding_dataset()
if test_dataset is None:
... | The main task of the code is to train a ResNet-18 model using zero-shot learning on filtered Open Images and STL-10 datasets. It employs a temperature parameter of 1.0, leveraging unlabeled data with a 90% filter, and evaluates performance using test embeddings derived from Open Images validation data. The function aim... | def train_resnet18_text_open_images_224_filter90():
train_student_zero_shot(
"data/experiments/cifar10_c_w_unlabeled/train_resnet18_text_open_images_224_filter90",
arch="resnet18",
temperature=1.,
train_dataset=get_stl10_open_images_filtered_dataset_90(),
test_dataset=get_stl... |
def train_student_zero_shot(
f_name,
output_dir: str,
arch: str,
temperature: float=1.,
train_dataset = None,
test_dataset = None
):
if train_dataset is None:
train_dataset = get_stl10_train_unlabeled_embedding_dataset()
if test_dataset is None:
... | This function trains a ResNet-18 model for zero-shot learning using filtered Open Images (90% dataset) and STL-10 datasets, with a temperature parameter of 100. It employs a student model trained on unlabeled data, leveraging text embeddings for open-image categories, and evaluates performance on STL-10 test embeddings... | def train_resnet18_text_open_images_224_filter90_temp100():
train_student_zero_shot(
"data/experiments/cifar10_c_w_unlabeled/train_resnet18_text_open_images_224_filter90_temp100",
arch="resnet18",
temperature=100.,
train_dataset=get_stl10_open_images_filtered_dataset_90(),
te... |
def train_student_zero_shot(
f_name,
output_dir: str,
arch: str,
temperature: float=1.,
train_dataset = None,
test_dataset = None
):
if train_dataset is None:
train_dataset = get_stl10_train_unlabeled_embedding_dataset()
if test_dataset is None:
... | This function trains a ResNet-18 model for zero-shot learning using filtered Open Images text embeddings and STL-10 data. It configures datasets with 96px transforms, applies a temperature scaling of 100, and trains with filtered 90% Open Images data, evaluating on STL-10 test embeddings. | def train_resnet18_text_open_images_96_filter90_temp100():
train_student_zero_shot(
"data/experiments/cifar10_c_w_unlabeled/train_resnet18_text_open_images_96_filter90_temp100",
arch="resnet18",
temperature=100.,
train_dataset=get_stl10_open_images_filtered_dataset_90(get_open_images... |
def roulette_wheel_selection(self, population, num_parents, limitation):
fitness_scores = self.create_fitness_scores(population, limitation)
sum_fitness = np.sum(fitness_scores)
selection_prob = fitness_scores / sum_fitness
cum_prob = np.cumsum(selection_prob)
parents = []
... | This function generates a new population by replacing individuals through selection, crossover, and mutation. It uses roulette wheel selection to choose parents, creates offspring via crossover, applies mutation, and evaluates fitness. The process iterates until the new population is filled, returning the updated popul... | def generation_replacement(
self, population, crossover_rate, mutation_rate, limitation
):
pop_new = []
j = 1
while j <= population.shape[0]:
parents = self.roulette_wheel_selection(population, 2, limitation)
offspring = self.generate_offspring(parents[0], p... |
def roulette_wheel_selection(self, population, num_parents, limitation):
fitness_scores = self.create_fitness_scores(population, limitation)
sum_fitness = np.sum(fitness_scores)
selection_prob = fitness_scores / sum_fitness
cum_prob = np.cumsum(selection_prob)
parents = []
... | This function performs deterministic crowding in a genetic algorithm. It iteratively selects parents via roulette wheel selection, generates offspring through crossover and mutation, and replaces parents with offspring based on fitness comparisons. Offspring with higher fitness deterministically replace parents, while ... | def deterministic_crowding(
self, population, crossover_rate, mutation_rate, limitation
):
pop_new = population.copy()
j = 1
while j <= population.shape[0]:
parents = self.roulette_wheel_selection(pop_new, 2, limitation)
offspring = self.generate_offspring... |
def roulette_wheel_selection(self, data, population, num_parents):
fitness_scores = self.create_fitness_scores(data, population)
fitness_inverse = 1 / fitness_scores
sum_fitness = np.sum(fitness_inverse)
selection_prob = fitness_inverse / sum_fitness
cum_prob = np.cumsum(select... | This code performs a generation replacement in an evolutionary algorithm. It selects parents via roulette wheel selection, generates offspring through crossover, applies mutation, and replaces the old population with the new offspring. The process continues until all individuals are replaced, then calculates fitness sc... | def generation_replacement(self, data, population, crossover_rate, mutation_rate):
pop_new = []
j = 1
while j <= population.shape[0]:
parents = self.roulette_wheel_selection(data, population, 2)
offspring = self.generate_offspring(parents[0], parents[1], crossover_rate)... |
def roulette_wheel_selection(self, data, population, num_parents):
fitness_scores = self.create_fitness_scores(data, population)
fitness_inverse = 1 / fitness_scores
sum_fitness = np.sum(fitness_inverse)
selection_prob = fitness_inverse / sum_fitness
cum_prob = np.cumsum(select... | The function performs deterministic crowding in a genetic algorithm: it iteratively selects parents via roulette wheel, generates offspring through crossover and mutation, evaluates fitness, and replaces parents with offspring if the offspring's fitness is better or equal, maintaining population size while evolving sol... | def deterministic_crowding(self, data, population, crossover_rate, mutation_rate):
pop_new = population.copy()
j = 1
while j <= population.shape[0]:
parents = self.roulette_wheel_selection(data, pop_new, 2)
offspring = self.generate_offspring(parents[0], parents[1], c... |
def _apply_canny_filter(image, min_thresh, max_thresh):
"""Extract edges from the image"""
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur_img = cv2.GaussianBlur(gray_img, (5, 5), 0)
return cv2.Canny(blur_img, threshold1=min_thresh, threshold2=max_thresh)
def _get_region_of_inter... | This function calculates the heading angle error by detecting lane lines in a frame using edge detection, perspective transformation, histogram analysis, and polynomial fitting. It identifies left/right lane boundaries, estimates their position, and returns the angular deviation from the center lane, with optional visu... | def get_heading_angle_error(self, current_frame):
"""Main task"""
copy_of_current_frame = np.copy(current_frame)
canny_img = self._apply_canny_filter(current_frame, 80, 180)
roi = self._get_region_of_interest(canny_img)
zeros_img = np.copy(self._zeros_image)
warped_img ... |
def handle_directive(self, directive, data): # pylint: disable=unused-argument
"""Override to do something with directives."""
self.warning(f"unexpected directive `{directive}'")
def validate_column_count(self, count):
"""Allows you to do things like warning of extra columns. Default is to insist on the same numb... | This code reads a CSV file from a filename or file object, parses each row, strips whitespace, skips comments, processes directives, validates column data against regex or functions, handles exceptions, and appends processed rows to self.data for further processing. | def read(self, fp_or_fn): # pylint: disable=too-many-branches
"""Read a CSV file from a filename or file object and parse it. Details in the class doc."""
if isinstance(fp_or_fn, str):
self.filename = fp_or_fn
else:
self.filename = getattr(fp_or_fn, 'name', '<none>')
with open(self.filename, 'rt', encod... |
def is_tree_made(self):
return len(self.root.children) > 0
def make_tree(self, node):
if node.check_terminal():
node.winner = node.turn_no
return node
else:
round_leaves, round_winner = self.make_round_tree(node)
for leaf in round_leaves:
... | The main task of the code is to determine if a tree structure results in a single unique "winner" by first ensuring the tree is built, retrieving all winners, and checking if all winners are identical. It returns True if there is exactly one unique winner, otherwise False. | def check_if_deterministic(self):
if not self.is_tree_made():
self.root = self.make_tree(self.root)
w = self.get_winners(self.root)
return len(set(w)) == 1 |
def random_group_order():
# Randomly switching groups
chosen_groups = grouping_chosen_alphabet()
mixed_groups = chosen_groups[0]
task_text = chosen_groups[1]
task_text += "\nSwitch groups:"
base_groups_order = [
(0,"first"),
(1,"second"),
(2,"third"),
(3,"fourth"... | The main task of the code is to generate a randomized exercise with a correct answer and task text. It uses `random_group_order()` to create a base exercise, applies `do_letter_switch()` for modification, extracts the correct answer as a string, and returns the formatted exercise details along with a title and subtitle... | def exercise_5():
title = EXERCISE5
subtitle = EXERCISE5_SUBTITLE
exercise_base = random_group_order()
exercise = do_letter_switch(exercise_base)
correct_answer = make_one_string(exercise[0])
task_text = exercise[1]
return correct_answer, task_text, title, subtitle |
def __add_border(self):
for y, row in enumerate(self.grid):
for x, _ in enumerate(row):
# I'd like the boundary of the map to stay as walls :D
if x == 0 or x == self.MAP_WIDTH-1 or y == 0 or y == self.MAP_HEIGHT -1:
self.grid[y][x] = 99
def __add_s... | The code's main task is to interpolate Perlin noise-generated grid values into a specified integer range, then add borders, spawn points, and treasure locations. If an error occurs during this process, it adjusts the seed, reinitializes the grid, and retries generation recursively. | def generate(self):
# Interpolate the values generated by
# Perlin noise to integers in range `RANGE`
try:
self.grid = np.interp(
self.grid,
[self.grid.min(), self.grid.max()],
self.RANGE
).astype(int)
self.__... |
def interpolate_blinks(df, measure='pupil', blink_detection_measure='pupil', cutoff=50, coalesce_period=1, buffer=0.2):
blink_starts, blink_ends = _detect_blinks(df, blink_detection_measure, cutoff, coalesce_period)
df['{}_int'.format(measure)] = df[measure].copy()
df['is_blink'] = 0
if blink_starts is ... | The main task of the code is to preprocess pupil data by interpolating blinks, applying filters, calculating percentage signal change, fraction, and slope, then plotting results and saving the processed DataFrame to an HDF5 file for a given subject. | def preprocess_pupil(df, params, output_dir, subject_id):
# preprocess:
interpolate_blinks(df=df)
filter_pupil(df=df, fs=params['fs'], hp=params['hp'], lp=params['lp'], order=params['order'])
psc_pupil(df=df)
fraction_pupil(df=df)
slope_pupil(df=df, hp=params['s_hp'], fs=params['fs'], order... |
def _title(self, depth: int = 0, alternate: bool = False) -> str:
return f"{self.depth_prefix(depth)}{self.title if not alternate else self.title_alternate}"
def all_params(self) -> Iterable[str]:
if shell_params := self.shell_params():
shell, *shell_params = shell_params
yield f... | This method generates a hierarchical rendering of elements by yielding formatted strings for titles and parameters, recursively processing sub-items and siblings with increasing depth to represent nested structures. | def render(self, depth: int = 0) -> RenderableGenerator:
if self.only_if:
yield " | ".join((self._title(depth), *self.all_params()))
if self.title_alternate:
yield " | ".join((self._title(depth, True), *self.all_params()))
for item in self.subclass_render_ho... |
def get_egoCar_first_wp_index(self):
"""
get_next_waypoint(pose)
gets next waypoint index, leveraged from path planning
Input:
current pose
Return:
index of next waypoint
"""
# gets closest waypoint
egoCar_first_wp_index = self.... | The code's main task is a continuous loop that processes messages, generates final waypoints based on the ego car's position and track data, and publishes these waypoints at a 10 Hz rate. It checks for valid ego car pose and track waypoints, retrieves the next waypoint index, generates ahead waypoints, and publishes th... | def loop(self):
"""
loop() - continuous loop that processes messages and publishes final waypoints
"""
Update_rate = rospy.Rate(PUBLISH_RATE) # 10 Hz / previously was 2 Hz
while not rospy.is_shutdown():
if (self.egoCar_pose is not None) and (self.full_track_w... |
def display_table_header():
'''This function displays the header of the table which is responsible for displaying the information'''
print(colored("~" * 154, 'blue'))
print(
f' {colored(max_display("Topic/specialty"), "blue")}{colored("|", "blue")}{colored(max_display(" Clinician Name"), "blue")}{c... | The main task of the code is to delete unbooked calendar slots by checking if selected events have attendees. If no attendees (indicating unbooked slots), it deletes them; otherwise, it prevents deletion due to existing bookings. The function lists events, processes user input, verifies booking status, and executes del... | def cancel_slot(service):
"""This function cancels the whole slot if no one has booked them"""
page_token = None
all_events = []
event_id_andstatus = []
events = service.events().list(calendarId='waflx@example.com',
pageToken=page_token, ).execute()
user_detail... |
def display_table_header():
'''This function displays the header of the table which is responsible for displaying the information'''
print(colored("~" * 154, 'blue'))
print(
f' {colored(max_display("Topic/specialty"), "blue")}{colored("|", "blue")}{colored(max_display(" Clinician Name"), "blue")}{c... | The function cancels a booking by removing the second attendee if their email matches the user's. It retrieves events, validates the user's email against attendees, and updates the event to remove the second attendee upon confirmation. | def booking_cancalation(service):
"""This function cancels the second attendee of the event if the emails are the same"""
page_token = None
all_events = []
event_id_andstatus = []
events = service.events().list(calendarId='waflx@example.com',
pageToken=page_token, ... |
def display_table_header():
'''This function displays the header of the table which is responsible for displaying the information'''
print(colored("~" * 154, 'blue'))
print(
f' {colored(max_display("Topic/specialty"), "blue")}{colored("|", "blue")}{colored(max_display(" Clinician Name"), "blue")}{c... | The function cancels unbooked calendar slots by listing events in a specified time range, verifying if selected slots are unbooked, and deleting them if no attendees are present. It handles user selection, checks for bookings, and ensures only unreserved slots are removed from the clinic calendar. | def cancel_slot(service):
"""This function cancels the whole slot if no one has booked them"""
page_token = None
all_events = []
event_id_andstatus = []
min_range = datetime.now().replace(
hour=0, minute=0, second=1)
max_range = min_range.replace(hour=23, minute=59, second=59) + timedelt... |
def display_table_header():
'''This function displays the header of the table which is responsible for displaying the information'''
print(colored("~" * 154, 'blue'))
print(
f' {colored(max_display("Topic/specialty"), "blue")}{colored("|", "blue")}{colored(max_display(" Clinician Name"), "blue")}{c... | The function cancels a clinic booking by verifying the user's email matches the second attendee of an event. It retrieves upcoming events, checks attendee details, and confirms cancellation with the user. If valid, it updates the event to remove the attendee via the Calendar API. | def booking_cancalation(service):
"""This function cancels the second attendee of the event if the emails are the same"""
page_token = None
all_event = []
event_id_andstatus = []
min_range = datetime.now().replace(
hour=0, minute=0, second=1)
max_range = min_range.replace(hour=23, minute... |
def testing_final(soup, url):
if 'https://www.fandomspot.' in url or 'https://www.imdb' in url or 'https://www.cbr.' in url:
if 'https://www.cbr.' in url:
terms_h2 = soup.select('h2')
res, response = testing_cbr(terms_h2)
else:
terms_h3 = soup.select('h3')
... | The code scrapes multiple websites concurrently using asynchronous HTTP requests, extracts data with BeautifulSoup, processes it through a parser function, cleans and formats the results, and returns a list of unique, title-cased items. | def scrapeUrls(sites):
data = set()
headers = requests.utils.default_headers()
headers.update(
{
'User-Agent': 'My User Agent 1.0',
}
)
with sessions.FuturesSession() as session:
futures = [session.get(site, headers=headers) for site in sites]
... |
def play_process(app, EzCadAppRef, numberOfObjectsInSVG, begin_at_layer_no, const_printing_interval, marking_time):
global should_pause, is_paused, thread
# should_pause is used to tell the print3dItem function that the pause button has been pressed and the function has to be stopped after execution of current... | This code creates a GUI for controlling a 3D printing automation process. It sets up a window with "Pause/Resume" buttons, displays current layer information, and initializes a background thread to handle printing operations. The GUI remains on top, tracks layer progress, and allows real-time control of the printing wo... | def createControlGUI(app, EzCadAppRef, numberOfObjectsInSVG, begin_at_layer_no, const_printing_interval, marking_time):
# Create the GUI window of controls on screen
gui_controls_root = tkinter.Tk()
gui_controls_root.title("Automator controls")
try:
gui_controls_root.wm_iconbitmap("../asse... |
def moveAppToRightSide():
# successStatus = False
pyautogui.FAILSAFE = False
# Find the Notepad window
hwnd = win32gui.FindWindow(None, "EzCad2.14.11 - No title")
if hwnd:
# Get the position of the title bar
rect = win32gui.GetWindowRect(hwnd)
x = rect[0] + rect[2] ... | The main task of the code is to automate the initialization and setup of the EZCAD2 application by launching it, handling initial dialogs, positioning the window, importing a vector file, configuring settings like coordinates and layer grouping, and preparing for layer-based processing. It also triggers a control GUI c... | def begin(resizingWaitTime, begin_at_layer_no, const_printing_interval, marking_time):
app = Application(backend='win32').start(cmd_line=u'"C:\\Users\\maury\\Desktop\\For OptiLOM\\EZCAD2-Software\\EZCAD2 For AiO (20220915 Release)\\EZCAD2 For AiO.exe" ')
EzCadAppRef = app[u'EzCad2.14.11 - No title']
# Ha... |
def __ACCESS_TOKEN_PATH():
return os.path.join(__PRIVATE_PATH(), 'tokens', 'access_token.md')
def __decrypt_data(encrypted_path, key_path, passcode):
with open(encrypted_path, 'rb') as fobj:
private_key = RSA.import_key(
open(key_path).read(),
passphrase=passcode)
enc_ses... | The function retrieves an access token from a file by decrypting its content, checks if the token is still valid (within the last hour), and returns it if valid. If expired or invalid, it refreshes the token recursively. If the file doesn't exist, it notifies the user. | def _get_access_token():
if os.path.exists(__ACCESS_TOKEN_PATH()):
token_file = open(__ACCESS_TOKEN_PATH(), 'r')
content = __decrypt_data(__ACCESS_TOKEN_PATH(),
__PRIVATE_KEY_PATH(),
__PRIVATE_CODE()).split(',')
try:
... |
def critical(n1, n2):
phic = math.sqrt(n2)/(math.sqrt(n1)+math.sqrt(n2))
chic = 0.5*(math.sqrt(n1)+math.sqrt(n2))*(math.sqrt(n1)+math.sqrt(n2))/(n1*n2)
return chic, phic
def phi_sp(chi, n1, n2):
val = 2.0*n1*n2*chi
coef = n1-n2-val
root = math.sqrt(coef*coef-4.0*val*n2)
return -0.5*(coef+root)/val, -0.5*(coef... | The code generates a phase diagram (binodal/spinodal curves) for two polymer components by calculating critical points, iterating chi values, and plotting results using gnuplot. It retrieves component properties (degree of polymerization, names), computes phase boundaries, and outputs data as a plot and/or CSV file if ... | def phase_diagram(_udf_, index1, index2, dev, max_plus, type, csv_file):
raw_n1 = _udf_.get("component_properties.components[].degree_of_polymerization",[index1])
raw_n2 = _udf_.get("component_properties.components[].degree_of_polymerization",[index2])
name1 = _udf_.get("component_properties.components[].name",[inde... |
def load_image(self, _id):
filename = os.path.join(self.path, "fakes", _id)
image = cv2.imread(filename)
max_dim = self.config.IMAGE_SHAPE[0]
min_dim = self.config.IMAGE_SHAPE[0]
# image_dtype = image.dtype
# Default window (y1, x1, y2, x2) and default scale == 1.
... | The code prepares a batch of images and their corresponding RPN (Region Proposal Network) targets for training. It loads images, processes bounding boxes, generates RPN match/bbox targets, and organizes data into tensors for model input. The task involves batching, preprocessing, and creating training samples with anch... | def __getitem__(self, idx):
# Choose the image ID's to be loaded into the batch
image_ids = self.image_ids[idx * self.config.BATCH_SIZE: (idx + 1) * self.config.BATCH_SIZE]
# Only RGB images - todo: fix this
image_batch = np.zeros(((self.config.BATCH_SIZE, ) + self.config.IMAGE_SHAPE + ... |
def qstat_status(jobid, debug=False):
""" qstat to obtain job status, raises StatusCheckException if qstat fails
Parameters
----------
jobid: str
The job being evaluated
Returns
-------
str: status string (running, failed, success) (success not possible)
debug: Optional[bool]
... | The function `check_status` determines the status of a job (running, failed, success) by sequentially checking: 1) `qstat` output, 2) cluster directory exit files, and 3) a "missing" state if previous checks fail. It prioritizes `qstat` for active jobs, falls back to file-based checks for completed jobs, and uses `miss... | def check_status(jobid, debug=False):
""" Uses qstat/local files/qacct to check for the status of given jobid
Parameters
----------
jobid: str
The job being evaluated
debug: Optional[bool]
If set, print additonal information to stderr
Returns
-------
str: status string ... |
def escaped_split(s, delim):
ret = []
current = []
itr = iter(s)
for ch in itr:
if ch == '\\':
try:
current.append('\\')
current.append(next(itr))
except StopIteration:
pass
elif ch == delim:
ret.append('... | The code reads user input with a prompt showing the current directory and username, splits the input by pipes, processes each command with `pHelp`, and returns the processed commands as a string. If the input starts with "exit", it raises a `GumError` to terminate the session. | def parseInput():
i = input('%s %s$ ' % ((os.getcwd().split('/')[-1] if os.getcwd().split('/')[-1]
!= getpass.getuser() else '~'), getpass.getuser()))
if i.split(' ')[0] == "exit":
raise GumError
cmds = []
cmds.extend([stri.strip() for stri in escaped_split(i, '|')])
for i in range(l... |
def set_mnist():
"""
read every mnist template into memory and process it
in order to be the dictionary for the following input.
"""
global mnist
global top_dir
global gradient_template
global MNIST_DIR
# winname = 'mnist demo'
# cv2.namedWindow( winname, cv2.WINDOW_NORMAL )
... | The main task of the code is to process a door image by resetting the match list, setting the working directory, loading and preprocessing an image (via `read_door_img` and `image_preprocess`), and returning the processed image along with the cleared `MATCH_PAIR` list. It handles errors by checking if the image exists ... | def main_proc( index = 1 ):
global top_dir
global MATCH_PAIR
MATCH_PAIR.clear() # reset match list
top_dir = os.getcwd()
set_mnist()
img = read_door_img( count = index )
if img is None:
print( 'It is None, no such file exist.' )
return None
img = image_pre... |
def playAnimation(self,sprite,x,y,delay=3,flip=(False,False)):
numFrames = len(sprite)
for i in range(0,numFrames*delay):
if((self.deltaAnim+i)%(numFrames*delay) == 0):
try:
self.surface.blit(pygame.transform.flip(sprite[len(sprite)-int(math.ceil((i+1)/del... | This method updates character animations based on movement direction and state, renders the HUD, checks collisions, and draws missile particles. It increments an animation counter, plays appropriate sprites for still/walking states, handles directional mirroring, updates the particle surface, and blits all visual eleme... | def draw(self):
self.deltaAnim += 1
# pygame.draw.rect(self.surface,(0,0,255),(self.x+self.camera.x,self.y+self.camera.y,self.cWidth,self.cHeight))
if(self.xDir == "LEFT"):
if(self.currentState == "STILL"):
self.playAnimation(self.sprite_still,self.x,self.y+(self.cHei... |
def with_stdout_as_file(filename, thunk):
with open(filename, 'w') as f:
with redirect_stdout(f):
thunk()
def gen_tests_r_type(inst):
print(f'## desc = Autogenerated test file for {inst}')
cycles = 0
reg = 3
a_dtype, b_dtype = arg_types[inst]
print(f'# Edge cases')
for a,... | The main task of the code is to generate comprehensive RISC-V instruction test cases by iterating through different instruction types (e.g., R-type, I-type, SW/LW, SB/LB, LUI), executing corresponding test generation functions, and redirecting output to distinct text files for each instruction variant, including specia... | def gen_all_tests():
for inst in r_type_np_impls.keys():
with_stdout_as_file('./riscv-tests/' + inst + '_tests.txt', lambda: gen_tests_r_type(inst))
for inst in i_type_r_type:
with_stdout_as_file('./riscv-tests/' + inst + '_tests.txt', lambda: gen_tests_i_type_r_type(inst))
with_stdout_as_fi... |
def h(p1,p2):
x1,y1=p1
x2,y2=p2
return abs(x1-x2)+abs(y1-y2)
def reconstruct_path(came_from,current,draw):
while current in came_from:
current = came_from[current]
current.make_path()
draw()
def draw(win,grid,rows,width):
win.fill(WHITE)
for row in grid:
for spot ... | This code implements the A* pathfinding algorithm to find a path from a start node to an end node on a grid. It uses a priority queue to explore nodes, calculates tentative scores (g and f), updates the path, and visualizes the process by modifying node states and redrawing the grid. The algorithm returns True if a pat... | def algorithm(draw,grid,start,end):
count = 0
open_set = PriorityQueue()
open_set.put((0,count,start))
came_from = {}
g_score = {spot:float("inf") for row in grid for spot in row}
g_score[start]=0
f_score = {spot:float("inf") for row in grid for spot in row}
f_score[start]=h(start.get_po... |
def make_grid(rows,width):
grid = []
gap = width//rows
for i in range(rows):
grid.append([])
for j in range(rows):
spot = Spot(i,j,gap,rows)
grid[i].append(spot)
return grid
def draw(win,grid,rows,width):
win.fill(WHITE)
for row in grid:
for spot i... | This code creates a pathfinding visualization tool using Pygame. It initializes a grid, allows users to set start/end points and barriers via mouse clicks, and runs a pathfinding algorithm (triggered by SPACE) to find routes. The 'C' key resets the grid. The main task is to provide an interactive interface for visualiz... | def main(win,width):
ROWS = 25
grid = make_grid(ROWS,width)
start = None
end = None
run = True
while run:
draw(win,grid,ROWS,width)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if pygame.mouse.get_pressed()[0]:... |
def _update_repodata_from_shards(repodata, links, new_shards, removed_shards, subdir):
all_shards = {}
read_subdir_shards("repodata-shards", subdir, all_shards, shard_paths=new_shards)
print(
f"{HEAD} found {len(all_shards)} repodata shards for subdir {subdir}",
flush=True,
)
if n... | The function `_rebuild_subdir` processes and rebuilds repodata for a specific directory (`subdir`) by updating, patching, and writing files based on new/removed shards. It filters relevant shards, updates `all_repodata` and `all_patched_repodata`, handles labels, and generates files like `repodata.json` and `current_re... | def _rebuild_subdir(
*, subdir, new_shards, removed_shards, repatch_all_pkgs,
all_repodata, all_patched_repodata, all_links, updated_data,
make_releases, main_only, patch_fns, futures, rel, exec,
):
if new_shards is not None:
new_subdir_shards = [
k
for k in new_shards
... |
def _clone_repodata_shards():
subprocess.run(
"git clone https://github.com/conda-forge/repodata-shards.git",
shell=True,
check=True,
)
def _clone_repodata():
subprocess.run(
f"git clone https://github.com/{REPODATA_REPO}.git",
shell=True,
check=True,
)
de... | The main task of the code is to continuously build and update repodata for a specified time limit, managing GitHub interactions, patching, and releases. It clones repositories, rebuilds repodata shards, handles errors by force-rebuilding, and uploads updates. If enabled, it creates releases, updates channel data, and d... | def main(time_limit, make_releases, main_only, debug, allow_unsafe):
"""Worker process for continuously building repodata for a maximum
number of TIME_LIMIT seconds.
"""
global DEBUG
DEBUG = debug
start_time = time.time()
# refresh at the start
refresh_github_token_and_client()
wi... |
def update_shards(labels, all_shards, rank, n_ranks, start_time, time_limit=3300):
cd = requests.get(
"https://conda.anaconda.org/conda-forge/channeldata.json"
).json()
shards_to_write = set()
for label in tqdm.tqdm(labels, desc="labels"):
for subdir in CONDA_FORGE_SUBIDRS:
... | The main task of the code is to synchronize Anaconda repodata shards with a local copy and upload packages, depending on the specified step. For the "shards" step, it fetches and sorts channel labels by package count, updates repodata shards in parallel, and attempts to push the repository. For the "releases" step, it ... | def main(step, rank, n_ranks, time_limit):
"""Sync anaconda repodata shards w/ a local copy and upload packages.
"""
start_time = time.time()
print("rank|n_ranks: %d|%d" % (rank, n_ranks), flush=True)
all_shards = {}
print("reading all shards", flush=True)
for subdir in CONDA_FORGE_SUBIDRS... |
def clear_checked(self):
self.var.set(0)
self.var1.set(0)
self.var2.set(0)
self.var3.set(0)
self.var4.set(0)
self.var5.set(0)
self.var6.set(0)
self.var7.set(0)
self.var8.set(0)
def knn_own(self):
self.clear_results()
self.preprocess... | The code's main task is to display KNN-related ROC curves based on checkbox selections. It checks three variables (var, var1, var2) to determine which KNN variant (standard, PCA, LDA) to visualize. If a checkbox is selected, it clears the canvas, generates the corresponding ROC curve using methods like knn_own(), knn_p... | def knn_checked(self):
#get if checked
var = self.var.get()
var1 = self.var1.get()
var2 = self.var2.get()
self.clear_checked()
self.canvas_im.delete("all")
#if knn without analysis is checked then show knn roc curve
if var ==1:
self.knn_own()
... |
def clear_checked(self):
self.var.set(0)
self.var1.set(0)
self.var2.set(0)
self.var3.set(0)
self.var4.set(0)
self.var5.set(0)
self.var6.set(0)
self.var7.set(0)
self.var8.set(0)
def naive_bayes(self):
self.clear_results()
self.prepro... | The main task of the code is to handle user selections for different Naive Bayes models (basic, PCA, LDA), generate their ROC curves, and display corresponding images on a canvas. It clears previous content, checks selected options, executes model-specific methods, loads images, and renders them on the canvas based on ... | def nb_checked(self):
var3 = self.var3.get()
var4 = self.var4.get()
var5 = self.var5.get()
self.clear_checked()
self.canvas_im.delete("all")
#if naive bayes without analysis is checked then show naive bayes roc curve
if var3 == 1:
self.naive_bayes()
... |
def clear_checked(self):
self.var.set(0)
self.var1.set(0)
self.var2.set(0)
self.var3.set(0)
self.var4.set(0)
self.var5.set(0)
self.var6.set(0)
self.var7.set(0)
self.var8.set(0)
def mlp(self):
self.clear_results()
self.preprocessing(... | The function `mlp_checked` processes user selections to display different MLP model results. It clears previous selections, deletes canvas images, and loads specific images (`mlp_img.png`, `pcamlp_img.png`, `ldamlp_img.png`) based on the values of `var6`, `var7`, and `var8`. Each condition triggers a corresponding MLP ... | def mlp_checked(self):
var6 = self.var6.get()
var7 = self.var7.get()
var8 = self.var8.get()
self.clear_checked()
self.canvas_im.delete("all")
if var6 ==1:
self.mlp()
#''change image to knn without pca
self.img=img =ImageTk.Phot... |
def monitor_nonlinearity(x, x_gamma_function):
"""Monitor colour displaying is not linear but follows x^gamma function.
Convert raw image values to monitor scale.
parameters:
- x: image as numpy.ndarray (floats in [0,255])"""
x = x * 255
x_int = x.astype(np.uint8)
assert np.allclose(x, x_i... | The function converts an input image to opponent colors by adjusting for monitor nonlinearity using a gamma function. It first scales the image to [0,1], applies monitor nonlinearity correction, transforms the image into opponent color space, and then reverses the nonlinearity adjustment to produce the final false-colo... | def false_colour(image, x_gamma_function): # =np.linspace(0, 1, 256)):
"""Return image converted to have opponent colours.
parameters:
- image: a numpy.ndarray
- x_gamma_function: an array mapping colour intensities in [0,255]
to measured monitor output"""
# adjust image t... |
def get_author_details(author_id: str, ss: ssapi.SemanticScholarAPI):
fields = [f"papers.{f}" for f in ssapi.FIELDS_PAPER_BASIC] + ssapi.FIELDS_AUTHOR_BASIC
author = ss.author_details(author_id, fields=fields)
papers_df = papers2df(author.papers)
author_df = author2df(author)
return author, author_d... | This function computes self-citation and pseudo-self-citation metrics for an author's papers using Semantic Scholar API. It calculates citation counts, ratios, adjusted h-indices, and i10-indices while excluding self-citations, pseudo-citations (involving co-authors), and aggregates these metrics into author-level stat... | def compute_self_citation_count(author_id: str, ss: ssapi.SemanticScholarAPI = None) -> int:
if ss is None:
ss = ssapi.SemanticScholarAPI() # default
author, author_df, papers_df_trunc = get_author_details(author_id, ss)
papers = ss.author_papers(author_id, fields=ssapi.FIELDS_PAPER_BASIC)
pa... |
def read(self):
ret = {}
services = check_output(
[self.chamber, "list-services"], env=self._env()
).decode()
services = services.split("\n")
# self.debug(f"_read() {services=}")
self.debug(
f"_read() {self.service} in services: {self.service in se... | This code synchronizes secret credentials for servers by deleting existing entries not present in the new secrets and writing the updated credentials, ensuring consistency with the chamber tool. It reads current secrets if not provided, iterates through servers to remove outdated ones, writes new credentials, and verif... | def write(self, secrets, current):
if current is None:
current = self.read()
for server in current.keys():
if server not in secrets.keys():
cmd = [
self.chamber,
"delete",
self.service,
... |
def debug(self, msg, **kwargs):
if self.logger:
self.logger.debug(f"{self}: {msg}", **kwargs)
def read(self):
ret = {}
services = check_output(
[self.chamber, "list-services"], env=self._env()
).decode()
services = services.split("\n")
# self.debug... | The code updates a server's credentials in a stored configuration by reading existing data, modifying the specified server's username and secret, and writing the changes back. | def put(self, server, username, secret):
self.debug(f"put({server=} {username=} {secret=})")
current = self.read()
update = current.copy()
update[server] = {"Username": username, "Secret": secret}
self.write(update, current) |
def debug(self, msg, **kwargs):
if self.logger:
self.logger.debug(f"{self}: {msg}", **kwargs)
def read(self):
ret = {}
services = check_output(
[self.chamber, "list-services"], env=self._env()
).decode()
services = services.split("\n")
# self.debug... | This code deletes a specified server entry from stored data. It reads current data, checks if the server exists, removes it if present, and writes the updated data. If the server isn't found, it triggers a not-found response. Debug logging is included for tracking. | def delete(self, server):
self.debug(f"delete({server=})")
current = self.read()
if server in current.keys():
update = current.copy()
update.pop(server)
self.write(update, current)
else:
self.server_not_found(server) |
def get_output(mode,side,controller,controls,events):
if mode == "controller":
return get_output_controller(side,controller,controls["controller"],events)
if mode == "keyboard":
return get_output_keyboard(side,controller,controls["keyboard"],events)
def is_blocking(state,player):
if player ... | This code simulates a 2D fighting game with two players. It handles input, state transitions (like attacks, movement, and recovery), collision detection between hitboxes and hurtboxes, damage calculation, and life management. The loop updates game states, renders visuals, and returns outcomes like "quit", "draw", or pl... | def play(state):
global window,controls,background,key_state,frame_data
pygame.event.set_blocked(None)
pygame.event.set_allowed([pygame.KEYUP,pygame.KEYDOWN,pygame.JOYBUTTONDOWN,pygame.QUIT])
key_state=[{"left":"up","right":"up","down":"up","up":"up"},{"left":"up","right":"up","down":"up","up":"up"}]
... |
def menu(state):
global window,controls,background
pygame.event.set_blocked(None)
hitboxes_options= []
hitboxes_options= hitboxes_options + [text("play",30,(0,0,0),"midtop",800,350)]
hitboxes_options= hitboxes_options + [text("controls",30,(0,0,0),"midtop",800,400)]
hitboxes_options= hitboxes_op... | This code initializes a Pygame game window with a background, sets up dual-player controls (keyboard/controller), detects joysticks for input configuration, and manages game states (menu, controls, ready, play, end) through a state machine loop until the "quit" state is reached. | def main():
global window,modes,controls,background
window = pygame.display.set_mode((1600,800))
pygame.display.set_caption("NeutralGame (work in progress)")
background= pygame.image.load("data/backgrounds/summer landscape.png")
controls= [
{"keyboard":[{97:"left",100:"right",115:"down",119:"up... |
def parse_expert_part(self, part, part_lines):
logger.debug("parsing expert track %s", part)
difficulty_lines = defaultdict(list)
notes_by_ms = defaultdict(list)
for line in part_lines:
if '=' not in line:
continue
ms, value = [_line__part.strip() ... | The code parses a file by segmenting it into sections defined by bracketed headers (e.g., [Expert], [SyncTrack], [Song]). When encountering a '}', it processes the accumulated lines for the current section using specialized parsing methods, then resets the buffer for the next section. | def parse_file(self, lines):
part = None
part_lines = []
for line in lines:
self.lines.append(line)
if re.match(r'^\[\w*\]$', line):
part = line
continue
if line == '}':
if part:
if '[Expert'... |
def check_word(guess):
global winner
btn_index = letter_count - 5
for i, letter in enumerate(guess):
if letter == word[i]:
letters[btn_index + i]['bg'] = green
letters[btn_index + i]['activebackground'] = green
elif letter in word:
if guess.count(letter) >... | This code handles keyboard input for a word-guessing game. It tracks letters entered by the player, updates the interface with each letter, and checks if the formed word is valid every 5 letters. If valid, it proceeds; if not, it resets progress. The game continues until 30 letters are processed, triggering a win/loss ... | def key_pressed(event):
global letter_count, guess
if not winner:
if event.char >= 'a' and event.char <= 'z' or event.char >= 'A' and event.char <= 'Z':
if letter_count <= 29:
letters[letter_count]['text'] = event.char.upper()
letters[letter_count].focus()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.