dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def process_sentence(sentence):
doc = nlp(sentence)
if non_punct_count(doc) <= NO_SPLIT_LIMIT:
return [[token for token in doc]]
all_phrases = []
current_phrase = []
for token in doc:
# print(token.text, token.dep_, token.pos_, token.lemma_)
if token.pos_ in [ADP, AUX, CONJ,... | The code processes input text by replacing specific characters, splitting sentences, chunking them, consolidating chunks, and finalizing a document. It cleans text, segments into sentences, processes each into chunks, consolidates chunks, and returns a unified document structure. | def process_input(input_text):
input_text = input_text.replace("\"", "”")
input_text = input_text.replace('\n', ' ')
input_text = input_text.replace('\t', ' ')
input_text = input_text.replace('\r', ' ')
sentences = re.split('(?<=[.!,?”"]) +', input_text)
processed_sentence_chunks = []
for s... |
def are_files_released(self, post):
medias = self.get_media_from_paths(post)
return False if not medias[1] or list(set(medias[0]) ^ set(medias[1])) else True
def are_files_converted(self, post):
images_without_webp = list(filter(lambda x: not x.endswith(self.webp_format) and re.match(r'^\d{1,2}... | The main task of the code is to copy media files from source paths to destination paths for release, converting them to WebP if not already converted. It skips files already in the release directory, handles missing destination folders by creating them, and logs errors if copying fails. | def release_media_files(self, data):
if not data:
data = self.media_data_paths
for post in data:
#Checking: if files already moved into release, then skip iteration
if self.are_files_released(post):
continue
if not self.are_files_converte... |
def wrap_str(paragraph, cols):
lines = []
for line in paragraph.splitlines():
if not line:
wrapped_lines = [""]
else:
wrapped_lines = _wrap_line(line, cols)
lines.extend(wrapped_lines)
if paragraph and paragraph[-1] == "\n":
lines.append("")
return... | The code creates a text editor interface using the curses library. It handles user input for navigation (arrow keys), text editing (backspace, delete), and cursor positioning. The editor displays wrapped text on the screen with custom coloring, logs cursor positions, and manages screen dimensions dynamically. It includ... | def run_app(stdscr):
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
entry = ""
rows, cols = stdscr.getmaxyx()
cursor_pos = ClassNamespace()
cursor_pos.x = 0
cursor_pos.y = 0
while True:
# Clear screen
stdscr.clear()
# This raises ZeroDivisionError when... |
def initFTPUpdater(self):
self.isInitFTPUpdater=True
logger=Debug()
logger.enablePrintConsole=False
logger.logText="ftpUpdateRunner"
logger.warningText="ftpUpdateRunner"
logger.errorText="ftpUpdateRunner"
self.ftpUpdater = FTPUpdater(self.nic,logger)
self.... | This function manages the FTP updater process by checking boot stage changes. If triggered, it initializes logging, sets a timer to either start the FTP updater or abort based on conditions, and updates the stage. If not triggered, it checks readiness to run the updater in a thread, with sleep intervals for timing cont... | def logicStageFTPUpdater(self):
if(self.bootStageChanged):
self.drawingTextLine1="FTP Updater"
self.logFTPUpdater.append("Init")
if self.needDoneFTPUpdater:
self.tim = Timer(period=1000, mode=Timer.ONE_SHOT, callback=lambda t:self.initFTPUpdate... |
def stageChangerCallback(self,newVal):
self.bootStage=newVal
self.bootStageChanged=True
def logicStageEthernet(self):
if(self.bootStageChanged):
self.drawingTextLine1="Ethernet module"
self.drawingTextLine2="Init"
self.tim = Timer(period=1000, mode... | The function `microStageRunner` manages sequential boot stages by executing specific logic based on `self.bootStage`. It initializes a timer for stage transitions, handles Ethernet, FTP update, and MQTT initialization tasks, and pauses when no stage changes are detected. | def microStageRunner(self):
if self.bootStage==1:
if(self.bootStageChanged):
self.tim = Timer(period=3000, mode=Timer.ONE_SHOT, callback=lambda t:self.stageChangerCallback(2))
self.bootStageChanged=False
else:
time.sleep_ms(1)
elif ... |
def _get_parquet(
table_name: str, year: int, download: bool = True, save: bool = True
) -> pd.DataFrame:
file_name = f"{year}_{table_name}.parquet"
try:
table = pd.read_parquet(defaults.processed_data.joinpath(file_name))
except FileNotFoundError as exc:
print(
f"Table {tabl... | The function `read_table` loads and concatenates data from multiple tables (or table-year combinations) by retrieving Parquet files, applying yearly schemas if specified, and optionally adding metadata like year, duration, or table names. It returns a unified DataFrame with combined data, handling schema enforcement an... | def read_table(
table_name: _OriginalTable | list[_OriginalTable] | tuple[_OriginalTable],
from_year: int | None = None,
to_year: int | None = None,
apply_yearly_schema: bool = True,
add_year: bool = False,
add_duration: bool = False,
add_table_names: bool = False,
**kwargs,
) -> pd.Data... |
def read_table(
table_name: _OriginalTable | list[_OriginalTable] | tuple[_OriginalTable],
from_year: int | None = None,
to_year: int | None = None,
apply_yearly_schema: bool = True,
add_year: bool = False,
add_duration: bool = False,
add_table_names: bool = False,
**kwargs,
) -> pd.Data... | This function loads and processes a specified table or list of sub-tables, combining them into a single DataFrame. It applies schema-defined settings, classifications, and handles edge cases like redundant columns. The result is a consolidated table adhering to the specified metadata structure and parameters. | def load_table(
table_name: _Table,
from_year: int | None = None,
to_year: int | None = None,
**kwargs,
) -> pd.DataFrame:
"""docs"""
if table_name in metadata.original_tables:
table_name_list = [table_name]
else:
table_name_list: list[_Table] = metadatas.schema[table_name]["... |
def load_table_data(
table_name: str, year: int, urban: bool | None = None
) -> pd.DataFrame:
"""
Reads CSV file(s) containing data for a given table, year, and urban/rural category,
and returns the data as a pandas DataFrame.
:param table_name: The name of the table to be read.
:type table_nam... | The main task of the code is to clean a specified table using metadata for both urban and non-urban data of a given year, applying metadata to each subset, and concatenating the cleaned results into a unified pandas DataFrame for further analysis or processing. | def clean_table_with_metadata(table_name: str, year: int) -> pd.DataFrame:
"""
Clean the specified table using metadata and return a cleaned pandas DataFrame.
:param table_name: The name of the table to be cleaned.
:type table_name: str
:param year: The year for which the table will be cleaned.
... |
def is_dir(self):
"""Return True if the query has blobs under it's prefix."""
if self._is_dir is None:
self._is_dir = any(self.get_prefix_blobs())
return self._is_dir
def get_prefix_blobs(self) -> Iterable[BlobProperties]:
"""Return an iterator of objects in the storage that ... | This method returns the latest modification time of a directory or blob. If the object is a directory, it computes the maximum last-modified timestamp among all items in the directory. For a blob, it directly returns the last-modified timestamp of the blob. | def mtime(self) -> float:
"""Returns the modification time."""
if self.is_dir():
return max(
item.last_modified.timestamp() for item in self.get_prefix_blobs()
)
return self.blob_client().get_blob_properties().last_modified.timestamp() |
def is_dir(self):
"""Return True if the query has blobs under it's prefix."""
if self._is_dir is None:
self._is_dir = any(self.get_prefix_blobs())
return self._is_dir
def get_prefix_blobs(self) -> Iterable[BlobProperties]:
"""Return an iterator of objects in the storage that ... | This method calculates and returns the size in bytes of a file or directory. If the object is a directory, it sums the sizes of all child items; otherwise, it retrieves the direct size from the blob's properties. | def size(self) -> int:
"""Returns the size in bytes."""
if self.is_dir():
return sum(item.size for item in self.get_prefix_blobs())
return self.blob_client().get_blob_properties().size |
def is_dir(self):
"""Return True if the query has blobs under it's prefix."""
if self._is_dir is None:
self._is_dir = any(self.get_prefix_blobs())
return self._is_dir
def get_prefix_blobs(self) -> Iterable[BlobProperties]:
"""Return an iterator of objects in the storage that ... | This method downloads an object from storage to a local path, creating necessary directories if it's a directory. It iterates over blobs in the prefix, constructs local paths, and downloads each blob. If the object is a file, it downloads directly. Finally, it verifies the local file exists, raising an error if not. | def retrieve_object(self):
if self.is_dir():
self.local_path().mkdir(parents=True, exist_ok=True)
for item in self.get_prefix_blobs():
name = item.name[len(self.blob_path) :].lstrip("/")
local_path = self.local_path() / name
local_path.pare... |
def CREATE_WINDOW_FRAMES():
window = Tk()
# Set the size of the window
window.geometry("1500x900")
window.title("LOCAL ALIGNMENT APP")
label = Label(window, text="LOCAL SEQUENCE ALIGNMEN", fg="#800080", font=("Georgia", 15, "bold"))
label.pack(pady=30)
frame = ttk.LabelFrame(window, height=1... | This code creates a GUI application using Tkinter with two radio buttons for selecting between DNA and PROTEIN modes. It dynamically switches between two frames (DNA_LF and Protein_LF) based on user selection, utilizing an IntVar to track the choice. The interface includes layout management, event handling, and a main ... | def DNA_PROTEIN_LF():
# Create an instance of tkinter frame or window
window, frame, DNA_LF, Protein_LF = CREATE_WINDOW_FRAMES()
var = IntVar()
var.set(1)
dna_LF(window, DNA_LF)
DNA = ttk.Radiobutton(frame, text="DNA", value=1, variable=var,
command=lambda: change_to_DN... |
def generate_quiz(quiz_length: int, num_answers: int) -> PitchQuiz:
quiz = []
for index in range(0, quiz_length):
quiz.append(generate_quiz_question(num_answers))
return quiz
def generate_prompt(question: QuizQuestion) -> str:
question_prompt = question[0][0]
frequency = question[0][1]
p... | The code's main task is to generate an interactive quiz with specified question and answer lengths, play audio cues for each question, prompt users for answers, and validate responses until correct answers are provided. It uses command-line arguments for quiz parameters, loops through generated questions, and ensures u... | def main():
quiz_length = int(sys.argv[1])
answer_length = int(sys.argv[2])
questions = generate_quiz(quiz_length, answer_length)
for question in questions:
user_has_chosen_correctly = False
# Present Question and play sound
prompt = generate_prompt(question)
play_sound... |
def print_results():
rez_str = ''
clear_zombies()
row = []
for phone in phones:
row.append([phone, phones[phone]['state'], phones[phone]['device'], phones[phone]['wifi'], phones[phone]['os'],
phones[phone]['phone'], phones[phone]['time'], phones[phone]['notes']])
return r... | The main task of the code is to update the GD values with printed results, conditionally display WiFi devices, verbose messages, and retrieve device names based on specified arguments (airdrop, verb, active) by updating corresponding UI elements and triggering specific functions. | def while_waiting(self):
self.gd.values = print_results()
if args.airdrop:
self.OutputBox.value = print_wifi_devs()
self.OutputBox.display()
if args.verb:
self.VerbOutputBox.value = pop_verb_messages()
self.VerbOutputBox.display()
if args.a... |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | The code updates feed information by sending a PUT request to a constructed URL endpoint using the provided `feed_id` and serialized `meta` data. It processes the response with `_feed_process` and re-raises exceptions if errors occur during the update. | def update_feed_info(self, feed_id, meta):
try:
return self._feed_process(self.put(self._build_feed_url("/{}/feedinfo".format(feed_id)), data=dumps(meta)))
except Exception as e:
raise Exception(e) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | This function updates a specific feed report by sending the provided report data to a constructed URL. It logs the update action, serializes the report, and uses a PUT request to update the feed's report via the `_feed_process` method. | def update_feed_report(self, feed_id, report):
self._log.debug("updating_report={} feed={}".format(dumps(report), feed_id))
return self._feed_process(
self.put(self._build_feed_url("/{}/reports/{}".format(feed_id, report["id"])), data=dumps(report))) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | This method retrieves and processes feed data from a constructed URL, including an option to include public feeds. It formats the URL with the 'include_public' parameter, fetches the data, processes it via _feed_process, and handles exceptions by re-raising them with the original error message. | def get_all_feeds(self, include_public="false"):
try:
return self._feed_process(self.get("{}?include_public={}".format(self._build_feed_url(), include_public)))
except Exception as e:
raise Exception(e) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | The main task of the code is to retrieve and process a feed by its ID. It constructs a URL using `feed_id`, fetches data via `self.get()`, processes it with `_feed_process()`, and returns the result. If an error occurs during this workflow, it re-raises the exception with the original error message. | def get_feed(self, feed_id):
try:
return self._feed_process(self.get(self._build_feed_url("/{}".format(feed_id))))
except Exception as e:
raise Exception(e) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | The main task of the code is to retrieve and process feed information using a given feed_id. It constructs a URL with the feed_id, fetches data via `self.get`, processes it with `_feed_process`, and returns the result. If an error occurs during execution, it raises an exception with the captured error. | def get_feed_info(self, feed_id):
try:
return self._feed_process(self.get(self._build_feed_url("/{}/feedinfo".format(feed_id))))
except Exception as e:
raise Exception(e) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | The main task of the code is to retrieve and process reports for a specific feed by constructing a URL with the provided feed ID, fetching data via an API call, and returning the processed result. It handles exceptions by re-raising them. | def get_feed_reports(self, feed_id):
try:
return self._feed_process(self.get(self._build_feed_url("/{}/reports".format(feed_id))))
except Exception as e:
raise Exception(e) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | The main task of the code is to retrieve a feed report by constructing a URL with given `feed_id` and `report_id`, making a request, processing the response via `_feed_process`, and handling exceptions by re-raising them. | def get_feed_report(self, feed_id, report_id):
try:
return self._feed_process(self.get(self._build_feed_url("/{}/reports/{}".format(feed_id, report_id))))
except Exception as e:
raise Exception(e) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | The main task of the code is to delete a specific feed resource identified by `feed_id` by constructing a URL, invoking a deletion operation, processing the result via `_feed_process`, and re-raising any exceptions encountered during the operation. | def delete_feed(self, feed_id):
try:
return self._feed_process(self.delete(self._build_feed_url("/{}".format(feed_id))))
except Exception as e:
raise Exception(e) |
def _build_live_endpoint(self, endpoint):
return "integrationServices/v3/cblr/session{}".format(endpoint)
def _live_response_process(self, response, msg=""):
self._log.debug("status=trace response={}".format(response))
self._log.debug("status=start code={}".format(response.status_code))
... | The main task of the code is to initiate a live session for a specified device by constructing a URL endpoint, sending a POST request with sensor_id data, and processing the response to handle session establishment or potential errors. | def _open_live_session(self, device_id):
endpoint = self._build_live_endpoint("/{}".format(device_id))
self._log.debug("status=start endpoint={}".format(endpoint))
return self._live_response_process(self.post(endpoint, data=dumps({"sensor_id": device_id})),
... |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | The main task of the code is to create a private feed by sending POST data to a dynamically built URL, processing the response via `_feed_process`, and handling exceptions by re-raising them. It serializes input data, executes a POST request, and returns processed results while ensuring error propagation. | def _create_private_feed(self, data):
try:
return self._feed_process(self.post(self._build_feed_url(), data=dumps(data)))
except Exception as e:
raise Exception(e) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | The main task of the code is to create a public feed by sending a POST request with serialized data to a constructed URL, then processing the response via `_feed_process`. It handles exceptions by re-raising them, ensuring error propagation. | def _create_public_feed(self, data):
try:
return self._feed_process(self.post(self._build_feed_url("/public"), data=dumps(data)))
except Exception as e:
raise Exception(e) |
def _feed_process(self, response):
if "status_code" in response:
self._log.debug("action=got_response status={} text={}".format(response.status_code, response.text.encode('utf-8')))
if not isinstance(response, str):
if response.status_code == 200:
return response.... | This function replaces reports for a specified feed by sending a POST request with the provided reports data to a dynamically constructed URL, then processing the response. It handles exceptions by re-raising them with the original error message. | def replace_feed_reports(self, feed_id, reports):
try:
return self._feed_process(self.post(self._build_feed_url("/{}/reports".format(feed_id)), data=dumps(reports)))
except Exception as e:
raise Exception(e) |
def post(self, endpoint, data={}, **kwargs):
url = self._build_url(endpoint)
self._log.debug("status=start url={}".format(url))
r = None
try:
r = self._session.post(
url,
data=data,
headers=self._current_header,
... | The main task of the code is to retrieve files using a SHA-256 hash by sending a POST request to a specified API endpoint. It validates input parameters, handles JSON responses, checks for errors, and compiles retrieved files with their URLs and summaries. The function returns a list of retrieved file data or raises ex... | def get_file(self, shash=None):
self._last_content = "action=get_file_init hash={}".format(shash)
if shash is None or self.org_key is None:
raise Exception("Hash not passed")
endpoint = "ubs/{}/orgs/{}/file/_download".format(self.api_version, self.org_key)
self._last_content ... |
def _open_live_session(self, device_id):
endpoint = self._build_live_endpoint("/{}".format(device_id))
self._log.debug("status=start endpoint={}".format(endpoint))
return self._live_response_process(self.post(endpoint, data=dumps({"sensor_id": device_id})),
... | This function executes a live response command on a remote device via a session. It opens a session, waits for it to activate, issues the command, monitors its status, handles errors/timeouts, maps responses based on the command type, and closes the session. It ensures proper session management and returns the processe... | def live_response(self, device_id, command, **kwargs):
# Local 'Globals'
self._log.debug("status=start")
# if len(self.api_url) < 1:
if not self.api_url:
raise Exception("No Live Response API provided.")
max_wait_loops = 10
wait_time = 100
map_response... |
def change_data(data):
"""
check data for double generators and delete one, the function also ensures that
every radius is positiv
:param data: data is a np array with generators inside, e.g data = [[1,1,1],[2,
3,3]] where the first 2 entries are the coordinates and the third one is the radius,
... | The main task of the code is to generate a tessellation from input points, plot the resulting structure with cell edges and generating points, and save the tessellation vertices to a CSV file. It processes input data to compute cells using convex hulls, handles edge cases where points fail to form cells, adjusts plot l... | def create_tessellation(data, filename="0", block=False, center=False, setTitle=None):
"""
main function to calculate the vertices of the tessellation, plot the tessellation and write the vertices to a file
:param data: needs the generating points as a pandas data frame, the data should be around (0,0)
... |
def change_data(data):
"""
Delete multiple entry's in the tessellation data and assure that cell labels are integers.
:param data: tessellation data
:return: adjusted data
"""
data = np.unique(data, axis=0)
for i in range(len(data)):
data[i][0], data[i][1] = int(data[i][0]), int(da... | The main task of the code is to generate coordinates for Voronoi tessellation generators, ensuring they lie within their respective cells. It calculates initial generators based on positional relationships between adjacent cells, iteratively assigns new generators using neighboring cell data, adjusts weights to radii v... | def generating_points(x1, y1, w1, data, x2=None, y2=None):
"""
Give the coordinates of the first generator of the first cell and x2 or y2 of the second generator. The coordinates
of the first generator must be in its generating cell, the coordinates of the second generator must be given as
follows:
... |
def check_tessellation(data):
"""
Check if tessellation is not degenerated, returns True if it is degenerated
:param data: The tessellation data
:return: True if data is degenerated, otherwise False
"""
vertices = [[data[x][y], data[x][y + 1]] for x in range(len(data)) for y in [2, 4]]
uni... | The function generates the first four points for a tessellation approximation algorithm, validating tessellation integrity, coordinate placement, and adjacent cell relationships. It initializes generators, checks cell adjacencies, and computes subsequent points based on assigned neighbors, adjusting weights to radii fo... | def generating_first_four_points(x1, y1, w1, data, x2=None, y2=None):
"""
Nearly the same as the function generating_points() but only the first four points are calculated in order to check
if the sample for the approximation algorithm is suitable.
Check generating_points for more details.
:param x... |
def change_data(data):
"""
check data for double edges and delete one
:param data: data is a np array with edges inside, e.g data = [[1,2,0.1,0.2,3,4],[2,
3,0.1,0,4,1]] where the first 2 entries are the labels of the neighbour cells and the other 4 are the coordinates of
the shared edge
:retur... | The function computes generator points for a tessellation by analyzing adjacent cells' shared edges. It checks for degenerate tessellation, constructs adjacency lists, and calculates intersection points of rays derived from neighboring edges, returning these as generators for each cell. | def generating_points(data):
"""
compute the generator points of a given data set
:param data: data is a np array with edges inside, e.g data = [[1,2,0.1,0.2,3,4],[2,
3,0.1,0,4,1]] where the first 2 entries are the labels of the neighbour cells and the other 4 are the coordinates of
the shared edge... |
def change_data(data):
"""
check data for double edges and delete one
:param data: data is a np array with edges inside, e.g data = [[1,2,0.1,0.2,3,4],[2,
3,0.1,0,4,1]] where the first 2 entries are the labels of the neighbour cells and the other 4 are the coordinates of
the shared edge
:retur... | This function approximates Voronoi tessellation generator points from edge data. It processes cell adjacencies, calculates rays between neighboring edges, computes weighted variations, and aggregates them into generator points per cell, handling potential degeneracies and inexact vertices. | def approximated_generating_points(data):
"""
compute the generator points of a given data set where the vertices might not be accurate or it is just assumed to
be a Voronoi tessellation. Therefor it calculates approximative generators.
:param data: data is a np array with edges inside, e.g data = [[1,... |
def change_data(data):
"""
Delete multiple entry's in the tessellation data and assure that cell labels are integers.
:param data: tessellation data
:return: adjusted data
"""
data = np.unique(data, axis=0)
for i in range(len(data)):
data[i][0], data[i][1] = int(data[i][0]), int(da... | The function approximates generating points with minimal maximum radius (>0), ensuring the first four generators lie within their cells. It samples from a multivariate normal distribution (with optional custom mean/covariance), iteratively refining parameters using an elite subset of samples. The process terminates whe... | def approximated_generating_points(data, sampleSize=20, rarityParameter=0.2, mu=None, sigma=None, epsilon=None):
"""
Calculate a set of generating points with a minimal maximum radius greater than 0. At least the first 4 generators
have to be in their generated cells.
If the runtime is too large, the pa... |
def generating_points(data):
"""
compute the generator points of a given data set
:param data: data is a np array with edges inside, e.g data = [[1,2,0.1,0.2,3,4],[2,
3,0.1,0,4,1]] where the first 2 entries are the labels of the neighbour cells and the other 4 are the coordinates of
the shared edge... | The main task of the code is to compute the original generator points of a Voronoi tessellation from given tessellation data and save them to a specified file. It uses either an exact method (if the tessellation is confirmed as Voronoi) or an approximation method (if uncertainty exists). The result is stored in a file,... | def main(data, filename, approximation=False):
"""
The main method of inverting Voronoi tessellations.
:param data: tessellation data as a pandas dataframe
:param filename: the name of the file where the calculated generators shall be saved
:param approximation: True if you want to use the approxim... |
def generating_points(x1, y1, w1, data, x2=None, y2=None):
"""
Give the coordinates of the first generator of the first cell and x2 or y2 of the second generator. The coordinates
of the first generator must be in its generating cell, the coordinates of the second generator must be given as
follows:
... | The main task of the code is to invert Laguerre tessellations by computing generators using either an exact algorithm (`generating_points`) or an approximation algorithm (`approximated_generating_points`), based on the `approximation` parameter. It saves the computed generators to a specified file. The choice of algori... | def main(data, filename, x1=None, y1=None, w1=None, x2=None, y2=None, approximation=False, sampleSize=None,
rarityParameter=None, mu=None, sigma=None, epsilon=None):
"""
The main method of inverting Laguerre tessellations. Uses either the algorithm generating_points() or the algorithm
approximated_... |
def get_key(mod_value,key):
key_matrix =[
[key+20000,key-2700],
[key-21150,key+3066],
]
key_matrix=np.array(key_matrix)
key_matrix=key_matrix%mod_value
return key_matrix
def check_matrix(mod_value,test_matrix):
determinant,i=check_determin... | This code performs audio encryption using matrix operations and RSA. It generates a key matrix, validates its properties, mixes it with audio data, creates a transpose matrix, and encrypts the key via RSA. The process involves mod value adjustments, determinant checks, and returns encrypted data along with cryptographi... | def do_encryption(mod_value,source_audio_int_2D):
print("\t\t\t!!!! ENCRYPTION PROCESS !!!!")
print(f"The mod value is {mod_value}.")
#Getting the key matrix
key=int(input("Please enter the key:"))
key_matrix=get_key(mod_value,key)
temp=key
print(f"The initial key value is {key... |
def decrypt_key(n,key,public_key,encrypt_key,shy_fn):
MI_Key,status=RSA_MI(public_key,shy_fn)
print(f"MI is {MI_Key}.")
if key>n:
print(f"Key size is too large.\n{key} is larger than {n}.")
return
decrypt_key=(encrypt_key**MI_Key)%n
return decrypt_key
def get_key(mod_value,key):
... | The code decrypts an audio signal using matrix inversion and modular arithmetic. It generates a decryption key, validates the key matrix, computes its modular inverse, and applies the inverse to the encrypted audio data through mixing operations. The process adjusts the modulus value if necessary and outputs the decryp... | def do_decryption(n,public_key,encrypt_key,shy_fn,mod_value,source_audio_int_2D,num,transpose_final):
print("\t\t\t!!!! DECRYPTION PROCESS !!!!")
print(f"The mod value is {mod_value}.")
#Getting the key matrix
encrypt_key=int(input("Please enter the key:"))
print(f"\nEncrypted Key is {e... |
def make_encoder(input, name='resnet50', pretrained=True):
if name == 'resnet18':
from classification_models.keras import Classifiers
ResNet18, _ = Classifiers.get('resnet18')
model = ResNet18(
weights='imagenet' if pretrained else None,
input_tensor=input,
... | This code constructs a U-Net model for image segmentation using a pre-trained encoder (e.g., ResNet50). It extracts encoder layers, processes them at different scales, upsamples features, concatenates encoder-decoder paths, and applies convolutions to output a 6-class softmax segmentation map. | def build_unet(size=300, basef=64, maxf=512, encoder='resnet50', pretrained=True):
input = layers.Input((size, size, 3))
encoder_model = make_encoder(input, name=encoder, pretrained=pretrained)
crosses = []
for layer in encoder_model.layers:
# don't end on padding layers
if type(layer... |
def authenticated_scan_policies(username: str):
"""
gets all AWS policies attached to a user, fetched by his/her AWS username, and checks whether the LeanIX CI Policies
were created and authenticates / verifies the credentials, if it fails to query the IAM console.
"""
try:
user_pol... | The main task of the code is to verify user permissions against policies, generate a policy report, and handle authentication errors. It logs in, checks policies, and creates a report. If access is denied or credentials are invalid, it prompts the user to reconfigure settings, re-authenticates, and reruns the check. If... | def run_policy_check(save_runtime: bool):
try:
login_info = login()
if login_info['check']:
user_policies = authenticated_scan_policies(
username=login_info['username'])
policy_checks = verify_permissions(policies=user_policies)
create_policy_report(p... |
def _update_agent_locations(self, step):
self._env_map[0, self._agent_location[0], self._agent_location[1]] = 0
self._agent_location += step
self._env_map[0, self._agent_location[0], self._agent_location[1]] = 1
def _update_object_locations(self):
if self._env_map[1:, self._agent_locatio... | The code defines a `step` method for an agent-environment interaction, updating agent/object positions, calculating rewards based on mental states and object interactions, and determining termination/truncation. It computes rewards from mental state changes, step cost, and object rewards, returning observations, reward... | def step(self, action):
self._goal_selection_step += 1
step = self._all_actions[action]
# reward = 0
self._update_agent_locations(step)
step_length = np.linalg.norm(step)
dt = np.array(1) if step_length < 1.4 else step_length
object_reward = self._env_map[1:,
... |
def extract_arguments_from_scenario(self, scenario):
enumerated_scenarios = self.enumeratea_scenarios(scenario)
self.recur_subset(enumerated_scenarios)
def compute_sum_of_weights_for_each_recovery_behavior(self, show_rule):
sum_of_weights = {}
max_support_for_recovery_behavior = {}
... | The code's main task is to generate a second guess by processing a scenario: extracting arguments, computing weight sums for recovery behaviors (with optional rule display), and returning the recovery behavior with the highest support sum. | def generate_second_guess(self, scenario, show_rule=False):
self.extract_arguments_from_scenario(scenario)
self.compute_sum_of_weights_for_each_recovery_behavior(show_rule)
return self.find_recovery_behavior_with_highest_sum_of_support() |
def enumeratea_scenarios(self,scenario):
enumerated_scenarios = []
for idx in range(len(scenario)):
if scenario[idx][0] != 'Noc':
enumerated_scenarios.append([idx, scenario[idx][0]])
enumerated_scenarios.append([idx, scenario[idx][1]])
else:
... | This code processes a scenario by enumerating its scenarios, recursively generating subsets, and then adding each subset as an argument along with its supporting recovery behavior, using the current best recovery strategy for each subset. | def add_arguments_from_scenario(self, scenario):
enumerated_scenarios = self.enumeratea_scenarios(scenario)
self.recur_subset(enumerated_scenarios)
for subset in self.subsets:
self.add_argument(subset)
self.add_support(subset, self.current_best_recovery_behavior) |
def add_recovery_behavior(self):
if self.current_best_recovery_behavior not in self.recovery_behaviors:
self.recovery_behaviors.append(self.current_best_recovery_behavior)
self.add_bidirectional_attack_between_recovery_behaviors()
def add_argument(self, argument):
if argument not... | The method updates the current best recovery behavior by assigning the provided `best_recovery_behavior`, adds it as an argument, and integrates scenario-specific arguments from the given `scenario` to enhance the recovery strategy. | def update_baf(self, scenario, best_recovery_behavior):
self.current_best_recovery_behavior = best_recovery_behavior
self.add_recovery_behavior()
self.add_argument(best_recovery_behavior)
self.add_arguments_from_scenario(scenario) |
def preprocess(
img: np.ndarray, resolution: list = [192, 192]
) -> Tuple[np.ndarray, np.ndarray]:
"""Preprocesses the image by clipping, cropping and resizing. Clipping at -1024 and 600 HU, cropping to the body
Args:
img (np.ndarray): Image to be preprocessed
resolution (list, optional... | This function performs medical image inference using a neural network model. It converts input images to numpy arrays, handles orientation normalization, preprocesses slices (with HU-specific adjustments), applies the model in batches, and post-processes outputs. The result is a segmented mask, with optional orientatio... | def _inference(
self, image: Union[sitk.Image, np.ndarray], model: torch.nn.Module
) -> np.ndarray:
"""Performs model inference
Args:
image (Union[sitk.Image, np.ndarray]): Input image (volumetric)
model (torch.nn.Module): Model to be applied
Returns:
... |
def plot_pending_overhead(input_files, output_prefix, label, k):
cmap = get_cmap(len(input_files))
for i, file in enumerate(input_files):
df = pd.read_csv(file)
pending_overhead_list = df['pending_overhead'].to_list()
x, y = get_cdf(pending_overhead_list)
plt.plot(x, y, label='%s... | The main task of the code is to process input CSV files to analyze fairness and pending overhead metrics, generating visualizations and average job completion time (JCT) summaries. It uses command-line arguments to specify input files, output file prefix, label name, and a parameter for selecting the last k-th pattern ... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input_files', nargs='+', type=str, help='input file path')
parser.add_argument('--output_prefix', default='result', type=str, help='output file prefix')
parser.add_argument('--label_name', default='label', type=str)
parser.add_arg... |
def is_job_finished(job):
return job['total_executed_time'] >= job['duration']
def finish_job(self, job):
assert self.release_job_resource(job) == True
self.switch_job_status(job, prev="RUNNING", cur="END")
#TODO: the fairness value may be not accurate, add scheduling fairnees to address thi... | This method checks running jobs for termination conditions. It finishes jobs that are completed, releasing their resources, and handles lease expiration by either skipping large GPU jobs or transitioning others to pending status based on time and configuration rules. | def check_terminated_jobs(self, cur_time):
for job in self.running_jobs:
# if running->finished: finish job; release job resource
if is_job_finished(job):
self.finish_job(job)
# if running->expiry: change job status to pending
elif is_job_lease_exp... |
def job_selection(self, user):
pending_jobs = user.pending_jobs.copy()
delay_jobs = self.user_delay_jobs[user].copy()
empty_jobs = list()
# remove starvation jobs in job selection, since such jobs in a seperate queue
for u in self.USERS:
for j in self.user_st... | The code allocates GPU resources to user jobs using a fair or dynamic policy, prioritizing jobs based on quota ratios and U/W metrics. It updates user quotas, checks free GPUs, and attempts job allocation, handling backfilling, preemption, and starve job management to ensure efficient resource distribution while adheri... | def allocate_job_resources_with_user(self, cur_time):
free_gpu = self.CLUSTER.check_free_gpus()
# store temp utilized/weighted
user_utilized = self.user_utilized.copy()
user_weighted = self.user_weighted.copy()
user_U_divide_W = self.user_U_divide_W.copy()
user_job_dict ... |
def on_closing(self, win_closed):
if messagebox.askokcancel("Confirm Close", "Do you want to finish the experiment"):
self.send_lsl_marker(win_closed)
print("Window is closing")
self.serial_port.close()
root.destroy()
def UpdateTab(self, mod):
self.mod_sel... | This code initializes a GUI application for neurostimulation task control, setting up a window with mode (Air/Vib/Car) selection, intensity grids, save/load buttons, timers, and LSL marker integration. It configures task sequences, serial communication, and threading for real-time data handling, enabling user interacti... | def __init__(self, root, serial_port, LSLMarkerStream):
self.root = root
self.root.title("NeuroPain Volunteer")
self.root.geometry("512x400")
self.root.configure(bg="#f0f0f0")
root.protocol("WM_DELETE_WINDOW", lambda: self.on_closing("1997"))
self.win_closed = "1997"
... |
def coor2dd(point):
lat = point[:6]
lon = point[7:14]
lat_dms = (float(lat[:2]) + float(lat[2:4])/60 + float(lat[4:6])/(60*60))
lon_dms = (float(lon[:3]) + float(lon[3:5])/60 + float(lon[5:7])/(60*60))
return lat_dms,lon_dms
def get_arc_polygon(point):
arc_list = get_arc_list_coor(point)
sta... | The main task of the code is to generate a polygon in LAT/LON coordinates from a given volume name by combining direct point lookups and dynamically generated arcs for missing points, ensuring correct orientation via counter-clockwise checks. | def get_polygon(volume_name):
"""
create polygon from volume name in LAT LON
"""
points = fdp_volume[volume_name]['points']
polygon_list = []
for i,point in enumerate(points):
if point in point_json:
p = point_json[point]
coor = coor2dd(p)
polygon_l... |
def get_polygon(volume_name):
"""
create polygon from volume name in LAT LON
"""
points = fdp_volume[volume_name]['points']
polygon_list = []
for i,point in enumerate(points):
if point in point_json:
p = point_json[point]
coor = coor2dd(p)
polygon_l... | The code generates an interactive map plot using Plotly and Mapbox, visualizing a specified geographic volume's polygon area. It calculates the volume's center, zoom level, and formats polygon data for rendering. The map is styled with a dark theme, includes a red-filled polygon layer, and a cyan marker at the center, ... | def create_volume_plot(volume_name):
polygon=get_polygon(volume_name)
center,min_,max_ = find_center_and_max(polygon)
zoom = get_zoom(min_,max_)
poly_plot=[]
for i in polygon:
poly_plot.append([[i][0][1],[i][0][0]])
mapbox_token=open('./mapbox_token.txt').read().strip()
fi... |
def get_polygon(volume_name):
"""
create polygon from volume name in LAT LON
"""
points = fdp_volume[volume_name]['points']
polygon_list = []
for i,point in enumerate(points):
if point in point_json:
p = point_json[point]
coor = coor2dd(p)
polygon_l... | The code generates an interactive map plot of a specified sector using geographic polygons, centers the map on the sector's area, and returns a Plotly figure with Mapbox styling for visualization. | def create_sector_plot(sector_name):
volume_list = sector_json[sector_name]['volume']
polygon_list = []
for volume_name in volume_list:
polygon_list.append(get_polygon(volume_name))
lat,lon = get_latlon(polygon_list)
center,min_,max_ = find_center_sector(lat,lon)
zoom = get_zoom(min_,m... |
def _getReleaseData(self, page: int = 1) -> bool:
# TODO: Consider how to handle a non Github Repo
# TODO: Consider how to handle more than a single binary release, e.g. aws-cli
if "platform" not in self.result or self.result['platform'] == 'github':
if 'license' not in self.result:
... | The main task of the code is to generate release packages in 'deb' and 'rpm' formats based on the specified formats in `self.result`, then clean up by removing the existing package directory if it exists. It coordinates data retrieval, asset handling, and package rendering for software distribution. | def getRelease(self):
self._getReleaseData()
self._getAsset()
if 'deb' in self.result['formats']:
self._renderDebPackage()
if 'rpm' in self.result['formats']:
self._renderRpmPackage()
if os.path.exists(os.path.join(self.package_path)):
shutil.r... |
def is_valid_move(self, index):
if index < 0 or index > 8:
return False
if self.matrix[index] == 'X' or self.matrix[index] == 'O':
return False
return True
def print_matrix(self, matrix):
for i in range(3):
for j in range(3):
print(matr... | The code runs a tic-tac-toe game, alternating turns between two players. It validates moves, updates the game board, checks for a win after each move, and declares a winner or a draw if all turns are exhausted without a win. | def start(self):
while self.turns_taken < 9:
curr_player = self.turns_taken % 2
choice = -1 # -1 is invalid choice
while self.is_valid_move(choice - 1) == False:
self.print_matrix(self.matrix)
print(self.players[curr_player].name + "'s turn: "... |
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... | This function performs multi-time series anomaly detection by validating input data, running statistical tests, scoring anomalies, and determining outliers. It ensures sufficient data points and series count, checks parameter validity, and returns processed results with diagnostics if inputs meet criteria. | 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 multiple statistical outlier detection tests (SD, MAD, IQR, Grubbs, GESD, Dixon, Gaussian mixture) on a dataset, using baseline and normalized data. It updates the DataFrame with test scores, checks data size requirements for each test, and logs diagnostics including test eligibility, results, and normali... | 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... | This function detects univariate statistical anomalies in a dataset using an ensemble of tests (standard deviation, IQR, MAD, Grubbs, Dixon, etc.) with weighted scores. It validates input constraints (minimum data points, sensitivity score range, max anomaly fraction), runs selected tests, scores results, and identifie... | 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 take_input_signal_manually():
global global_ctr
print("Input signal")
# number of elements as input
Lx = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, Lx):
ele = int(input())
x_input.append(ele) # adding the element
x_graph =... | The code allows users to select or input signals (like unit step, impulse, etc.) and their parameters, then performs convolution by combining the chosen input signal and impulse response, finally visualizing the result through a draw_output function. | def starter():
global global_ctr
global_ctr = 0
print("^^^^^^^ ....... Welcome to our app ....... ^^^^^^^\n\n\n")
print("\t 1. Enter the input signal manually")
print("\t 2. Choose one of the known input signals")
input_signal_choice = int(input("\nSelect one of either options: "))
if(... |
def prepare_dataset(self, lines, model_size=128, batch_size=64, test_mode=False):
lines = lines.decode('utf-8')
raw_data = []
for line in lines.split('\n'):
raw_data.append(line.split('\t'))
raw_data.pop()
raw_data_en, raw_data_fr, _ = list(... | The code initializes a transformer model by setting up components like the optimizer, preparing datasets with positional embeddings, extracting batches, and configuring the transformer architecture with parameters from hparams, including model size, attention heads, and layers. | def __init__(self, hparams, raw_dataset):
self.hparams = hparams
self.en_tokenizer = None
self.fr_tokenizer = None
self.encoder = None
self.decoder = None
self.batches = []
self.vocab_size_overhead = 10000
self.optimizer = tf.keras.optimizers.Adam(hparams.... |
def flatten_amr(graph):
# Turns the AMR graph to lAMR, i.e. condences the graph to one line
graph = re.sub(r'\s+', ' ', graph) # Remove change of lines
graph = re.sub('(# ::snt .*?) (\([\w\n]+ /)', '' + r"\2", graph) # Remove sentence
graph = re.sub('(\"[\w\d-]*)[\(|\)]+([\w\d-]*")', r'\1' + r'\2', grap... | The main task of the code is to convert an abstract meaning representation (AMR) graph into a dictionary format. It identifies the main predicate from extracted arguments, processes graph nodes to map arguments to their values, and structures the result with the main predicate as the key and a nested dictionary of argu... | def graph_to_dict(graph):
# Turns the graph into dictionary form, with the argument as key and its constituents as values
argdict = {}
final_dict = {}
graph = flatten_amr(graph)
args = extract_developed_arguments(graph)
main_pred = args[-1][1]
env_graph = envelop_arguments(graph)
nodes =... |
def fhedeck_net_source_name(net, inputs, groups):
if len(net.sources) == 0:
assert net.is_global_input_net()
return f"ct_{inputs[net]}", f"ct_{inputs[net]}_clear"
assert len(net.sources) == 1
gate = net.sources[0].gate
if str(gate.type) == "HAL_GND":
return "0", "0"
if str(... | The code generates C++ code to evaluate logic gate groups using homomorphic encryption, handling both encrypted (ciphertext) and plaintext (cleartext) data. It creates decomposition functions for rotations, processes inversion (INV), full adder (FA), and look-up table (LUT) gates, and asserts consistency between encryp... | def fhedeck_print_groups(inputs, groups, ciphertext=True, cleartext=False):
bootstraps = 0
print(f"{TAB}std::vector<RotationPoly> decomp;")
print(f"{TAB}std::vector<long (*)(long)> fdecomp;")
for i in range(LMAX):
cases = "\n"
for j in range(1 << LMAX):
cases += f"{TAB}{TAB}... |
def setup_ui(self):
# Define a style for ttk elements
style = ttk.Style()
style.theme_use("default")
style.configure("TFrame", background=DARK_MODE_BG)
style.configure("TLabel", background=DARK_MODE_BG, foreground=DARK_MODE_TEXT)
style.configure("TEntry", background="#F... | The code initializes a GUI application using Tkinter, sets up a window titled "Player Query," tracks file positions, manages sorting orders for columns, and starts periodic checks for file changes. It also centers the window and enters the main event loop to handle user interactions. | def __init__(self, conn):
self.conn = conn
with open(filepath, "r") as f:
self.file_position = f.tell()
self.app = tk.Tk()
self.app.title("Player Query")
self.sorting_orders = {} # Dictionary to keep track of sorting order for each column
self.setup_ui()
... |
def get_all_age_zip_combinations_to_process(employees, zip_to_use, tax_year, process_group):
all_ages_in_the_employee_map_for_zips = set()
for employee in employees.values():
if is_employee_record_invalid(employee, zip_to_use):
continue
if process_group == "FT and no status employee... | The code installs required packages, reads employee data from an Excel file, processes age-zip code combinations for tax year data, and uses a browser driver to find LCSP (Lowest Cost Shared Plan) information for each combination. It handles errors by saving progress and quitting the browser, ensuring partial results a... | def run(self):
package_installer = PackageInstaller(["selenium", "webdriver_manager", "requests", "pandas", "openpyxl", "bs4"])
package_installer.install_packages()
employees = ExcelProcessor.get_employee_map_from_file(self.input_file, self.zip_to_use)
try:
Utils.print_line_... |
def load_audio(song_name):
'''
Return the recorded audio and sampling_rate as a Tuple
'''
#length = 60
length = 10
return librosa.load(song_name, sr = 44100, duration = length)
def get_spectrogram(recorded_audio, sampling_rate):
'''
Return the spectrogram corresponding to `recorded_audio... | The main task of the code is to process audio files from given song names by extracting spectrogram features, identifying local peaks, generating fingerprint keys, and populating a fingerprint database and song database with associated SongRecord objects. It converts audio into spectral data, isolates significant peaks... | def fill_database(song_names: List[str], fingerprint_database: Dict[FingerprintKey, SongRecord], song_database: List[SongRecord]):
'''
Fill the database given the fingerprint database, song database,
and a list of song names (file path to songs).
'''
for s in range(len(song_names)):
recorded... |
def get_spectrogram(recorded_audio, sampling_rate):
'''
Return the spectrogram corresponding to `recorded_audio` with `sampling_rate` as the sampling_rate
'''
return mlab.specgram(recorded_audio,
NFFT=4096,
Fs=sampling_rate,
... | The code generates an audio fingerprint by converting the input audio into a spectrogram, identifying significant frequency peaks above a dynamic cutoff, and encoding these peaks into a compact key representation for audio matching or identification tasks. | def compute_fingerprint(recorded_audio, sampling_rate):
spectrogram, freq, times = get_spectrogram(recorded_audio, sampling_rate)
cutoff = get_cutoff(spectrogram)
peaks = local_peaks_mask(spectrogram, cutoff)
fingerprint_keys = construct_fingerprint(peaks)
return fingerprint_keys |
def array_to_key_points(arr):
kp = []
for k in arr:
kp.append(cv2.KeyPoint(k[0][0], k[0][1], k[1], k[2], k[3], k[4], k[5]))
return kp
def knn_match(desc1, desc2, flag=True):
if flag:
print('--------- In knn_match_v2 ---------')
else:
print('--------- In knn_match ---------')
... | The code computes homography between two images using specified matching algorithms (knn, sinkhorn, linear assignment) and evaluates accuracy. It loads image data, extracts keypoints/descriptors, applies intersection or multilevel matching based on flags, calculates homography (H), and returns H along with match scores... | def make_match2(path1, path2, path3, algorithm1, algorithm2, flag):
img1 = cv2.cvtColor(cv2.imread(path1), cv2.COLOR_BGR2RGB)
img2 = cv2.cvtColor(cv2.imread(path2), cv2.COLOR_BGR2RGB)
data = np.load(path3, allow_pickle=True)
# fig = plt.figure(figsize=(10, 10))
# fig.add_subplot(1, 2, 1)
# plt.... |
def remove_newline(self, value):
return re.sub("\n", "", value)
def mist_hex(self, value, length=8, lookup=True):
if lookup:
try:
return self.cache[value]
except:
h = self.hexvalue(value)
self.cache[value] = h
return... | The code converts API calls for a thread into MIST format by processing each call's attributes, generalizing API names, mapping to XML-defined categories, formatting values by type (e.g., hex, string), and logging mismatches. It writes structured instructions to a report, handling edge cases like missing APIs and defau... | def convert_thread(self, pid, tid, api_calls):
"""Convert API calls for a thread to MIST format."""
self.mist_report.write("# process " + str(pid) + " thread " + str(tid) + " #\n")
for api_call in api_calls:
arguments = api_call["arguments"]
category = api_call["category... |
def algorithm_compatibility_check(self):
""" Check selected cryptography algorithms for availability. If ok return true, or else return false """
# Private
if (self.config.private_key_encryption == "") or (self.config.private_key_encryption == None):
self.config.private_key_... | The code's main task is to encrypt web pages, ACL resources, roles, and user data in a structured process. It first encrypts web page content, stores cryptokeys in JSON, and replaces original tags. Next, it encrypts ACL resource secrets, then role secrets referencing ACL keys. User data is encrypted using passwords or ... | def process(self):
""" Analyze and encrypt web pages and their parts or encrypt files
This is quite confusing, what we going to do?
It is not needed to describe Algorithm compatibility check and Resource directory check. What we have to describe is encryption of some files.
... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False):
if args.local_rank not in [-1, 0] and not evaluate:
... | The code defines a script for training and evaluating a model on tasks like SQuAD, using Hugging Face Transformers. It parses arguments for model configuration, data paths, training parameters, and evaluation settings. The script initializes the model, tokenizer, and device, handles distributed training, and performs t... | def main():
parser = argparse.ArgumentParser()
parser.add_argument("--task_name", default=None, type=str, required=True, help="")
## Required parameters
parser.add_argument("--train_file", default="train.jsonl", type=str, required=False,
help="SQuAD json for training. E.g., t... |
def get_building_blocks(i, t, m, verbosity=False):
init, term = inator_smi_lookup(i, t) #converts end groups to mol objects if not right direction for text addition.
if type(m) == list:
#replace any dict keys with corresponding smiles.
deciphered_dict_keys = parse_smiles_dict_keys(m, mono)
... | The main task of the code is to generate a Polymer object from polymer building blocks (repeat unit, end groups) by constructing a SMILES string. It handles cases with/without end groups, random repeat unit combinations, and test mode for visualization. The function returns either the Polymer object or a test SMILES st... | def createPolymerObj(i, n, r, t, verbosity=False, test=False, random=False):
"""
given the components of the polymer, like end groups, n and the repeat unit --> Polymer object
init and term may or may not be mol
i and t are both str.
"""
init, term, repeat_unit, m_per_n = get_building... |
def getStaticSettings():
"""
Reads the settings file if it exists in CWD. Otherwise uses the default settings.
"""
expected_settings_path = "HXSettings.json"
if os.path.exists(expected_settings_path):
from hydrophobicity_explorer.settings import readJson
print(f"NOTICE: found {expec... | The main task of the code is to generate polymer structures from user inputs (CLI arguments or files), merge SMILES dictionaries, perform calculations, and export results. It handles polymer creation, visualization, data analysis, and file I/O, supporting both random and sequence-based polymer generation, with options ... | def main(**kwargs):
default_dict = getStaticSettings()
vardict = getArgs()
#merge user-created smiles with built-in dicts and make accessible to all funcs
global ini, mono
ini, mono = checkAndMergeSMILESDicts(init_dict, monomer_dict)
for key in kwargs:
vardict[key] = kwargs[key] #... |
def display_board():
print(board[0] + ' | ' + board[1] + ' | ' + board[2])
print(board[3] + ' | ' + board[4] + ' | ' + board[5])
print(board[6] + ' | ' + board[7] + ' | ' + board[8])
def handle_turn(player):
global last_player
valid = False
print(player + '\'s' + ' turn')
p... | The code defines a tic-tac-toe game loop that displays the board, alternates player turns, checks for win/draw conditions, and declares the result. It runs until the game ends, switching players and handling moves until a winner is determined or the game ends in a draw. | def tic_tac_toe():
# Display Initial Board
display_board()
while game_not_over:
global player
handle_turn(player)
check_game_over()
change_player()
if winner == PLAYER_1 or winner == PLAYER_2:
print('Game won by ' + winner + '.')
elif winne... |
def update_player_dict(self):
player_dict = { player.name: {'color':player.color} for player in self.players.values() }
msg = { 'type':'update_player_dict',
'player_dict': player_dict }
return self.broadcast( pickle.dumps(msg) )
def player_disconnect(self, player_name):
... | This code handles client connections by assigning unique player names, initializing player objects with random colors, and managing message processing until disconnection. It ensures name uniqueness, updates player data, and processes incoming messages to maintain game state. | def client_handler(self, conn, addr):
"Handles connection with each client player."
# get the player name
has_name = False
while not has_name:
player_name = self.recvMsg(conn)
if player_name not in self.players.keys():
has_name = True
... |
def IsValidWidgetId(widgetId):
if len(widgetId) != 36:
return False
# ensure the positions of the dashes are correct
if widgetId[8] != "-" or widgetId[13] != "-" or widgetId[18] != "-" or widgetId[23] != "-":
return False
# check that all other characters are hexadecimal
hexCharacter... | The function processes widget-related requests by validating the widget ID and executing corresponding actions (create, update, delete) using the specified storage strategy and destination. It logs warnings for unknown request types. | def ProcessRequest(request, destination, storageStrategy):
widgetId = request["widgetId"]
if IsValidWidgetId(widgetId):
requestType = request["type"].lower()
if requestType == "create":
CreateOrUpdateWidget(request, destination, storageStrategy, operation="created")
elif requ... |
def RetrieveRequestFromS3(bucketSource):
try:
# the request data's key is numeric with the same number of digits each time; thus, grabbing the first element should be the smallest key
response = S3_CLIENT.list_objects_v2(Bucket=bucketSource, MaxKeys=1)
if 'Contents' in response:
... | The main task of the code is to continuously retrieve requests from either an S3 bucket or an SQS queue, process them using a specified storage strategy, and then delete the processed requests from their source. It handles errors during processing, logs them, and maintains a loop with short delays when no requests are ... | def main(bucketSource, destination, storageStrategy, queueURL):
while True:
if bucketSource and not queueURL:
request, key = RetrieveRequestFromS3(bucketSource)
if request:
try:
ProcessRequest(request, destination, storageStrategy)
... |
def addDoctorWidgetsSetup(self):
'''This function initializes all variables that will later need to be accessed in the Add Doctor Tab'''
self.firstNameInputAddDoctorTab = self.findChild(QLineEdit, 'firstNameInputAddDoctorTab')
self.lastNameInputAddDoctorTab = self.findChild(QLineEdit, '... | The code initializes a main window by loading a UI file ('DMShome.ui') and setting up widgets for adding/modifying doctor and patient data, preparing the GUI for healthcare management tasks. | def __init__(self):
'''Initializer for the main window'''
super().__init__()
uic.loadUi('DMShome.ui', self)
self.addDoctorWidgetsSetup()
self.modifyDoctorWidgetsSetup()
self.addPatientWidgetsSetup()
self.modifyPatientWidgetsSetup() |
def compareO():
lowest = 999999
lowestIndex = 0
# list of all height values for L rot1
Orot1 = compareO1()
i = 0
while i <= 8:
if Orot1[i] < lowest: # change <= or <
lowest = Orot1[i]
lowestIndex = i
i = i + 1
distribution[O1] = distribution[O1] + 1
... | The code continuously monitors a Tetris game screen by capturing pixel data to detect the next falling piece (e.g., O, L, J, I, T, S, Z). It triggers corresponding comparison functions to analyze the piece's position, updates game state variables like distribution and column height, checks for line clears, and loops ne... | def main():
repeat = 0
keyPress.waitStart()
while repeat < 99999999:
1
nextPiece = (0, 0, 0)
im = quickGrab.screenGrab()
nextPiece = im.getpixel(initPix)
time.sleep(0.01)
if(nextPiece == Oc):
print('Oc')
compareO()
if(nextPiece ... |
def make_private_key(self):
return self.docker_run(['wg', 'genkey'])
def make_public_key(self, private_key):
return self.docker_run(['sh', '-c', f"echo '{private_key}' | wg pubkey"])
def make_preshared_key(self):
return self.docker_run(['wg', 'genkey']) | The code generates a private key, derives a corresponding public key from it, creates a preshared key, and returns all three for cryptographic operations. | def make_keys(self):
private = self.make_private_key()
public = self.make_public_key(private)
psk = self.make_preshared_key()
return private, public, psk |
def checkFlag(self,flag):
if flag not in self.asFlags:
self.asLabel[flag] = len(self.asFlags)
self.asFlags.append(flag)
def labelStr(self,ls):
return "%{}%".format(ls)
def doCont(self,cont):
if not cont:
self.cmdGoto(self.prompt) | This code appends an "IF F(flag) GOTO next" instruction to a list of assembly-like lines, checking a flag's validity first. It uses label strings for branching logic and conditionally continues processing based on the 'cont' parameter. | def cmdIfSetGoto(self,flag,next=prompt,cont=True):
self.checkFlag(flag)
self.asLines.append('IF F({}) GOTO {}'.format(self.labelStr(flag),self.labelStr(next)))
self.doCont(cont) |
def checkFlag(self,flag):
if flag not in self.asFlags:
self.asLabel[flag] = len(self.asFlags)
self.asFlags.append(flag)
def labelStr(self,ls):
return "%{}%".format(ls)
def doCont(self,cont):
if not cont:
self.cmdGoto(self.prompt) | This function generates an 'IF' conditional instruction that checks if a specified flag equals a given value, and if true, jumps to a labeled line. It appends this logic to a code list, validates the flag, and manages execution flow continuation via the 'doCont' method. | def cmdIfValGoto(self,flag,val,next=prompt,cont=True):
self.checkFlag(flag)
self.asLines.append('IF F({})={} GOTO {}'.format(self.labelStr(flag),val,self.labelStr(next)))
self.doCont(cont) |
def checkFlag(self,flag):
if flag not in self.asFlags:
self.asLabel[flag] = len(self.asFlags)
self.asFlags.append(flag)
def labelStr(self,ls):
return "%{}%".format(ls)
def doCont(self,cont):
if not cont:
self.cmdGoto(self.prompt) | The function `cmdSetVal` validates a flag, appends a formatted command line to a list, and triggers a continuation action. It checks the flag's validity, records a line like 'F(flag)=value', and executes a continuation based on the `cont` parameter. | def cmdSetVal(self,flag,val=1,cont=True):
self.checkFlag(flag)
self.asLines.append('F({})={}'.format(self.labelStr(flag),val))
self.doCont(cont) |
def checkFlag(self,flag):
if flag not in self.asFlags:
self.asLabel[flag] = len(self.asFlags)
self.asFlags.append(flag)
def labelStr(self,ls):
return "%{}%".format(ls)
def doCont(self,cont):
if not cont:
self.cmdGoto(self.prompt) | This method validates three flags, constructs a mathematical expression string using the flags and an operator, appends it to a list, and triggers a continuation process. It formats the expression as "F(flag1) = F(flag2) [operator] F(flag3)" using label strings, then calls doCont() with the cont parameter to handle exe... | def cmdExp(self,flag1,flag2,exp,flag3,cont=True):
self.checkFlag(flag1)
self.checkFlag(flag2)
self.checkFlag(flag3)
self.asLines.append('F({})=F({}) {} F({})'.format(self.labelStr(flag1),self.labelStr(flag2),exp,self.labelStr(flag3)))
self.doCont(cont) |
def checkFlag(self,flag):
if flag not in self.asFlags:
self.asLabel[flag] = len(self.asFlags)
self.asFlags.append(flag)
def labelStr(self,ls):
return "%{}%".format(ls)
def wrapPrint(self,line):
if (line==""):
return('?')
else:
wrapper = textwrap.TextWrapper(wi... | The main task of the code is to generate conditional assembly instructions based on a flag value. It appends two IF statements to `self.asLines`: one executing `trueLine` if the flag is true, and another executing `falseLine` if the flag is zero. The `doCont(cont)` method is then called to handle continuation logic, li... | def cmdAltPrint(self,flag,trueLine,falseLine,cont=True):
self.checkFlag(flag)
self.asLines.append('IF F({}) THEN {}'.format(self.labelStr(flag),self.wrapPrint(trueLine)))
self.asLines.append('IF F({})=0 THEN {}'.format(self.labelStr(flag),self.wrapPrint(falseLine)))
self.doCont(cont) |
def label(self,ls):
if (ls != ''):
if ls in self.asLabel:
print("REM * Warning: label {} redefined".format(ls))
self.asLabel[ls] = self.lineNumber(len(self.asLines))
def cmdInsert(self,line,cont=True):
self.asLines.append(line)
self.doCont(cont)
def labelStr(self,ls):
... | The function parses a hierarchical tree structure, generating conditional goto statements for navigation. It processes each key in the tree, handling wildcards ("*") and nested dictionaries recursively. For synonyms, it inserts conditional checks, while non-dictionary values trigger direct jumps. The function labels no... | def parseTree(self,tree,prefix,level=0):
self.label(prefix)
id=0
final = self.badParse
#breadth first
for key in tree.keys():
plabel = prefix + "." + str(id)
id = id +1
if (key == "*"):
final = tree[key]["!"]
elif (type(tree[key]) is dict):
... |
def cmdInsert(self,line,cont=True):
self.asLines.append(line)
self.doCont(cont)
def labelStr(self,ls):
return "%{}%".format(ls)
def cmdGoto(self,next=prompt):
self.asLines.append(self.gotoStr(next))
def label(self,ls):
if (ls != ''):
if ls in self.asLabel:
print("REM *... | This code generates BASIC-like pseudocode for a simple command parser, handling input scanning, tokenization, and state management. It initializes variables, processes user input by splitting commands into tokens, and sets up error handling for unrecognized commands. The parser uses labels and GOSUB calls to manage flo... | def boilerPlate(self):
# Top of program
self.cmdInsert('TEXT:NORMAL:? CHR$(4);"PR#3"')
self.cmdInsert('DIM W$({}): DIM F({})'.format(self.maxWords,self.labelStr(self.flagCount)))
#self.cmdRem(['Flags',self.labelStr(self.flagList)])
self.cmdGoto(self.start)
# Scanner
self.labe... |
def label(self,ls):
if (ls != ''):
if ls in self.asLabel:
print("REM * Warning: label {} redefined".format(ls))
self.asLabel[ls] = self.lineNumber(len(self.asLines))
def parseTree(self,tree,prefix,level=0):
self.label(prefix)
id=0
final = self.badParse
#breadt... | The code's main task is to generate formatted output by setting labels for flags, constructing a parse tree, and printing processed program lines with line numbers. It updates label data, generates parsing structures, and outputs each line after variable replacement, ensuring structured and numbered display of the proc... | def generate(self):
# Set final values
self.asLabel[self.flagCount] = max(0,len(self.asFlags)-1)
self.asLabel[self.flagList] = ', '.join(self.asFlags)
# Generate parser
self.label(self.parser)
self.parseTree(self.actionTree,"parse")
# Dump program
lineNum = 0;
fmt... |
def base_builder(client, root_id, voxel_resolution, contrast_lookup={}):
black = contrast_lookup.get(client.datastack_name, dict()).get("black", 0)
white = contrast_lookup.get(client.datastack_name, dict()).get("white", 1)
img = sb.ImageLayerConfig(
client.info.image_source(), contrast_controls=True... | The function constructs coverage paths for a skeleton structure by combining base layers, optional selection point data, and sampled endpoints. It generates path layers using specified spacing and interpolation methods, returning the resulting data and structure layers for further processing or visualization. | def construct_cover_paths(
l2_sk,
n_choice,
spacing,
root_id,
ep_segment_thresh,
client,
target_length=None,
voxel_resolution=[1, 1, 1],
interp_method="linear",
selection_point=None,
downstream=True,
contrast_lookup={},
):
sbs = []
dfs = []
sb_base, df_base =... |
def to_str( head ):
"""
to_str: FrozenNode -> str
Convert a sequence of nodes to a string of the nodes' values
surrounded by brackets and the individual values separated by commas.
It is a recursive solution.
:param head: The first node in the list to be converted
:return: The entire sequenc... | The code tests operations on a linked list (FrozenNode), including creating a list, inserting values at specific indices, appending elements, removing by value, and emptying the list. It demonstrates insertion, modification, and traversal of a custom linked list structure with functions like insert_before_index, append... | def test():
print( "Create list [5,10,15]." )
lst = FrozenNode( 5, FrozenNode( 10, FrozenNode( 15, None ) ) )
print( to_str( lst ) )
print( "Insert 1's everywhere in the list by index." )
lst = insert_before_index( lst, 1, 3 )
for i in range( 2, -1, -1 ):
lst = insert_before_index( lst,... |
def draw_bowtie0(size):
'''
Draws nothing
'''
pass
def draw_bowtie1(size):
'''
Draws one bowite
Preconditions: turtle facing East
Postconditions: turtle facing East in the starting location
'''
# Draws the bowtie
turtle.left(30)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(... | The main task of the code is to generate and display "bowtie" fractals of increasing depth using Python's turtle graphics. It initializes the canvas, sets colors and speed, then sequentially draws fractals from depth 0 to 5, prompting user input to progress. Finally, it allows user-specified depth for a custom fractal,... | def main():
'''
Calls the bowtie functions in order
'''
# Sets the canvas size
turtle.setup(720,720)
# Sets the pen color and fill color
turtle.color("cyan", "pink")
# Makes the pen really fast
turtle.speed(0)
# Makes the 0th depth fractal
draw_bowtie0(turtle.window_width()/6)
# Makes the 1th depth fr... |
def inisialization():
try:
f = open('contact_save.txt', 'r')
read_result = f.read()
f.close()
return json.loads(read_result)
except IOError:
f = open('contact_save.txt', 'w+')
print("File tidak ditemukan! Mencoba membuat file baru :)")
f.close()
re... | The code implements a phonebook application with a menu-driven interface, allowing users to view, add, edit, delete, search contacts, and save changes. It maintains a contact dictionary, processes user inputs (1-6) for different operations, and persists updates after each action. The loop continues until the user selec... | def phonebook():
dict_contact = inisialization()
while True:
welcome()
user_input = input("Silahkan Input Pilihan yang Diinginkan: ")
if user_input == "1":
if not dict_contact:
print("Kontak kosong tambah kontak dulu masbro!")
else:
... |
def load_all_dicts():
full_df_dict = {}
senttype_dfs_dict = {}
for model in all_models:
full_df, senttype_dfs = load_and_mean_diffs(model)
full_df_dict[model] = full_df
senttype_dfs_dict[model] = senttype_dfs
return full_df_dict, senttype_dfs_dict
def get_nouns_list(full_df_dic... | The code processes and combines noun-related data from multiple models into a unified DataFrame, aligning them by 'Noun' columns. It renames model-specific columns, joins all dataframes, filters rows with non-zero values, and returns the cleaned, combined dataset for correlation analysis. | def run_correlation_pipeline():
full_df_dict, senttype_dfs_dict = load_all_dicts()
total_nouns_list = get_nouns_list(full_df_dict)
full_df_dict = rename_df_dicts(full_df_dict)
print(len(total_nouns_list))
df = pd.DataFrame()
df['Noun'] = total_nouns_list
for model in full_df_dict:
... |
def find_stand(image :np.ndarray):
stand_mask = isolate_stand(image)
bounds = get_stand_bounds(stand_mask)
return bounds
def isolate_verticals(image :np.ndarray) -> np.ndarray:
lines = skimage.filters.scharr_v(image)
mags = abs(lines)
iso = skimage.filters.threshold_isodata(mags)
mask = mags... | The function `find_tube_bounds` identifies the left and right boundaries of a tube in an image. It uses vertical analysis and existing functions to determine the bounds, adjusting for the position of a detected "stand." If the stand is on the left, it focuses on the right part of the image; if on the right, it focuses ... | def find_tube_bounds(image :np.ndarray):
stand_bounds = find_stand(image)
middle = image.shape[1] // 2
vert_mask = isolate_verticals(image)
col_totals = vert_mask.sum(axis=0)
if stand_bounds is None:
return get_bounds_old(image)
elif is_left(stand_bounds, middle):
first_col = sta... |
def _process_json_response(self, r, action_result):
# Try a json parse
try:
resp_json = r.json()
except Exception:
# If I can't parse the json
self.save_progress("Failed to parse json naturally")
try:
resp_json = json.loads(self._h... | The function processes an HTTP response by checking its Content-Type. It logs debug data, handles JSON or HTML responses via specific methods, and manages empty responses. If none apply, it returns an error with the status code and response text, ensuring compatibility with different Python versions. | def _process_response(self, r, action_result):
# store the r_text in debug data, it will get dumped in the logs if the action fails
if hasattr(action_result, 'add_debug_data'):
action_result.add_debug_data({'r_status_code': r.status_code})
action_result.add_debug_data({'r_text':... |
def _handle_py_ver_compat_for_input_str(self, input_str):
"""
This method returns the encoded|original string based on the Python version.
:param input_str: Input string to be processed
:return: input_str (Processed input string based on following logic 'input_str - Python 3; encoded inp... | This code unblocks a file hash by removing it from specified or all blocklist packages via API. It checks if a blocklist ID is provided, constructs the appropriate request URL and payload, executes a POST request, and updates the action result with the response. The function handles both scenarios—removing from a speci... | def _handle_unblock_hash(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Optional values use get parameter
blocklistid = param.get('blocklistid', '')
hash_param = self._handle_py_ver_compat_for_input_str(param['hash'])
actio... |
def _handle_py_ver_compat_for_input_str(self, input_str):
"""
This method returns the encoded|original string based on the Python version.
:param input_str: Input string to be processed
:return: input_str (Processed input string based on following logic 'input_str - Python 3; encoded inp... | This function removes a specified file hash from application capture packages. It checks if an application ID is provided, constructs the appropriate API endpoint, and sends a POST request to either remove the hash from all packages or a specific application. It handles the response, updates the action result with the ... | def _handle_disallow_hash(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Optional values use get parameter
applicationid = param.get('applicationid', '')
hash_param = self._handle_py_ver_compat_for_input_str(param['hash'])
... |
def _handle_py_ver_compat_for_input_str(self, input_str):
"""
This method returns the encoded|original string based on the Python version.
:param input_str: Input string to be processed
:return: input_str (Processed input string based on following logic 'input_str - Python 3; encoded inp... | The main task of the code is to add a file hash to a specified blocklist via an API call. It extracts the hash from the input parameter, constructs a JSON payload, sends a POST request to the blocklist endpoint, and handles the response by updating the action result with success/failure status and relevant data. | def _handle_block_hash(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
# Empty arrays
url_req = []
hash_param = self._handle_py_ver_compat_for_input_str(param[... |
def _handle_py_ver_compat_for_input_str(self, input_str):
"""
This method returns the encoded|original string based on the Python version.
:param input_str: Input string to be processed
:return: input_str (Processed input string based on following logic 'input_str - Python 3; encoded inp... | This code handles adding a file hash to an Airlock repository and linking it to an application capture. It processes input parameters, sends two REST API requests to populate the hash in the repository and associate it with an application, then returns success or error status based on API responses. | def _handle_allow_hash(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
# Empty arrays
url_req = []
hash_param = self._handle_py_ver_compat_for_input_str(param[... |
def _validate_integer(self, action_result, parameter, key):
if parameter is not None:
try:
if not float(parameter).is_integer():
return action_result.set_status(phantom.APP_ERROR, ERR_VALID_INT_MSG.format(key)), None
parameter = int(parameter)
... | The code handles listing endpoints by extracting and validating parameters, constructing a request, making a REST API call to retrieve endpoint data, and returning results with appropriate status or error messages. | def _handle_list_endpoints(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
# Optional values should use the .get() function
ip = param.get('ip', '')
hostname = ... |
def __map_ATTCK_IDs_as_tags(self, case, techniques):
# Collect ATT&CK techniques and tag appropriately
for tech_id, _ in self.__get_ATTCK_IDs(techniques):
tags = [t for t in Tag.filter() if tech_id in t.name]
for tag in tags:
ref = Tagged(source=case, target=tag).... | This function maps intrusion set data to QuoLab cases by creating adversary cases with names, descriptions, and aliases, tagging them with ATT&CK techniques, processing external references to organize reports, and linking malware software. It iterates through each intrusion set, constructs case objects, and associates ... | def map_to_quolab(self):
for name in self.__intrusion_set:
print('[+] Mapping Intrusion Set \"%s\" to QuoLab' % (name))
# Create an adversary case with as name the group value
case_name = name
aliases = self.__intrusion_set[name]['aliases']
aliases.rem... |
def collect_transformer_weights(model):
"""Ad hoc function for retrieving layer weights from a Transformer object"""
ws = {}
encoder = model.encoder
decoder = model.decoder
ws["encoder/pos_embedding/embedding"] = encoder.pos_embedding.embedding.get_weights()
for i, layer in enumerate(encoder.en... | This function quantizes the transformer weights of a model, synchronizes the floating-point weights with the quantized values, and stores the quantized weights for optimization or deployment. It first collects the weights, applies quantization, aligns the original weights with the quantized counterparts, and saves the ... | def _quantize_and_sync_model(self):
ws = collect_transformer_weights(self.model)
qs = quantize_transformer_weights(ws)
sync_fp_weights_with_quantized_values(self.model, qs)
self.quantized_weights = qs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.