dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def predict(model, input):
"""
predict images
Parameters
----------
model
input
Returns
-------
"""
ans = model.predict(input)
img = ((input + 1) / 2)
img = img[0]
return ans, img
def predicted_box(predicted_output):
"""
convert predicted output to rectangle... | The function `predict_func` uses a model to predict on an input image, draws bounding boxes around detected objects, displays the annotated image, and optionally saves it if `image_save` is True. It returns the processed image with rectangles and handles visualization and storage based on parameters. | def predict_func(model, inp, name, image_save=False):
"""
predict image and show and save
Parameters
----------
model
inp
name
image_save
Returns
-------
"""
r_img = None
pred_out, img = predict(model, inp)
rects = predicted_box(pred_out)
for rect in rects:... |
def _unpack_header_string(self, length):
""" Read the next characters as a string. """
start_pos = self._file.tell()
# noinspection PyBroadException
try:
header = struct.unpack(f'>{length}s', self._file.read(length))[0]
header = header.decode('utf-8')
exce... | This function reads an APP segment from a file starting at a specified offset, checks its 4-byte header to identify the segment type (JFIF, JFXX, or EXIF), and delegates processing to specialized methods like _read_jfif_segment or _read_exif_segment based on the header value. | def _read_app_segment(self, offset):
""" Read an APP segment and handle any known segment types. """
with ReadSegment(self._file, segment_start=offset) as seg:
seg.go_to_segment_data()
if self._unpack_header_string(4) in [constants.JFIF_HEADER, constants.JFXX_HEADER]:
... |
def _find_next_marker(self):
""" Find and return the next marker (2 bytes). """
# Find first byte following 0xff that is not 0xff or null
b1, b2 = self._file.read(2)
while b1 != 0xff:
self._file.seek(-1, os.SEEK_CUR)
b1, b2 = self._file.read(2)
while b... | This method reads a JPEG file, validates its format via SOI marker, iterates through segments to identify metadata, and extracts resolution data from SOF markers while processing APP markers for additional metadata like pixel aspect ratio. | def _read_file(self):
with open(self._file_path, 'rb') as f:
# Validate that the file we're reading is a JPEG file
self._file = f
marker = self._find_next_marker()
assert marker == segment_markers.SOI.marker, f"File is not a JPEG file: {self._file_path}"
... |
def dates_to_xvalues(self,
dates):
""" Converts dates to the same units of x values used in the model.
input:
------
dates : the input abscissa (time) values. These should be datetime-like objects.
... | The code runs a statistical model test by generating synthetic data with given parameters, executing MCMC sampling, and visualizing results through trace plots, pair plots, time series, and risk ratio distributions to evaluate model performance and parameter accuracy. | def run_model_test(self,
theta = None):
""" Runs a test of the model.
input:
------
theta : the true parameters to use in the test
This could be None if the test_only flag
was set... |
def get_engine():
#Yaml stored in directory above script directory (where repository was cloned)
fp=os.path.dirname(os.path.realpath(__file__))
yaml_fp=fp[:fp.index('NCAA-Database')]
if os.path.isfile(yaml_fp+'sql.yaml'):
with open(yaml_fp+'sql.yaml', 'r') as stream:
data_loaded = yaml.load(stream)
... | The main task of the code is to initialize a database engine, retrieve a list of game IDs, and update player box scores using those game IDs. The function orchestrates data retrieval and processing for sports statistics, likely for a database or analytics system. | def main():
engine=get_engine()
game_ids=get_gameids(engine)
update_player_boxscores(engine,game_ids) |
def get_active_reminders(bot: Sopel) -> Dict[str, List[ContextualReminder]]:
"""
Gets the reminders currently active in the bot
"""
return bot.memory[BOT_MEMORY_NAMESPACE]["reminders"]
def set_active_reminders(bot: Sopel, reminders: Dict[str, List[ContextualReminder]]) -> None:
"""
Sets the acti... | This function updates the pastebin URLs of existing active reminders in a bot's system by matching them with provided updated_reminders. It retrieves current active reminders, iterates through them, and replaces their pastebin_url with corresponding values from updated_reminders. Finally, it saves the modified reminder... | def update_reminders_pastebin_url(bot: Sopel,
updated_reminders: Dict[str, List[ContextualReminder]]) -> None:
"""
Receives a list of updated reminders and applies the pastebin URL and saves the list
to persistence file
"""
if len(updated_reminders) == 0:
return
active_reminders = ... |
def _get_page(self, constraints, start):
if self.cloudflare_flagged == False:
return bs4.BeautifulSoup(requests.get(self._gen_url(constraints, start=start), headers={
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safa... | This function gathers proxy data from a source by repeatedly fetching and parsing web pages, collecting proxy details into a list of dictionaries until the specified time limit (ignore_time) is exceeded or Cloudflare blocks the request. It handles errors, retries up to 25 times if blocked, and extracts proxy attributes... | def gather(self, constraints: dict, ignore_time: int = 15):
'''
Gathers proxies (blocking op) until ignore_time (minutes) is hit
'''
self.last_check_time = datetime.datetime.now()
proxies = []
current_gathered = 1
current_trs = []
i = 0
attempts = ... |
def Generate_Device_DF(self, data):
device_df = pd.DataFrame()
for key in data.keys():
if key.__contains__("pixel"):
pixel_data = data[key]
pixel_df = pd.DataFrame([[pixel_data['PCE[%] Rv'], pixel_data['PCE[%] Fw'],
pixel_data['Jsc[mA/cm2] ... | This function handles UI item selection events by clearing graphs, identifying the selected device type (Pixel/Device/Group), and triggering corresponding actions: generating dataframes, dropping specific columns, creating bar graphs for Devices, or passing data to processing functions. It ensures appropriate visualiza... | def Item_Selected(self):
RL.Clear_Graphs()
if len(ui.DUI.devices_tree.selectedItems()) >= 1:
selected_item = ui.DUI.devices_tree.selectedItems()[0]
if selected_item.type == "Pixel":
#print(selected_item.info)
RL.Pixel_Selected(selected_item.info)... |
def early_stop_action():
global_truths.test_accuracy = test()
action = decreases_function(global_truths.test_accuracy, global_truths.last_test_accuracy)
if action == 1:
print("test accuracy has gone down; early stopping")
exit(0)
if action == 0:
global_truths.last_test_accuracy ... | This function performs early stopping or learning rate annealing based on global flags. It triggers early stopping if `check_loss` is active, adjusts the learning rate via annealing if `learn_rate_annealing` is enabled, and executes a combined check-annealing process if `check_loss_annealing` is set. The actions depend... | def perform_early_stop_or_anneal(learn_rate):
#early stop
if global_truths.check_loss == 1:
early_stop_action()
#learn rate annealing
if global_truths.learn_rate_annealing == 1:
learn_rate_anneal_action(learn_rate)
#test of both
if glob... |
def forward_prop(num_layers):
for m in range(1, num_layers):
L[m].weighted = L[m].weights_and_biases(L[m-1].output)
L[m].output = L[m].activate(L[m].weighted)
def back_prop(image_no, learn_rate):
num_layers = len(L)
#output L[num_layers-1] is the first layer done, it has different calcs
... | This function implements Stochastic Gradient Descent (SGD) for training a neural network. It iterates over epochs, randomly selects batches, performs forward propagation, calculates accuracy/cost, executes backpropagation with learning rate adjustment, and monitors training progress with metrics like accuracy, cost, an... | def sgd(epochs, batch_size, learn_rate):
num_layers = len(L)
for h in range(epochs):
start_time = time.time()
expected_prob_total = 0
cost_total = 0
rand_list = np.random.choice(range(0, L[0].length_param), size=batch_size, replace=False)
for i in range(batch_size):
... |
def get_memsize(arg):
'''Convert memory size with suffix to kB'''
match = re.match(r'(\d+)([' + BINARY_PREFIX + r']?)$', arg.upper())
if match is None:
sys.exit('{} is not a valid page size'.format(arg))
num = float(match.group(1))
suffix = match.group(2)
if suffix == "":
return ... | This script processes command-line arguments to configure huge pages, enabling actions like displaying current settings, clearing pages, mounting/unmounting filesystems, reserving pages with specified sizes, and performing full setup. It validates input parameters, ensures reserved memory aligns with page sizes, and ex... | def main():
'''Process the command line arguments and setup huge pages'''
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="Setup huge pages",
epilog="""
Examples:
To display current huge page settings:
%(prog)s -s
To a complete se... |
def resize_image(im, max_side_len=2400):
"""
resize image to a size multiple of 32 which is required by the network
:param im: the resized image
:param max_side_len: limit of max image size to avoid out of memory in gpu
:return: the resized image and the resize ratio
"""
h, w, _ = im.shape
... | The code detects text boxes in an input image using a neural network, returning their coordinates, scores, and processing metrics. It resizes the image, runs inference to get score/geometry maps, detects boxes, adjusts coordinates for scaling, filters small boxes, and structures results with timing data and runtime par... | def predictor(img):
"""
:return: {
'text_boxes': [
{
'score': ,
'x0': ,
'y0': ,
'x1': ,
...
'y3': ,
}
],
'rtparams':... |
def get_mistral_llm():
# llm = Ollama(model="mistral:7b", temperature=0)
llm = HuggingFaceEndpoint(repo_id="mistralai/Mistral-7B-Instruct-v0.2", temperature=0.01)
tools = get_key("tools", [search, generate_music, generate_image, generate_video])
# prompt = hub.pull("hwchase17/react-chat-json")
promp... | The main task of the code is to update the session state with a selected language model (LLM) and agent. It checks the current model name in `st.session_state`, assigns either `get_mistral_llm()` or `get_gpt_llm()` to `st.session_state["llm"]` based on the model, and then updates `st.session_state["agent"]` using `get_... | def update_llm_model():
model = st.session_state["model"]
st.session_state["llm"] = get_mistral_llm() if model == "mistral" else get_gpt_llm()
st.session_state["agent"] = get_agent() |
def get_key(key, default_value):
if key not in st.session_state:
st.session_state[key] = default_value
return st.session_state[key]
def get_mistral_llm():
# llm = Ollama(model="mistral:7b", temperature=0)
llm = HuggingFaceEndpoint(repo_id="mistralai/Mistral-7B-Instruct-v0.2", temperature=0.01)
... | This function updates the retriever tool dictionary by processing uploaded CSV, PDF files, and URLs. It creates temporary files for new data sources, generates corresponding tools (SQL for CSV, retriever for PDF/URL), and updates session state with the new tool set. It also configures the language model and agent based... | def update_retriever_tool(type):
model = get_key("model", "mistral")
tool_dict = get_key("tool_dict", {})
updated_tool_dict = {}
csv_files = st.session_state["csv_files"]
pdf_files = st.session_state["pdf_files"]
urls = [url.strip() for url in st.session_state["urls"].split("\n") if url.strip()]... |
def automatic_speech_recognition():
recognizer = sr.Recognizer()
# microphone = sr.Microphone()
# with microphone as source:
# recognizer.adjust_for_ambient_noise(source)
# audio = recognizer.listen(source)
with sr.AudioFile(TMP_WAV) as source:
audio = recognizer.record(source)
... | The code captures audio via WebRTC, converts it to text using automatic speech recognition, processes the text with natural language processing, and generates speech output if the result isn't a file-type string, creating an audio-Text interaction loop. | def voice_flow():
webrtc_ctx = webrtc_streamer(
key="webrtc_ctx",
mode=WebRtcMode.SENDRECV,
in_recorder_factory=lambda: MediaRecorder(TMP_WAV),
media_stream_constraints={"audio": True, "video": False},
rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"... |
def room_sidebar():
with st.sidebar:
st.text_input("Room ID", key="room_id", on_change=update_chat_history)
render_rooms()
if st.session_state["room_id"]:
with st.expander("Settings"):
st.selectbox("Model", ["mistral", "gpt"], key="model", on_change=update_llm_mod... | The main task of the code is to create a virtual assistant web application using Streamlit. It configures the page with a title and icon, displays a title, integrates a sidebar for navigation or input, manages chat flow logic, and renders the chat history to display conversation records. | def main():
st.set_page_config(page_title="Virtual Assistant", page_icon="random")
st.title("Virtual Assistant")
room_sidebar()
chat_flow()
render_chat_history() |
def create_3d_trap(radius, height, delta):
"""This function creates a 3D plot of the beach along with our trap
Args:
radius (int): radius of trap
height (int): height of trap
delta (int): location of trap
Returns:
A 3D plot of the trap
"""
h = height
r = r... | The code simulates fish harvesting in a 3D trap model, visualizing tide data and tracking population dynamics. It iteratively harvests a percentage of fish per cycle, updating results and generating plots for harvested vs. surviving fish. The process includes creating 3D models, tide graphs, and pie charts to display o... | def run(radius=25, height=2, location=5, slope=0.17, harvesting_percent=100):
model_3d = create_3d_trap(radius, height, location)
#fig = create_tide_plot_grade6(radius, height, location, slope, timeframe= 'week')
fig = create_dated_tide_plot(monthly_tide_df)
#lines below disabl... |
def parse_args(argv: list[str]) -> dict[str, Any]:
parser = argparse.ArgumentParser(prog='course_backups.py')
parser.add_argument('term', help='Term to back up')
parser.add_argument('--start', default=0, type=int,
help='Ordinal number (not ID) of course to start at')
args = pars... | This code processes course backups for a specified term by reading a course list, iterating through each course to create and download backups, and logging timestamps. It uses command-line arguments, handles file paths, and executes backup operations in a loop. | def main(argv: list[str]) -> int:
args = parse_args(argv[1:])
print(args, flush=True)
term: str = cast(str, args['term'])
backups_dir = Path.home().joinpath('Documents', 'DEd', 'course_backups')
courselist: list[dict[str, Any]] = read_course_list(term, Path.joinpath(backups_dir, 'reports'))
... |
def read_courses_from_file(filename: Path) -> tuple[list[int], list[str]]:
"""Takes the name of a CSV file containing course records (as from a
Canvas provisioning report). Returns a tuple for which the first element
is the list of course ID numbers, and the second element is the list of
course names (... | The main task of the code is to process course data from CSV files for SSS and FYS courses, extract quiz numbers, and generate reports. It reads course information from specified files, identifies quiz numbers from course identifiers, and creates reports using the processed data, storing results in a predefined directo... | def main(argv: list[str]) -> int:
most_recent_fall = 'Fall_2022'
info_lit_dir = Path.home().joinpath('Documents', 'DEd', 'info-literacy', most_recent_fall)
SSS_courses = read_courses_from_file(info_lit_dir.joinpath('SSS-courses.csv'))
#print(SSS_courses)
#print(list(zip(SSS_courses[0], SSS_courses[1... |
def wait_for_upload_complete(last_upload: int) -> bool:
max_wait = 1000 # Max time to wait (seconds)
wait_step = 5 # Wait time each time around the loop (seconds)
waited = 0 # Time waited so far (seconds)
while waited < max_wait and not upload_complete(last_upload):
waited = waited + wait_s... | The main task of the code is to upload a CSV file to a specified API endpoint, ensuring a previous upload completed successfully. It retrieves an access token, constructs a `curl` command to send the file, captures the response, extracts the upload ID from the JSON result, and returns it. The function avoids error hand... | def upload(stem: str, dir: Path, last_upload: int) -> int:
# First, figure out if the previous upload succeeded.
wait_for_upload_complete(last_upload)
# Next, do this upload
token = get_access_token()
cmd = ['curl', '--silent', '--show-error',
'-F', 'attachment=@' + str(dir.joinpath(stem... |
def mimeTypes(self):
# return ["application/vnd.text.list"]
return ["application/python-pickle"]
def rowCount(self, parentIndex=QtCore.QModelIndex()):
if not parentIndex.isValid():
item = self.rootItem
else:
item = parentIndex.internalPointer()
return le... | This function handles the drop of MIME-encoded data in a Qt-based tree structure. It validates the drop action, checks MIME type compatibility, determines the target row, decodes the data using pickle, and initializes the tree with the decoded objects. It returns True if the drop is successful, False otherwise. | def dropMimeData(self, data, action, row, column, parent):
if action == QtCore.Qt.IgnoreAction:
return True
elif column > 0 or not data.hasFormat(self.mimeTypes()[0]):
return False
# if row != -1:
# firstRow = row
# elif parent.isValid():
# ... |
def cmd_zones(data):
total_capacity = 0
used_capacity = 0
remaining_capacity = 0
reclaimable_capacity = 0
print("--- META ZONES ---")
for zone in get_meta_zones(data):
total_capacity += zone.max_capacity
remaining_capacity += zone.capacity
used_capacity += zone.used_capa... | The main task of the code is to process command-line arguments and execute corresponding operations based on the provided subcommand. It loads data from a JSON file (defaulting to "result.json") and delegates tasks to functions like `cmd_zones`, `cmd_files`, or `cmd_extents` depending on the input command. If an invali... | def main(argv):
cmd = argv[1]
json_file = argv[2] if len(argv) > 2 else "result.json"
if cmd == 'zones':
cmd_zones(load_data(json_file))
elif cmd == 'files':
cmd_files(load_data(json_file))
elif cmd == 'extents':
cmd_extents(load_data(json_file))
else:
print("Plea... |
def receive(self):
try:
output = self.get_socket_output()
output = self.pycomparse.clean_received(output)
#print('\n' + str(output) + '\n')
except WindowsError as e:
print(e)
self.new_state = 'listen'
def vprint(self, mes):
if self.verb... | The main task of the code is to handle client disconnection logic. It attempts to receive data, checks if the connection is inactive, updates the state to 'listen', and logs disconnection. It also captures KeyboardInterrupt exceptions to trigger a graceful shutdown via `self.keykill()`, ensuring proper resource cleanup... | def _connected(self):
try:
self.receive()
if not self.conactive:
self.state = 'listen'
self.vprint('Client has disconnected.')
except KeyboardInterrupt as e:
self.keykill() |
def receive_data(self):
try:
count = 0
while True:
output = self.get_socket_output(self.rc_file_size)
count += len(output)
print('Receieved ' + str(len(output)))
if count >= self.rc_file_size:
break
... | The main task of the code is to handle file reception by calling `receive_data()`, check if the connection is active, update the state to 'listen' and log disconnection if inactive, and gracefully handle keyboard interrupts by triggering `keykill()` for cleanup. | def _init_receive_file(self):
try:
fdata = self.receive_data()
if not self.conactive:
self.state = 'listen'
self.vprint('Client has disconnected.')
except KeyboardInterrupt as e:
self.keykill() |
def check_and_call(self, obj, statemeth, args=[]):
if hasattr(obj.__class__, statemeth):
statefunc = getattr(obj.__class__, statemeth)
if callable(statefunc):
if '_init_' in statemeth or '_end_' in statemeth:
premes = ':CheckCalls:\tCalling:\t'
... | The code processes a continuous loop to handle state transitions, time calculations, and keyboard interrupts. It calculates frame time deltas, invokes state-specific methods via `check_and_call`, updates the state, and terminates upon a keyboard interrupt by setting the state to 'Terminated' and breaking the loop. | def process_loop(self):
while True:
try:
ctime = time.time()
delta = time.time() - self.prev_frametime
self.prev_frametime = ctime
statemeth = '_' + self.state
self.check_and_call(self, statemeth)
self.ch... |
def load_full_codes(train_path, version='mimic3'):
"""
Inputs:
train_path: path to train dataset
version: which (MIMIC) dataset
Outputs:
code lookup, description lookup
"""
# get description lookup
desc_dict = load_code_descriptions(version=version)
... | This code initializes a dataset processor for medical coding tasks, loading and preprocessing MIMIC-III data. It sets up code mappings, tokenizers, label structures, and sampling configurations for training/evaluation. The class handles data paths, binary label encoding, and model-specific tokenizer adjustments, prepar... | def __init__(self,
config_name,
version,
mode,
model_name,
truncate_length,
label_truncate_length=32,
term_count=4,
sort_method='max',
sample_method='pos_neg_random',
... |
def create_m3u(items, output_dir, name, has_parent):
m3u_lines = ['#EXTM3U\n']
mp3_props = {}
bts_files = [f for f in os.listdir(f'{REPE_FOLDER}/bts') if f.endswith('.mp3')]
for item in items:
if is_bt(item):
best_bts = _get_best(item, bts_files)
if len(best_bts) == 0:
... | The code processes a list of items to generate media files (m3u, PDF) and metadata, filters out unused items, organizes outputs into directories, creates a JSON summary, copies files to a repertoire folder, and optionally uploads to Google Drive after user confirmation. | def create_repe_from_items(items, name, confirm_upload=True, parent=None, upload=True):
new_items = []
for item in items:
item_props = get_song_props(item)
if 'used' in item_props and item_props['used'] == False:
print(f'Dropping {item} as it is marked unused')
continue
... |
def prepare_database() -> None:
"""
Prepares the database by filling data in variables placeholder.
"""
v.chat["weekday"] = v.chat["date"].apply(lambda x: x.weekday()) # add weekday
v.chat["hour"] = v.chat["datetime"].apply(lambda x: x.hour) # add hour
v.chat_og = v.chat.copy() # Create copy of chat to use it ... | The main task of the code is to analyze chat data by preparing the database, performing sender-specific analysis, calculating summary statistics for all senders, and generating a statistics DataFrame. It initializes data structures, processes per-sender metrics, aggregates overall chat statistics, and timestamps the fi... | def analyze_chat() -> None:
"""
Analyzes the chat and creates the stats DataFrame.
"""
prepare_database()
analysis_per_sender() # data analysis per sender
calc_remaining_stats() # get the summary statistics for all senders
time("Calculating remaining statistics")
return |
def create_reports() -> None:
"""
Creates reports about the messages.
"""
create_txt_reports()
create_time_reports()
create_nlp_reports()
return
def add_title_footer(n: int = v.sc) -> None:
"""
Inserts the title of the page and the footer with the page number.
"""
pdf.set_margins(20, 20, 20) if pdf.page_no()... | The main task of the code is to generate a multi-page PDF report summarizing chat statistics, including message counts, media analysis, emoji usage, time-based activity, and visualizations like pie charts, bar graphs, heatmaps, and word clouds. It compiles sender-specific data (e.g., common words, sentiment) and output... | def make_pdf_report() -> None:
"""
Creates a pdf file with a summary of the chat and the statistics
"""
create_reports()
path = "data/output/images/generalpage/"
i = v.sc
add_title_footer(i) # Add first page of report
new_section(11, space=20)
# insert the amount of texts, media and emojis sent by all send... |
def parse_face_movement(movement):
assert len(movement) == 1 or (len(movement) == 2 and movement[1] == "'")
face = movement[0].lower()
assert face in [f[0] for f in FACES]
is_prime = len(movement) == 2 and movement[1] == "'"
return FaceMovement(face=face, is_prime=is_prime)
def _append_movement(self... | The code's main task is to rotate a face based on a given movement string, optionally storing the movement in history. It parses the movement, appends it to the history if specified, and applies the rotation. | def rotate_face(self, movement_str, should_store_in_history=True):
face_movement = parse_face_movement(movement_str)
if should_store_in_history:
self._append_movement(face_movement)
self._apply_movement(face_movement) |
def parse_cube_movement(movement):
assert movement in AXES
return CubeMovement(axis=movement)
def _append_movement(self, movement):
self.movement_history = self.movement_history[0:self.movement_history_pointer + 1]
self.movement_history.append(movement)
self.movement_history_pointer += 1... | This method rotates a cube around a specified axis, optionally storing the movement in history. It parses the movement, appends it to the history if required, then applies the rotation to the cube. | def rotate_cube(self, axis, is_ccw=False, should_store_in_history=True):
cube_movement = parse_cube_movement(axis)
if should_store_in_history:
self._append_movement(cube_movement)
self._apply_movement(cube_movement) |
def _apply_movement(self, movement, should_callback=True):
if isinstance(movement, FaceMovement):
self._rotate_face(movement, should_callback)
elif isinstance(movement, CubeMovement):
self._rotate_cube(movement, should_callback)
else:
raise ValueError(f'Unknow... | This method adjusts the movement history pointer to a specified position, validating the input range. If the new pointer differs from the current one, it sequentially applies or unapplies movements in the history based on the direction (forward/backward) until reaching the target pointer, then triggers movement callbac... | def set_movement_history_pointer(self, pointer):
if not -1 <= pointer < len(self.movement_history):
raise ValueError(
"pointer must be -1 or lie within movement_history's valid range"
)
if pointer == self.movement_history_pointer:
return
direct... |
def get_songs_to_download():
previously_downloaded_ids = get_already_saved_song_ids(
SAVED_SONGS_FILE)
recent_song_ids = get_recent_song_ids(INT_TIME_ARRAY)
songs_to_download = []
for id in recent_song_ids:
if(id not in previously_downloaded_ids):
songs_to_download.append(id... | The main task of the code is to retrieve a list of songs, print them, download each song, and save their IDs to a text file. It fetches songs using `get_songs_to_download()`, iterates through them, downloads each with `download_song()`, and appends their IDs to 'songIds.txt' via `add_song_id()`. The process combines so... | def main():
songs_to_download = get_songs_to_download()
print(songs_to_download)
for song in songs_to_download:
download_song(song)
add_song_id('songIds.txt', song) |
def load_data(filename):
"""Load data from the csv log
Parameters:
filename (str) -- the name of the csv log
Returns:
data (dict) -- the logged data with data categories as keys
and values list of floats
"""
is_filtered = False
if os.path.isfile(filename + "... | The main task of the code is to run an Extended Kalman Filter (EKF) on logged IMU and LiDAR data from a vehicle moving in a box formation around a landmark to estimate the system's state (position, orientation, etc.). It processes sensor data, performs prediction and correction steps, and evaluates the filter's perform... | def main():
"""Run a EKF on logged data from IMU and LiDAR moving in a box formation around a landmark"""
filepath = "./data/"
# filename = "2020_2_26__17_21_59"
filename = "2020_2_26__16_59_7"
data, is_filtered = load_data(filepath + filename)
# Save filtered data so don't have to process unf... |
def load_data(filename):
"""Load data from the csv log
Parameters:
filename (str) -- the name of the csv log
Returns:
data (dict) -- the logged data with data categories as keys
and values list of floats
"""
is_filtered = False
if os.path.isfile(filename + "... | The code implements an Extended Kalman Filter (EKF) to estimate the state of a system using IMU and LiDAR data from vehicles moving in a box formation around a landmark. It initializes the filter with 7 states, processes sensor data through prediction and correction steps, and compares covariance estimates when applyin... | def main():
"""Run a EKF on logged data from IMU and LiDAR moving in a box formation around a landmark"""
filepath = "./data/"
# filename = "2020_2_26__17_21_59"
filename = "2020_2_26__16_59_7"
data, is_filtered = load_data(filepath + filename)
# Save filtered data so don't have to process unf... |
def evaluate(self, board): #interrim score function
weights = self.tunable_values[0] #Scores of various pieces
board_int = self.convert_to_int(board)
score = 0
for x in board_int:
score = score + (weights[x+6])
if not board.turn:
score = -score
... | The code implements a **quiescence search** in a chess engine, evaluating board positions by focusing on **capture moves** to avoid the "horizon effect." It uses **alpha-beta pruning** to optimize the search, recursively exploring only critical positions (captures) and updating alpha/beta bounds. The function checks fo... | def quiesce(self, board, alpha, beta): #quiescence search
try:
bestmove = list(board.legal_moves)[0]
except:
outcome = board.outcome()
if outcome.winner:
if outcome.winner == board.turn:
return 100000000
... |
def quiesce(self, board, alpha, beta): #quiescence search
try:
bestmove = list(board.legal_moves)[0]
except:
outcome = board.outcome()
if outcome.winner:
if outcome.winner == board.turn:
return 100000000
... | This function implements a fail-soft alpha-beta search with transposition table and move ordering for game tree evaluation. It recursively explores legal moves, prunes branches using alpha-beta, and stores best scores/moves in a hash table. At max depth, it calls quiesce() for endgame stability. It returns the best mov... | def failsoft_alphabeta(self, board, alpha, beta, depth, maxdepth):
self.nodes = self.nodes + 1
if depth == maxdepth:
return [self.quiesce(board, alpha, beta)]
try:
bestmove = list(board.legal_moves)[0]
except:
outcome = board.outcome(... |
def _validate_env_variables():
gcp_project = os.environ.get("gcp_project")
gcp_region = os.environ.get("gcp_region")
cloud_function_name = os.environ.get("cloud_function_name")
cloud_function_directory = os.environ.get("cloud_function_directory")
credentials = os.environ.get("credentials")
if n... | The main task of the code is to configure and validate environment settings, check the existence of a cloud function directory, and deploy if valid. It retrieves the "debug_mode" environment variable, converts it to a boolean, validates other environment variables, checks if the required path exists, and triggers deplo... | def main():
env_debug_mode: str = os.environ["debug_mode"].title()
debug_mode = ast.literal_eval(env_debug_mode)
_validate_env_variables()
if _validate_if_path_exists():
_deploy(debug_mode)
else:
raise CloudFunctionDirectoryNonExistent |
def load(idx, train_dataset, test_dataset, train_path, test_path, code="all"):
# Check if patient is in train or test dataset
if idx <= 359 and idx > 0:
patient_code = train_dataset[idx]
path = os.path.join(train_path, patient_code)
elif idx > 359 and idx <= 512:
patient_code = test_... | The function `load_image_train` processes training images by loading structural MRI (strucMRI) and fractional anisotropy (FA) data, sorting them using entropy thresholds, applying random jitter for data augmentation, and returning preprocessed input and real image pairs for training. It integrates dataset lookups, path... | def load_image_train(idx, train_dataset_lookup, test_dataset_lookup, train_path, test_path, code, shann_threshold):
strucMRI, FA, num_modalities = load(idx, train_dataset_lookup, test_dataset_lookup, train_path, test_path, code)
input_imgs, real_imgs = entropy_sort(num_modalities, strucMRI, FA, shann_threshold)... |
def _lookup(self, zone: str, what: str, where: Optional[str] = None):
resolver = dns.resolver.Resolver()
if where is not None:
resolver.nameservers = [where]
elif self.resolver is not None:
resolver.nameservers = [self.resolver]
try:
answer = resolver.... | This method queries DNSSEC-related records (DS, DNSKEY, RRSIG) for a given zone to verify its security configuration. It fetches DS records from a public resolver, DNSKEYs from zone servers, and RRSIGs to identify active KSKs/ZSKs and their validation status, storing results for DNSSEC validation checks. | def query_zone(self, zone: str):
if zone in self.known_zones:
return
# on public resolver, fetch
# the DS that is currently being announced by the registrar
# (should be currently active KSKs)
# on each zone server, fetch:
# the DNSKEYs currently publ... |
def apply_reset(
self,
circ: stim.Circuit,
qubits: list[int],
unused_qubits_idle: bool = True,
):
"""Applies a Z reset operator to specified qubits.
Args:
circ: Stim circuit to append to.
qubits: List of qubits to a... | This function appends a syndrome measurement round to a quantum error correction circuit using Stim. It applies reset, Hadamard, and CNOT gates to measure stabilizers on active qubits, then records detector results comparing current and previous measurements. Special handling is applied for deterministic and inactive d... | def syndrome_round(
self,
circ: stim.Circuit,
deterministic_detectors: list[int] = [],
inactive_detectors: list[int] = [],
) -> stim.Circuit:
"""Add stim code for one syndrome round to input circuit. Uses
self.active_qubits to decide which qubits... |
def PCA(data, firstEig=None, lastEig=None):
if lastEig is None:
lastEig = len(data) - 1
if firstEig is None:
firstEig = 0
OldDim = len(data) #Amount of components
COV = np.cov(data) # Dim x Dim
D, E = np.linalg.eig(COV)
rankTolerance = 1e-7
maxLastEig = np.sum(D > rankTole... | The function performs Independent Component Analysis (ICA) on a mixed signal to separate it into independent sources. It centers the data, applies PCA for dimensionality reduction and whitening, then uses either a symmetric or deflationary approach to estimate the demixing matrix (W). The function returns the demixed s... | def FastICA(mixedsig, approach='Symm', maxIterations=10, threshold=0.0001):
Dim = len(mixedsig)
#Center X
m = np.mean(mixedsig, 1)
m = m.reshape((Dim, 1))
mixedmean = mixedsig.copy() - m
#PCA and whitening
#E - the eigenvectors, an orthogonal matrix, Dim x Dim-k
#D - the eigenvalues
... |
def checkVerticalConnect4(currentCol, latestRowIndex, currentSymbol):
isConnect4 = False
matches = 0
for i in range(latestRowIndex, len(currentCol)):
if currentCol[i] == currentSymbol:
matches += 1
else:
break
return matches == 4
def verifyHorizontalConnect4(latestRowIndex, latestColIndex, ... | The function checks if placing `currentSymbol` at the specified board position results in a winning condition by verifying four possible connection types: vertical, horizontal, rising diagonal, and falling diagonal. It returns `True` if any of these checks confirm a win, otherwise `False` | def verifyWin(latestColIndex, latestRowIndex, currentSymbol):
currentCol = boardMatrix[latestColIndex]
if checkVerticalConnect4(currentCol, latestRowIndex, currentSymbol):
return True
if verifyHorizontalConnect4(latestRowIndex, latestColIndex, currentSymbol):
return True
if verifyRisingDiagonalConnect... |
def allFeedbacks():
return feedbackStrings(5)
def narrowDown (guess, feedback, remaining_answers):
newList = []
for answer in remaining_answers:
if testWord(guess, answer) == feedback:
newList.append(answer)
return newList
def pickNextWord(possible_guesses, remaining_answers):
al... | The code generates second guesses for each possible feedback scenario from a fixed first guess in a word game. It iterates through all feedbacks, narrows down remaining answers using the first guess and feedback, selects the optimal next guess, and writes these guesses to a file for later use. | def hardCodeSecondGuesses():
f = open("secondGuessesX.txt", "w")
for feedback in allFeedbacks():
remaining_answers = narrowDown(FIRST_GUESS, feedback, master_answers)
guess2 = pickNextWord(guesses, remaining_answers)
print(guess2)
f.write(guess2 + '\n')
f.c... |
def pickNextWord(possible_guesses, remaining_answers):
all_feedbacks = allFeedbacks()
bestGuess = ""
bestScore = INFINITY
for guess in possible_guesses:
newScore = evaluateGuess4(guess, remaining_answers, bestScore, all_feedbacks)
if newScore < bestScore:
bestGuess = guess
... | The code simulates a word-guessing game where the goal is to identify a secret word using feedback from guesses. It starts with an initial guess, iteratively selects subsequent guesses based on feedback (e.g., "bbbbb" for all wrong, "ggggg" for correct), narrows down possible answers, and counts the number of guesses r... | def simulate(secretWord, firstGuess, master_answers, verbose):
answers = master_answers.copy()
guessCount = 0
feedback = "bbbbb"
manualFeedback = False
while(feedback != "ggggg"):
if guessCount == 0:
guess = firstGuess
elif guessCount == 1:
guess = SECOND_G... |
def dealToUser(self,hand):
"""The user will be displayed their hand and can either request to be dealt a new ard from the deck or they
can stick so stop and move on. When you are dealt a card we determine the score, if you go over the limit 21 you loose
and are bust. In this case we move on."""
... | The code implements a Blackjack game where the user and computer take turns drawing cards, aiming to reach a hand value of 21 or less. The user requests additional cards, while the computer follows a risk-based strategy to decide when to stop. After all cards are dealt, the winner is determined by who is closest to 21 ... | def blackJack(self,hands,computerRisk):
"""The Black Jack method is passed a deck of playing cards, a starting deal of two cards each and the level
of risk for the computer. The cards need to add up to 21 or less. If you go above 21 you are bust (loose). First the
user has the opportunity to request m... |
def load_user_data(self):
try:
with open("users.json", "r") as file:
return json.load(file)
except FileNotFoundError:
return {}
def show_popup(self, title, message):
popup_layout = BoxLayout(orientation="vertical", spacing=10)
popup_layout.add_widg... | The main task of the code is to handle user login by validating entered credentials against stored user data. It retrieves username and password inputs, loads user data from a JSON file, checks if the credentials match, and displays a success popup with user details if valid, or a failure message if invalid. | def perform_login(self, instance):
username = self.username_input.text
password = self.password_input.text
# Load user data from JSON file
user_data = self.load_user_data()
if username in user_data and user_data[username] == password:
self.show_popup... |
def load_user_data(self):
try:
with open("users.json", "r") as file:
return json.load(file)
except FileNotFoundError:
return {}
def show_popup(self, title, message):
popup_layout = BoxLayout(orientation="vertical", spacing=10)
popup_layout.add_widg... | The code handles user signup by retrieving username and password inputs, checking if the username exists in stored user data, and either displaying an error for duplicates or saving the new user and showing a success message. | def perform_signup(self, instance):
username = self.username_input.text
password = self.password_input.text
# Load existing user data
user_data = self.load_user_data()
if username in user_data:
self.show_popup("Signup Failed", "Username already exist... |
def option():
print("1. clip a line using Cohen Sutherland Line Clipping algorithm")
print("2. clip a polygon using Sutherland Hodgeman polygon clipping algorithm")
def getClippingWindowSize():
print("Enter the clipping window size : ")
xWinMin = float(input("Enter the minimum window value of x : "))
... | The code's main task is to perform line or polygon clipping against a defined window using OpenGL's GLUT. It prompts the user to select between clipping a line (option 1) or a polygon (option 2), retrieves input coordinates, and applies clipping algorithms (`clipLine` or `clipPolygon`) with the specified window boundar... | def main():
option()
option_val = int(input("your choice: "))
if option_val != 1 and option_val != 2:
print("Invalid choice")
exit()
xWinMin, xWinMax, yWinMin, yWinMax = getClippingWindowSize()
if option_val == 1:
x1,x2,y1,y2 = getLine()
glutFunct()
glutDispl... |
def files(root):
for directory, _, filenames in os.walk(root):
if is_hidden(root, directory):
continue
for filename in filenames:
yield path.join(directory, filename)
def classify(root, filename):
basename = path.basename(filename)
if basename.startswith('.'):
... | The code processes media files from a source directory, classifying each file into categories (e.g., 'sidecar' or media types). It maps filenames to MediaFile objects, groups files by their root name, and associates sidecar files with their corresponding media files by linking them via shared base names. Ignored files ... | def find(self, src):
sidecars = []
for fn in tqdm.tqdm(files(src), unit=' files'):
cls = classify(src, fn)
if not cls:
self.ignored.append(fn)
continue
if cls == 'sidecar':
sidecars.append(fn)
continue
... |
def parser_info(onnx_model):
ir_version = onnx_model.ir_version
producer_name = onnx_model.producer_name
producer_version = onnx_model.producer_version
for info in [ir_version, producer_name, producer_version]:
print("onnx model with info:{}".format(info))
def parser_inputs(onnx_graph):
inpu... | The code parses an ONNX model to extract and analyze its structure, including model information, input/output details, initializers, and computation nodes. It loads a pre-trained MNIST ONNX model and sequentially processes its graph components for inspection or further analysis. | def onnx_parser():
model_path = 'models/mnist/mnist-8.onnx'
model = onnx.load(model_path)
# 0.
parser_info(model)
graph = model.graph
# 1.
parser_inputs(graph)
# 2.
parser_outputs(graph)
# 3.
parser_graph_initializers(graph)
# 4.
parser_graph_nodes(graph) |
def display_home():
st.header("Welcome to WorkQuixote")
st.write("This is the home section. You can find job listings here.")
if 'page' not in state:
state.page = 0
query = st.text_input("Enter your job search query")
if st.button("Search"):
if not query.isalpha():
st.... | The main task of the code is to create a Streamlit web application titled "WORKQUIXOTE" with a sidebar menu allowing users to navigate between three sections: Home, Recommendations, and About. The app dynamically displays corresponding content based on the user's selection from the sidebar dropdown, leveraging conditio... | def main():
st.title("WORKQUIXOTE")
st.sidebar.title("Sidebar")
selected_section = st.sidebar.selectbox("WORKQUIXOTE", option1)
if selected_section == "Home":
display_home()
elif selected_section == "Recommendations":
display_recommendations()
elif selected_section == ... |
def run_tests(df):
tests_run = {
"DIFFSTD": 1,
"SAX": 1
}
# Break out each series to operate on individually.
series = [y for x, y in df.groupby("series_key", as_index=False)]
# Grab basic information: number of series, length of series.
num_series = len(series)
l = len(ser... | The function `detect_multi_timeseries` performs anomaly detection on multiple time series data. It validates input parameters (minimum data points per series, number of series, and parameter ranges), runs statistical tests, scores results using sensitivity, and identifies outliers based on a max anomaly fraction. It re... | def detect_multi_timeseries(
df,
sensitivity_score,
max_fraction_anomalies
):
weights = { "DIFFSTD": 1.0, "SAX": 1.0 }
# Ensure that everything is sorted by dt and series key
df = df.sort_values(["dt", "series_key"], axis=0, ascending=True)
num_series = len(df["series_key"].unique())
... |
def perform_statistical_calculations(col):
mean = col.mean()
sd = col.std()
# Inter-Quartile Range (IQR) = 75th percentile - 25th percentile
p25 = np.quantile(col, 0.25)
p75 = np.quantile(col, 0.75)
iqr = p75 - p25
median = col.median()
# Median Absolute Deviation (MAD)
mad = robust.... | The code runs outlier detection tests on a dataset, calculating baseline statistics, normalizing data, and applying tests like Grubbs, Dixon, GESD, and Gaussian mixture. It updates the DataFrame with test scores, tracks which tests were executed, and compiles diagnostics including validity checks and constraints (e.g.,... | def run_tests(df):
# Get our baseline calculations, prior to any data transformations.
base_calculations = perform_statistical_calculations(df['value'])
diagnostics = { "Base calculations": base_calculations }
(use_fitted_results, fitted_data, normalization_diagnostics) = perform_normalization(base_ca... |
def run_tests(df):
# Get our baseline calculations, prior to any data transformations.
base_calculations = perform_statistical_calculations(df['value'])
diagnostics = { "Base calculations": base_calculations }
(use_fitted_results, fitted_data, normalization_diagnostics) = perform_normalization(base_ca... | The main task of the code is to detect univariate statistical anomalies in a dataset using an ensemble of weighted statistical tests. It validates input parameters, runs multiple anomaly detection tests (e.g., MAD, IQR, Grubbs), combines their results with predefined weights, and determines final anomalies based on sen... | def detect_univariate_statistical(
df,
sensitivity_score,
max_fraction_anomalies
):
# Standard deviation is not a very robust measure, so we weigh this lowest.
# IQR is a reasonably good measure, so we give it the second-highest weight.
# MAD is a robust measure for deviation, so we give it the ... |
def makeRoom(self):
"""Randomly produce room size"""
rtype = 5
rwide = min(self.size_x - 2, randrange(8) + 3)
rlong = min(self.size_y - 2, randrange(8) + 3)
return rwide, rlong, rtype
def placeRoom(self, ll, ww, xposs, yposs, xsize, ysize, rty, ext):
"""Place feature if e... | This function generates a random dungeon map with rooms and corridors. It initializes a grid of walls, creates initial rooms, and iteratively places additional rooms or corridors while managing failures. It links rooms via portals, adjusts placement based on failure thresholds, and ensures a specified number of rooms (... | def makeMap(self, xsize, ysize, fail, b1, mrooms):
"""Generate random layout of rooms, corridors and other features"""
# makeMap can be modified to accept arguments for values of failed, and percentile of features.
# Create first room
self.size_x = xsize
self.size_y = ysize
... |
def throw_hero_dice(self, num_of_dice= 2):
if self.phase != ROLL:
return
if num_of_dice == 2:
self.hero_dice = self.shuffle_dice(400, 100)
else:
self.hero_dice = [self.shuffle_dice(400, 100)[0], 0]
def flash(self, color1, color2):
for _ in range(10):
... | The code implements a turn-based battle system between a hero and a monster. It alternates turns, uses dice rolls to determine damage and turn order, updates the game state (HP, visuals), and returns True if the hero wins or False if the hero loses. The battle continues until either the hero or monster's HP reaches zer... | def battle(self, monster_name: str):
self.phase = ROLL
self.map.set_alpha(128)
turn = False
monster_hp = MONSTERS[monster_name]['HP']
while True:
if self.hero_hit_points <= 0:
self.map.set_alpha(255)
self.phase = MOVE
... |
def get_hero_at_pixel(self, x, y):
for boxX in range(len(self.world)):
for boxY in range(len(self.world[boxX])):
center = self.center_coords_of_hero(boxX, boxY)
boxRect = pygame.Rect(0, 0, BOX_SIZE, BOX_SIZE)
boxRect.center = center
if ... | This code handles a hero's movement on a grid-based world. It validates new positions, updates coordinates if valid, deducts movement points for steps, and triggers interactions like HP changes, battles, or resets when stepping on specific tiles (villages, monsters, mines, Zork). It also transitions the game phase to '... | def move_hero(self, pos):
x, y , center = self.get_hero_at_pixel(pos[0], pos[1])
if x == None or y == None or center == None or self.world[x][y] == NOT_ACCESSIBLE:
return
if self.world[self.x][self.y] == START_ZONE and self.world[x][y] == START_ZONE:
self.x, self.y = x,... |
def makeDirsIfNotExist(dir):
if not os.path.exists(dir):
os.makedirs(dir)
def get_train_list(lowList, highList):
assert len(lowList) == len(highList), "low:%d, high:%d"%(len(lowList), len(highList))
train_list = []
for i in range(len(lowList)):
train_list.append([lowList[i], highList[i]]... | The code processes images by dividing them into 64x64 pixel blocks, extracting gradient and luminance data, and saving these blocks into separate output directories for training. It iterates through image pairs, splits them into blocks, and stores both low-resolution and high-resolution blocks in designated folders, fa... | def seprateGradient(low_dir, high_dir, smallOutput_dir, bigOutput_dir, smallGT_dir, bigGT_dir):
makeDirsIfNotExist(smallOutput_dir)
makeDirsIfNotExist(bigOutput_dir)
makeDirsIfNotExist(smallGT_dir)
makeDirsIfNotExist(bigGT_dir)
train_list = get_train_list(load_file_list(low_dir), load_file_list(hig... |
def generate_H_v(H_v_delta, dimension):
'''
:param H_v_size: size of hypothesis set H_v
:return: hypothesis set H_v : shape=(H_v_delta**(dimension - 1) ,dimension)
each hypothesis is represented as a d-dimensional vector
H_i : numpy array of size: H_i_size * dimension
'''
H_v = np.ones(sha... | The main task of the code is to execute a hypothesis testing algorithm (algorithm_1) by generating two hypothesis matrices (H₁, H₂), creating synthetic data samples (X₁, X₂) based on selected concepts, generating and flipping labels, then running the algorithm with parameters like epsilon (β) and confidence. It sets up... | def main():
H_1 = generate_H_v(H_1_delta, dimension_1)
H_2 = generate_H_v(H_2_delta, dimension_2)
# H_indices = generate_hypotheses(H_1.shape[0], H_2.shape[0])
print(f'Total number of hypotheses: {H_1.shape[0] * H_2.shape[0]}')
if random_seed > 0:
rng = default_rng(random_seed)
else:
... |
def train(instances: np.ndarray, labels, H):
best_h, best_err = H[0, :], 1
for index in range(H.shape[0]):
h_err = cal_h_err(H[index, :], instances, labels)
if h_err < best_err:
best_h, best_err = H[index, :], h_err
return best_h, best_err
def cal_h_pos_err(h_1, h_2, X_1, X_2, l... | The algorithm performs active learning on multi-view data by iteratively selecting unlabeled samples for labeling based on disagreement between two views. It initializes labeled data, trains classifiers on each view, identifies contention points where predictions differ, queries labels from these points and additional ... | def algorithm(X_1, X_2, labels, H_1, H_2, rng):
'''
:param X_1: shape=(sample_N, dimension) instances in view 1
:param X_2: shape=(sample_N, dimension) instances in view 2
:param labels: labels of all samples
:param H_1: shape=(sample_N, dimension) hypotheses in view 1
:param H_2: shape=(sample_... |
def generate_H_v(H_v_delta, dimension):
'''
:param H_v_size: size of hypothesis set H_v
:return: hypothesis set H_v : shape=(H_v_delta**(dimension - 1) ,dimension)
each hypothesis is represented as a d-dimensional vector
H_i : numpy array of size: H_i_size * dimension
'''
H_v = np.ones(sha... | The code generates synthetic data for two concepts (H₁, H₂) and their corresponding instances (X₁, X₂) using labeled samples. It initializes random seeds, selects concepts, creates labeled samples with positive/negative flips, generates instance data based on spherical distributions, and passes these to an algorithm fo... | def main():
H_1 = generate_H_v(H_1_delta, dimension_1)
H_2 = generate_H_v(H_2_delta, dimension_2)
# H_indices = generate_hypotheses(H_1.shape[0], H_2.shape[0])
# print(f'Total number of hypotheses: {H_1.shape[0] * H_2.shape[0]}')
if random_seed > 0:
rng = default_rng(random_seed)
else:
... |
def print_table(table, pivot=None, nb_var_artif=0):
"""
display the table in a more human readable way
:param table: multidimensional array representing the table of the PL
:return:
"""
printed_table = copy.deepcopy(table)
if isinstance(printed_table, np.matrixlib.defmatrix.matrix): # Conve... | The code processes a linear programming (LP) tableau by identifying rows requiring artificial variables (marked by `-1` in specific columns). It adjusts the tableau by inserting `1` or `0` in designated positions for these artificial variables. If the tableau's dimension changes, it initiates **Phase 1** of the simplex... | def process(nb_var, table):
"""
Real process
:param signs: list of constraints signs
:param table: multidimensional array representing the PL table
:return:
"""
old_dim = len(table[0])
nb_var_artif = 0
var_artif_row = []
for row_num, row in enumerate(table):
for i in row[... |
def get_data(file='file2.txt'):
"""
Read a file containing the problem set and return the number of varianles,
the number of constraints, the matrix of the problem and wether it is max or min
:param file: file containing the PL
:return: tuple of wether min or max, the list of signs, the multi dimens... | The code processes and standardizes data for optimization, retrieving input data, calculating original variables, adjusting signs and table format, then executing a processing function with updated parameters for further analysis or solving linear programming problems. | def main():
max_min, signs, table = get_data()
print_table(table)
nb_var = len(table[0][:-2]) # Original number of variables
standardize(signs, table)
print_table(table)
process(nb_var, table) |
def get_lat_long(place_name):
place = place_name.replace(' ', '%20')
url = f'{MAPQUEST_BASE_URL}?key={MAPQUEST_API_KEY}&location={place}'
# print(url) # uncomment to test the url in browser
place_json = get_json(url)
# pprint(place_json)
lat = place_json["results"][0]["locations"][0]['latLng'][... | The main task of the code is to find the nearest subway station or stop to a specified location in Boston. It first retrieves the latitude and longitude of the input place, then determines the nearest station using coordinates. Additionally, it directly finds the nearest stop using the place name. The code combines geo... | def main():
# final test here
place = input('Enter a place name in Boston such as "Fenway Park": ')
lat, lon = get_lat_long(place)
#print(lat, lon)
print(get_nearest_station(lat, lon))
# final wrap-up
print(find_stop_near(place)) |
def get_style_sheet(profiles, team_name, year_for_roster, year_for_report, how_many_pa_to_appear, years_seperated_or_together):
style_sheet = """
<style>
.spray-container {
display: flex;
justify-content: center;
}
.container {
position: relative;
text-align: center;
... | The function generates an HTML report by assembling a template with dynamic content. It replaces placeholders like {{style_sheet}}, {{team_profile}}, and {{player_profiles}} with data from helper functions, creating a styled webpage that displays team and player profiles, along with a disclaimer. The output combines CS... | def get_html_output(profiles, team_name, year_for_roster, year_for_report, how_many_pa_to_appear, years_seperated_or_together):
html_output = """<!DOCTYPE html>
<html>
{{style_sheet}}
<body>
{{team_profile}}
<br>
{{player_profiles}}
<br>
... |
def checkExists(unit):
check_message = "checkExist" + " " + unit
s.sendto(check_message.encode(), getClient("map"))
return recvData("checkExistData")
def checkCoords(coords):
check_message = "checkCoords" + " " + coords
s.sendto(check_message.encode(), getClient("map"))
return recvData("checkCoo... | This function validates a building request by checking if the specified building type is allowed, if it already exists (except for walls), and if the coordinates are empty. If valid, it sends a construction request, creates unit data for the building, and confirms the build. Otherwise, it prints error messages for inva... | def buildRequest(coords, building):
buildings_list = ["wall", "archery", "stable", "barracks", "workshop"]
if building not in buildings_list:
print("Invalid building")
return
if building != "wall" and checkExists(building) == "yes":
print(building + " has already been built!")
... |
def getPos(unit_name):
pos_message = "getPos" + " " + unit_name
s.sendto(pos_message.encode(), getClient("map"))
return recvData("getPosData")
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_pos[0] +... | This function moves a game unit in a grid-based system by a specified distance in a given direction (up, down, left, right). It checks if the target cell is empty, updates positions if unblocked, and halts if blocked, printing the obstacle. Movement occurs step-by-step with delays based on unit-specific data. | def moveUnit(unit_name, direction, distance_input):
distance = int(distance_input)
if direction == "up":
while distance != 0:
current_pos = getPos(unit_name)
current_pos_list = current_pos.split(",")
current_pos_up = current_pos_list[0] + \
"," + str(... |
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_pos[0] + "," + str((int(current_pos[1]) - 1))
current_pos_down = current_pos[0] + "," + \
str((int(current_pos[1]) + 1))
current_pos_le... | This function creates a villager of specified type (farmer, lumberjack, miner) if under the 6-villager limit. It generates a unique name, checks for available town center spawn space, assigns visual symbols, positions the villager near the town center, deducts resources, and handles errors for full capacity or blocked ... | def createVillager(villager_type):
if villager_num < 6:
if villager_type == "farmer":
villager_name = villager_type + str(farmer_num)
elif villager_type == "lumberjack":
villager_name = villager_type + str(lumberjack_num)
else:
villager_name = villager_typ... |
def checkExists(unit):
check_message = "checkExist" + " " + unit
s.sendto(check_message.encode(), getClient("map"))
return recvData("checkExistData")
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_p... | The function creates a militia unit adjacent to a barracks if the spawn position is unoccupied. It checks barracks existence, verifies the "down" position is empty, calculates coordinates, and initializes the militia with predefined stats. If blocked, it alerts the user; if no barracks exist, it prompts construction. | def createMilitia():
militia_name = "militia" + str(militia_num)
if checkExists("barracks") == "yes":
if getNextTo("barracks", "down") == "empty":
barracks_pos = getPos("barracks").split(",")
barracks_spawn = barracks_pos[0] + \
"," + str(int(barracks_pos[1]) + 1)... |
def checkExists(unit):
check_message = "checkExist" + " " + unit
s.sendto(check_message.encode(), getClient("map"))
return recvData("checkExistData")
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_p... | The code creates an archer unit named "archerX" based on militia_num, checking if an "archery" structure exists and if the position below it is empty. If valid, it sets the archer's coordinates and adds them to the unit data with specific attributes. If the archery is blocked or missing, it prints error messages requir... | def createArcher():
archer_name = "archer" + str(militia_num)
if checkExists("archery") == "yes":
if getNextTo("archery", "down") == "empty":
archery_pos = getPos("archery").split(",")
archery_spawn = archery_pos[0] + "," + str(int(archery_pos[1]) + 1)
setCoords(arche... |
def checkExists(unit):
check_message = "checkExist" + " " + unit
s.sendto(check_message.encode(), getClient("map"))
return recvData("checkExistData")
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_p... | This function creates a knight unit by checking if a 'stable' structure exists and if the position below it is unoccupied. If valid, it sets the knight's spawn coordinates, assigns attributes like health, speed, and name, and initializes its state. If the stable is missing or the spawn site is blocked, it prompts the u... | def createKnight():
knight_name = "knight" + str(knight_num)
if checkExists("stable") == "yes":
if getNextTo("stable", "down") == "empty":
stable_pos = getPos("stable").split(",")
stable_spawn = stable_pos[0] + "," + str(int(stable_pos[1]) + 1)
setCoords(stable_spawn,... |
def checkExists(unit):
check_message = "checkExist" + " " + unit
s.sendto(check_message.encode(), getClient("map"))
return recvData("checkExistData")
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_p... | The function creates a RAM unit adjacent to a workshop if the workshop exists and the downward position is unoccupied. It generates the RAM's name, checks for a valid spawn location, sets coordinates, and initializes unit data. If the workshop is missing or the spawn site is blocked, it outputs error messages to prompt... | def createRam():
ram_name = "ram" + str(ram_num)
if checkExists("workshop") == "yes":
if getNextTo("workshop", "down") == "empty":
workshop_pos = getPos("workshop").split(",")
workshop_spawn = workshop_pos[0] + \
"," + str(int(workshop_pos[1]) + 1)
set... |
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_pos[0] + "," + str((int(current_pos[1]) - 1))
current_pos_down = current_pos[0] + "," + \
str((int(current_pos[1]) + 1))
current_pos_le... | The function calculates the number of active farming units every 10 time units by checking adjacent tiles. Each farmer unit contributes to food production based on their activity. If a farmer is next to a farm, they farm (increase count), else they idle (decrease count). Food is then calculated as 10 times the active f... | def farmer(run_time):
farmer_amount = 0
if run_time % 10 == 0:
for unit_name in unit_data:
if unit_data[unit_name][4] == "farmer " + player_num:
if getNextTo(unit_name, "up") == "dead":
break
elif getNextTo(unit_name, "up") == "farm":
... |
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_pos[0] + "," + str((int(current_pos[1]) - 1))
current_pos_down = current_pos[0] + "," + \
str((int(current_pos[1]) + 1))
current_pos_le... | The main task of the code is to calculate the amount of wood collected by lumberjack units. It checks if the current run_time is a multiple of 10, then iterates through all units. For each lumberjack unit, it examines adjacent cells for trees, sets the unit to "chopping" if a tree is found, and increments the lumberjac... | def lumberjack(run_time):
lumberjack_amount = 0
if run_time % 10 == 0:
for unit_name in unit_data:
if unit_data[unit_name][4] == "lumberjack " + player_num:
if getNextTo(unit_name, "up") == "dead":
break
elif getNextTo(unit_name, "up") == "... |
def getNextTo(unit_name, direction):
if getPos(unit_name) != "dead":
current_pos = getPos(unit_name).split(",")
current_pos_up = current_pos[0] + "," + str((int(current_pos[1]) - 1))
current_pos_down = current_pos[0] + "," + \
str((int(current_pos[1]) + 1))
current_pos_le... | The code manages miner units to collect stones. When run_time is a multiple of 10, it checks adjacent tiles of each miner. If a stone is found, the miner switches to "mining" mode and increments the count. If no stone is nearby, it becomes "idle" and reduces the count. Finally, it calculates total stones as 10×miner_am... | def miner(run_time):
miner_amount = 0
if run_time % 10 == 0:
for unit_name in unit_data:
if unit_data[unit_name][4] == "miner " + player_num:
if getNextTo(unit_name, "up") == "dead":
break
elif getNextTo(unit_name, "up") == "stone":
... |
def getStats(stats):
stats_message = "getStats" + " " + stats
s.sendto(stats_message.encode(), getClient("stats"))
return int(recvData("getStatsData"))
def sendStats(food, stone, wood):
stats = "stats" + " " + str(food) + " " + str(stone) + " " + str(wood)
s.sendto(stats.encode(), getClient("stats")... | The main task of the code is to process food consumption for units in a simulation. Every 10 time units, it iterates through a copy of unit data to avoid modification during iteration. If a unit has available food, it sends food stats to the unit's designated location. If no food remains and the unit's third attribute ... | def consumeFood(run_time):
if run_time % 10 == 0:
# Copy unit data to avoid list changing whilst being iterated over
# error
unit_data_copy = unit_data.copy()
for unit in unit_data_copy:
if getStats("food") > 0:
sendStats(unit_data[unit][3], 0, 0)
... |
def consumeFood(run_time):
if run_time % 10 == 0:
# Copy unit data to avoid list changing whilst being iterated over
# error
unit_data_copy = unit_data.copy()
for unit in unit_data_copy:
if getStats("food") > 0:
sendStats(unit_data[unit][3], 0, 0)
... | The code defines a function `threads()` that runs an infinite loop, repeatedly calling `consumeFood()`, `farmer()`, `miner()`, `lumberjack()`, and `militia()` with an incrementing `run_time` value. Each iteration pauses for 1 second, simulating sequential task execution over time. The main task is to model a continuous... | def threads():
run_time = 0
while True:
consumeFood(run_time)
farmer(run_time)
miner(run_time)
lumberjack(run_time)
militia()
run_time += 1
time.sleep(1) |
def get_model_files(self, model, workspace):
file_dict = {}
model_id = self.models[(self.models.name == model) & (self.models.currentWorkspaceName == workspace)]['id'].iloc[0]
URL = self.api.api_url + "models/{0}/files".format(model_id)
files = self.get_request(URL)['files']
... | The code exports data by retrieving model and file IDs, fetching metadata, and concatenating CSV chunks from an API into a DataFrame. It processes each chunk, combines them, adjusts column names, and removes the header row before returning the cleaned dataset. | def export_data(self, model, workspace, export):
model_id = self.models[(self.models.name == model) & (self.models.currentWorkspaceName == workspace)]['id'].iloc[0]
file_id = self.get_model_files(model=model, workspace = workspace)[export]['id']
columns, delimiter = self.get_export_metadata(mod... |
def prepare_data_for_lines():
df_5g_static_lines = []
for num in range(1, 6):
df_5g_static_lines.append(
pd.read_csv(get_output_path('5g-static-line', num, 'phases.csv'))
)
# only 4 runs for 5G blocked
df_5g_block_static_lines = []
for num in range(1, 5):
df_5g_b... | The main task of the code is to generate boxplots for two distinct datasets. It prepares data for 'lines' and 'points' using separate functions, then calls `output_boxplot` with each dataset and their respective type parameter to visualize the data as boxplots tailored for lines and points. | def main():
data_for_lines = prepare_data_for_lines()
output_boxplot(*data_for_lines, type='lines')
data_for_points = prepare_data_for_points()
output_boxplot(*data_for_points, type='points') |
def get_or_create_client_id(request: 'HttpRequest') -> Tuple[str, bool]:
client_id = request.COOKIES.get(COOKIE_NAME)
if client_id is None:
return generate_client_id(), True
else:
return client_id, False
def store_user_cookie(response: 'HttpResponse', client_id: str):
response.set_cookie(
COOKIE_NAME,
clien... | The function processes analytics by generating or retrieving a unique client ID, setting a cookie if newly created, and storing request parameters associated with the client ID for tracking purposes. | def _process_analytics(context: RequestContext):
client_id, created = get_or_create_client_id(context.request)
if created:
store_user_cookie(context.response, client_id)
store_parameters(context.request, client_id=client_id) |
def predict_class(sentence, model):
p = bow(sentence, words, show_details=False)
res = model.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]
results.sort(key=lambda x: x[1], reverse=True)
return_list = [{"intent": classes[r[0]... | This code implements a chatbot that handles user queries by checking for previous responses, predicting intent using a model, and providing answers. If the response is unhelpful, it offers related questions for selection, allowing users to choose alternative queries for further assistance. | def chat():
while True:
print("Start")
print("Chatbot Response: Hello! How can I assist you today?")
conversation = []
while True:
message = input("You: ")
if message.lower() == 'exit':
print("Chatbot Response: Have a nice day!")
... |
def get_current_ip(host_json_path, network_name):
if not os.path.exists(host_json_path):
return None
with open(host_json_path) as fh:
host_data = json.loads(fh.read())
return host_data.get('ipv4', {}).get(network_name)
def allocate_new_ip(network_name, hosts_dir, networks_json):
hosts = ... | (The code allocates an IP address to a host within a network, ensuring concurrency control via a lock. It checks if the host already has an IP; if not, it assigns a new one from the specified network. The allocated IP and prefix length are stored in the host's JSON file and printed to stderr/stdout. Key tasks: IP alloc... | def main(host_name, network_name, hosts_dir, networks_json):
lockfile = os.path.join(
os.path.dirname(os.path.dirname(__file__)), '.ip-alloc.lock')
with InterProcessLock(lockfile):
host_json_path = os.path.join(hosts_dir, host_name, 'host.json')
current_ip = get_current_ip(host_json_path... |
def split_session_list(in_f):
with open(in_f, 'r', encoding = 'utf8') as i:
lines = i.readlines()[1:]
curr_track_id = 1
all_session_list = []
one_session_list = []
for line in lines:
item_list = line.strip('\n').split('\t')
curr_sess_id = int(item_list[0])
if curr_ses... | The function processes an input file by splitting it into session lists, filters non-empty sessions, processes each session using the given domain, collects results in a list, and returns them. It also prints the counts of processed and total sessions. | def process_file(in_f, domain):
all_session_list = split_session_list(in_f)
res_list = []
for item in all_session_list:
one_sess = build_session_list(item)
if len(one_sess) == 0:
continue
one_res_dict = process_session_list(one_sess, domain)
res_list.append(one_re... |
def createConnection(db_file):
try:
logger.info("Trying to Open connection")
conn = sqlite3.connect(db_file)
return conn
except sqlite3.Error as e:
print(e)
return None
def getTargetTickerFromDB ( pConn):
logger.info("Re... | The main task of the code is to initiate an application that checks for a SQLite database file, retrieves stock tickers from it, and fetches financial data from an API for those tickers using a predefined data structure. If the database is missing, it logs an error and exits. The process involves logging application st... | def callDriver():
logger.info("\n\n\n\n ================== Application Started : WALL ==============================\n\n")
#targetTickersAry = np.array(["C" , "AIG", "F", "QCOM", "VSLR" , "FOSL", "AKS", "JMBA", "NOK"])
db_loc_1 = os.path.join(BASE_DIR, 'GOOG_scraper_DB_v13.sqlite')
... |
def handle_text_to_text_message(self, new_message: str):
context_messages = self.contexts[self.current_context]
context_messages.append({"role": "user", "content": new_message})
if num_tokens_from_messages(context_messages) > TOKEN_LIMIT:
context_messages = context_messages[-5:] #... | The code routes incoming messages based on the specified command or predicted intent. If the command is "text" or "image", it processes accordingly; for "autogen", it uses a custom handler. If the command is unknown, it classifies the message using a trained Naive Bayes model to determine if it's an image or text reque... | def handle_message(self, new_message: str, command: str):
if self.current_context == None:
self.current_context = "0"
if command == "text":
return self.handle_text_to_text_message(new_message) # str
elif command == "image":
return self.handle_text_to_image(n... |
def findAppt():
""" Prints whether an appointment exists for a given user, date, and time. If one exists, returns
the user and appointment. Else, returns None by default.
"""
user, date, start = getInput('find') # the User, Date, and Time objects for the appointment to find
if user:
appt... | The code reschedules an existing appointment by prompting the user for new date and time details, validating inputs, checking for conflicts with the user's existing appointments, and updating the appointment if no conflicts exist, or informing the user of a conflict otherwise. | def reschedule():
""" If an appointment exists for a given user at a given date and start time, asks the user for
the new date and times for the appointment. If the new appointment does not conflict with another
appointment for that user, changes the date and times for the appointment to the new dat... |
def error(text):
global error_window
error_window = Tk()
error_window.title("Error")
error_window.geometry("200x125")
Label(error_window,height=1,text=" ",font='verdana 9') .grid(row=1, column=0, sticky=NSEW)
Label(error_window,height=1,text="",font='verdana 9') .grid(row=0, column=1, sticky=NS... | The code defines a function `add` that integrates a roller shutter (luik) control interface into a GUI. It connects to a COM port, creates UI elements (labels, buttons) for controlling the shutter (open/close/automatic/data/status), and updates the global `rolluiken` dictionary. Error handling ensures connectivity, and... | def add(name,com):
global x,rolluiken
try:
g = Rolgordijn(com)
except Exception:
error("Kan niet verbinden\nvia deze COM")
rolluiken[x] = [name,com,g]
Label(main_window,text=name, font='verdana 9') .grid(row=x,column=0,sticky=W)
x = x + 1
Button(main_window, text="Luik open",... |
def error(text):
global error_window
error_window = Tk()
error_window.title("Error")
error_window.geometry("200x125")
Label(error_window,height=1,text=" ",font='verdana 9') .grid(row=1, column=0, sticky=NSEW)
Label(error_window,height=1,text="",font='verdana 9') .grid(row=0, column=1, sticky=NS... | This function adds a new rolluik (shutter) entry with a name and COM port, ensuring no duplicate names, valid COM ports, and input constraints. It checks for empty fields, name length limits, BEE movie restrictions, and existing name/COM port conflicts before adding the entry to the system and closing the input window. | def add_rolluik():
global nameEntry,comEntry,add_window,rolluiken
name= nameEntry.get()
com = comEntry.get()
if name == "" or com == "":
error("Error\nVoer waardes in")
elif len(name)>20:
if bee(name):
error("BEE MOVIE NOT ALLOWED!!!")
else:
error("Err... |
def initialize_parameters_deep(layer_dims):
np.random.seed(3)
parameters={}
L=len(layer_dims)
for l in range(1, L):
parameters['W'+str(l)]=np.random.randn(layer_dims[l], layer_dims[l-1])*0.01
parameters['b'+str(l)]=np.zeros((layer_dims[l], 1))
assert(parameters['W' ... | The main task of the code is to train a deep neural network with multiple layers using gradient descent. It initializes parameters, iteratively performs forward and backward propagation, updates parameters using gradients, and visualizes the cost over iterations. The function returns the trained parameters after comple... | def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations=3000, print_cost=False):
np.random.seed(1)
costs=[]
parameters=initialize_parameters_deep(layers_dims)
for i in range(0, num_iterations):
AL, caches=L_model_forward(X, parameters)
cost=compute_cost(AL, Y)
... |
def basic_tokenize(tweet):
"""Same as tokenize but without the stemming"""
tweet = " ".join(re.split("[^a-zA-Z.,!?]*", tweet.lower())).strip()
return tweet.split()
def preprocess(text_string):
"""
Accepts a text string and replaces:
1) urls with URLHERE
2) lots of whitespace with one instance
3) mentions with M... | The code performs text prediction using a trained model by preprocessing input JSON data, extracting features (including POS tags), concatenating vectors, and returning predictions as JSON. It handles errors and ensures a trained model is available. | def predict():
if model:
try:
json_ = request.json
msg_df = pd.DataFrame(json_)
stopwords=stopwords = nltk.corpus.stopwords.words("english")
other_exclusions = ["#ff", "ff", "rt"]
stopwords.extend(other_exclusions)
msg_vector = vectorizer.transform(msg_df).toarray()
msg_tags = []
for m in m... |
def embed_image(input_img, processor, model, device):
inputs = processor(images=input_img, return_tensors="pt")
image_tensor = inputs["pixel_values"].to(device)
with torch.no_grad():
outputs = model.get_image_features(image_tensor)
return outputs
def get_closest_image(embedded_input_img, embeddi... | The main task of the code is to predict the geographic location (latitude and longitude) of an input image by comparing its embedding with a database of known geocells. It selects top geocells based on probability thresholds, filters relevant embeddings, identifies the closest match, calculates the distance from the in... | def main(input_lon, input_lat):
input_img = Image.open(input_img_path)
embedded_input_img = embed_image(input_img, processor, model, device)
embeddings_df = pd.read_parquet(embeddings_path)
metadata_df = pd.read_csv(metadata_path)
top_k_geocells = classifier(embedded_input_img)
value... |
def forward(self, X, data_size):
A, A_device = self.init_outputs(data_size)
if IN_CPU:
A = self.forward_cpu(X, data_size)
for i, weight_device in enumerate(self.weights_device):
if i == 0:
self._matmul(cuda.to_device(X), weight_device, A_device[i])
... | This code trains a neural network using GPU acceleration by performing forward and backward passes over multiple iterations. It calculates the loss, adjusts the learning rate if the loss is sufficiently low, and updates model parameters. The input data is augmented with a bias term, and CUDA is used for device-specific... | def train(self,X,y):
X = np.c_[X, np.ones(self.input_layer_shape[0])]
Y_device = cuda.to_device(y)
flag = True
# A_device_prev = None
for i in range(self.iterations):
A, A_device = self.forward(X,self.n_samples_train)
# A = self.forward_cpu(X,self.n_sample... |
def resolve(self, ids, categories=None):
"""
Returns a list of ids or categories depending on what is passed
to each internal corpus reader function.
"""
if ids is not None and categories is not None:
raise ValueError("Specify ids or categories, not both")
if ... | The main task of the code is to calculate and return corpus statistics, including file count, category count, file extensions distribution, total size, max/min/mean file sizes. It filters documents by given IDs/categories, processes file metadata, and aggregates metrics into a dictionary for analysis. | def stat(self, ids=None, categories=None):
"""
Calc corpus statistics
:param ids: only for documents in ids list
:param categories: only for documents in categories list
:return: dictionary with metrics
"""
fileids = self.resolve(ids, categories)
# Categ... |
def paras(self, ids=None, categories=None):
clean_text = self.clean_text
for txt in self.docs(ids, categories):
for s in txt.splitlines():
raw_text = s.strip()
text = clean_paragraph(raw_text) if clean_text else raw_text
if text:
... | The code calculates and returns corpus statistics, including paragraph, sentence, and word counts (if enabled) for specified documents or categories, by extending the base class's statistics with these metrics. | def stat(self, ids=None, categories=None, count_words=False):
"""
Calc corpus statistics
:param count_words:
:param ids: only for documents in ids list
:param categories: only for documents in categories list
:return: dictionary with metrics
"""
stat_dict ... |
def toIntArray(string, binary):
"""
converts a string (binary or character) into an int array
Args:
string (str): string (binary or character)
binary (bool): true if string is a binary string, false if char array
Returns:
int array: int array based on string
"""
# conve... | The function prepares text and key for a block cipher by converting them into integer arrays, padding the text with spaces to ensure divisible block length, splitting the text into blocks of size `blen`, and returning the processed text, key, and number of blocks for encryption/decryption. | def prepareBC(txt, key, binTxt, binKey, blen):
# prepares text, key, and number of blocks for use in block cipher scheme
txt = toIntArray(txt, binTxt)
key = toIntArray(key, binKey)
# split txt into into n blocks of length blen
# if m has indivisible length to blen, add spaces to the end
txt = ... |
def toIntArray(string, binary):
"""
converts a string (binary or character) into an int array
Args:
string (str): string (binary or character)
binary (bool): true if string is a binary string, false if char array
Returns:
int array: int array based on string
"""
# conve... | The function `altPRF` generates a pseudo-random integer array by traversing a binary tree of height `n`, using a secure pseudo-random generator (PRG). It processes input `k` and `x`, converting them to binary formats, then iteratively applies the PRG, splitting its output based on bits of `x` (left for '0', right for '... | def altPRF(k, x, binK=False, binX=False):
"""
pseudo-random function composed of PRGs - secure if PRG is secure
computationally intensive!!
traverses through a binary tree of height n
Args:
k (_type_): string (binary or character) of length m
x (_type_): string (binary or character)... |
def set_players(*args):
global player_1, player_2, player_turn
if player_turn is player_1:
player_1 = create_from_string(selected_cross.get(), Player.CROSS)
player_2 = create_from_string(selected_zero.get(), Player.ZERO)
player_turn = player_1
else:
player_1 = create_from_str... | The function `drop_board()` initializes a new game round by resetting global variables (winner, player_turn, turn_count), randomly selecting the starting player, updating UI highlights for the winner and next player, and resetting all board cells to their default state. It prepares the game for a fresh start, ensuring ... | def drop_board():
global winner, player_turn, turn_count
set_players()
player_turn = random.choice([player_1, player_2])
winner = Player.NOT_SET
turn_count = 0
highlight_winner()
highlight_next_turn_player()
for row in board:
for cell in row:
cell.drop_state()
... |
def set_font_from_preset(self, preset_name: str):
self.set_font(*self._font_presets.get(preset_name).get("font"))
self.set_text_color(*self._font_presets.get(preset_name).get("color"))
def show_stats(self, ship: Ship, start_x: int, end_x: int):
STAT_COLUMNS = [
[ShipStat.HP, ShipStat... | This code generates a PDF sheet for a ship, including its name, statistics, traits, system configurations (core and slot systems), weapon mounts, and bays. It organizes content using predefined fonts, positions tables on the page, and outputs the final document to the specified file path. | def create_sheet(self, ship: Ship, output_path: str):
self.alias_nb_pages()
self.add_page()
self.set_font_from_preset("Heading 2")
self.cell(0, 8, f"{ship._name}", border=0, ln=1, align='C')
self.set_font_from_preset("Paragraph")
self.show_stats(ship, self.l_margin, int((... |
def _find_init_client_name(self, content: str, init_pattern: str) -> str:
match = re.search(init_pattern, content)
return match.group(1) if match else ''
def _update_specific_patterns(self, specifics: List[Dict], var_name: str) -> List[Dict]:
return [{'pattern': specific['pattern'].format(var_na... | This function scans a file for specific library usages by checking import patterns, extracting initialization variable names, updating pattern specifics, and analyzing content for targeted usage. It processes each library's regex patterns to identify and track relevant code constructs. | def _scan_file(self, file_path: str, libraries: Dict):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
for library, patterns in libraries.items():
if re.search(patterns['import_pattern'], content):
var_name = self._find_init... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.