dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def excelfile_paths():
# Specify the folder path containing the OOS spreadsheets and the contact info
global OOS_file_input
global contact_file_input
OOS_file_input = input("\nInsert the file path for the 'OOS results folder': ")
contact_file_input = input("Insert a file path for the 'Contact detail... | The main task of the code is to initialize and execute an application by retrieving file paths, processing spreadsheet data through iterative checks, and passing validated results to a user interface for display. It sequentially calls functions to handle file paths, iterate over spreadsheet data, validate criteria, and... | def run_program():
""" This starts the application by:
1. Obtaining the file paths of the OOS result folder and the Contact details spreadsheet, then storing them in variables
2. Passing the output of 'spreadsheet_iterator()' into 'criteria_check()'
3. Passing the output of 'criteria check' into the 'us... |
def consume_till_next(opcode, conn):
expected_bytes = constant_to_bytes(opcode)
(fst, snd) = (expected_bytes[:1], expected_bytes[1:])
skip = bytearray()
done = False
try:
while not done:
rfst = conn.recv(1)
if rfst != fst:
skip += rfst
... | The function `recv_chunk` receives a data chunk from a connection, verifies its integrity by comparing a computed hash with an expected hash, and retries up to `num_retries` times if there's a mismatch. It skips stream data until the next chunk marker, reads the chunk's size, data, and hash, then checks for hash consis... | def recv_chunk(conn, num_retries):
tries_left = num_retries
while tries_left > 0:
try:
# Assume that the previous send failed, and skip over as much of
# the stream as is required.
consume_till_next(Constant.BEG_CHUNK, conn)
match_next(Constant.BEG_SIZE, ... |
def consume_till_next(opcode, conn):
expected_bytes = constant_to_bytes(opcode)
(fst, snd) = (expected_bytes[:1], expected_bytes[1:])
skip = bytearray()
done = False
try:
while not done:
rfst = conn.recv(1)
if rfst != fst:
skip += rfst
... | The function `recv_string` receives a string message from a connection by reading a specified number of data chunks, ensuring correct message structure with start/end markers and message type validation. It accumulates received data into a byte array, handles retries if configured, and returns the concatenated bytes of... | def recv_string(conn, num_retries=settings.MAX_RETRIES):
ba = bytearray()
try:
consume_till_next(Constant.BEG_TX, conn)
match_next(Constant.MSG_TYPE_STRING, conn)
match_next(Constant.BEG_COUNT, conn)
num_chunks = recv_uint(conn)
match_next(Constant.END_COUNT, conn)
... |
def consume_till_next(opcode, conn):
expected_bytes = constant_to_bytes(opcode)
(fst, snd) = (expected_bytes[:1], expected_bytes[1:])
skip = bytearray()
done = False
try:
while not done:
rfst = conn.recv(1)
if rfst != fst:
skip += rfst
... | The function `recv_file` receives a file over a network connection by parsing structured data packets. It reads the file name and size, then writes received data chunks to a local file. The process involves matching specific message markers (e.g., `BEG_TX`, `END_TX`), handling retries, and ensuring data integrity by se... | def recv_file(conn, num_retries=settings.MAX_RETRIES):
try:
consume_till_next(Constant.BEG_TX, conn)
match_next(Constant.MSG_TYPE_FILE, conn)
match_next(Constant.BEG_SIZE, conn)
fname_size = recv_uint(conn)
logger.debug("File name is {} bytes long".format(fname_size))
... |
def send_constant(cst, conn):
conn.sendall(constant_to_bytes(cst))
def uint_to_bytes(num):
return struct.pack("!I", num)
def send_chunk(chunk, conn, num_retries=settings.MAX_RETRIES, ab=(0, 0)):
tries_left = num_retries
while tries_left > 0:
conn.sendall(chunk)
if recv_inforeq(conn) != C... | The function sends a string over a network connection in chunks, marking the transaction with constants. It transmits the string's type, splits it into chunks, sends the chunk count, and iterates through each chunk to transmit them with retries. Each chunk is encoded, hashed, and sent with progress tracking, concluding... | def send_string(s, conn, num_retries=settings.MAX_RETRIES):
lst = utils.chunks_of(s, settings.CHUNK_SIZE)
# Mark the beginning of the transaction
send_constant(Constant.BEG_TX, conn)
send_constant(Constant.MSG_TYPE_STRING, conn)
send_constant(Constant.BEG_COUNT, conn)
conn.send(uint_to_bytes(le... |
def send_constant(cst, conn):
conn.sendall(constant_to_bytes(cst))
def uint_to_bytes(num):
return struct.pack("!I", num)
def send_chunk(chunk, conn, num_retries=settings.MAX_RETRIES, ab=(0, 0)):
tries_left = num_retries
while tries_left > 0:
conn.sendall(chunk)
if recv_inforeq(conn) != C... | This code sends a file over a network connection by transmitting its metadata (size, name, chunk count) followed by data chunks, using a custom protocol with constants and retry logic to ensure reliable transmission. | def send_file(filepath, conn, num_retries=settings.MAX_RETRIES):
flen = getsize(filepath)
num_chunks = flen // settings.FILE_CHUNK_SIZE
num_done = 0
fname = basename(filepath)
# Mark the beginning of the transaction
send_constant(Constant.BEG_TX, conn)
send_constant(Constant.MSG_TYPE_FILE, ... |
def count_tokens_in_file(file_path):
"""Count the number of tokens in a file using nltk."""
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
return count_tokens_in_text(text)
def count_tokens_in_text(text):
"""Count the number of tokens in a text using nltk."""
tokens ... | The main task of the code is to process text files from an OCR folder by truncating content to fit token limits, invoking GPT-4 for processing, saving results as JSON in an output folder, and logging errors for unprocessed files. It ensures no duplicate processing and handles token constraints to avoid API limits. | def main():
input_folder = './ocrs'
output_folder = './gpt_4_outputs'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
error_files = []
for filename in os.listdir(input_folder):
# time.sleep(5)
if filename.endswith('.txt'):
# Check if the file wa... |
def clean_text(text):
# remove unncessary trailing white spaces and remove
# paranthesis. eg "... (1985)" -> "... 1985"
res_list = []
token_list = text.strip().split()
for token in token_list:
res_list.append(clean_one_token(token))
return ' '.join(res_list).strip()
def replace_reference... | This function processes a reference sentence by replacing each slot key (from ordered_cell_dict) with a placeholder containing the slot key and its position, then maps the modified text to pure content. It cleans input text, iterates through slot keys, replaces matching parts in the reference with "__key__position__" f... | def process_one_instance(tokenized_reference, ordered_cell_dict):
res_text = clean_text(tokenized_reference) # remove trailing white spaces & parenthesis in sentence
for idx in range(len(ordered_cell_dict)): # loop over all slot keys (headers)
item = ordered_cell_dict[idx] # item -> {"slot_key": '__x__'... |
def checkPinsAndChecks(self):
pins = []
checks = []
inCheck = False
if self.whiteToMove:
enemyColor = "black"
allyColor = "white"
startRow = self.whiteKingLocation[0]
startCol = self.whiteKingLocation[1]
else:
enemyColor... | This method generates valid chess moves by checking if the current player is in check, filtering possible moves to block or capture threats, handling multiple checks with a dummy king, and determining checkmate/stalemate. It uses board state data to ensure moves avoid checks and enforces chess rules for king safety and... | def getValidMoves(self):
moves = []
self.inCheck, self.pins, self.checks = self.checkPinsAndChecks()
if self.whiteToMove:
kingRow = self.whiteKingLocation[0]
kingCol = self.whiteKingLocation[1]
else:
kingRow = self.blackKingLocation[0]
kin... |
def get_last_state() -> str:
try:
with open(state_file, "r") as f:
return f.read().strip()
except OSError:
return STATE_UNKNOWN
def is_usb_connected():
try:
storage.remount("/", readonly=False) # attempt to mount readwrite
storage.remount("/",... | This code initializes and runs an asynchronous loop to control blinking animations, managing state transitions (active/sleep) based on USB connection status. It schedules tasks for frame drawing, power updates, animation changes, and a timed halt after `run_for` minutes, starting from the current system time. | def run(self, run_for=1):
print(fancy_title)
print(f"last state: {self.get_last_state()}")
# someone has triggered the button (probably) which we'll interpret as a "stop blinking" command
if self.get_last_state() == STATE_ACTIVE:
if not is_usb_connected():
s... |
def is_usb_connected():
try:
storage.remount("/", readonly=False) # attempt to mount readwrite
storage.remount("/", readonly=True) # attempt to mount readonly
except RuntimeError:
return True
return False
def init_state_file(self):
try:
os.stat(state_file)
... | This code initializes an LED animation system by setting up hardware connections, registering LEDs with specific pins, and defining multiple animation sequences. It configures voltage monitoring, initializes animation effects like blinking, fading, and glitches, and organizes them into modes for display. The main task ... | def __init__(self, frame_rate: int = 25):
if not is_usb_connected():
self.init_state_file()
self.vbat_voltage = AnalogIn(board.VOLTAGE_MONITOR)
self.start = 0
self.frame_rate = frame_rate
self.leds = [] # type: List[Led]
self.led_light_green = self.registe... |
def randomly_place_all_ships():
"""
For this function, import the random library. Then append a ship to the list fleet, starting from the
battleship (one ship of 4 sq), then cruisers (two ships of 3 sq), destroyers (three ships of 2sq) and lastly
submarines (four ships of 1 sq). row, column and directio... | The main task of the code is to simulate a battleship game where the user inputs coordinates to shoot at a fleet of randomly placed ships. The program tracks successful hits, checks if ships are sunk, validates input, and ends the game when all ships are sunk, displaying the total number of shots taken. | def main():
current_fleet = randomly_place_all_ships()
game_over = False
shots = 0
hits = [] # a list to store all successful hits
while not game_over:
try:
loc_str = input('Enter row and column to shoot (separated by space) or enter "quit" to end game: ')
if loc_s... |
def select_videos(self, input_type):
""" INPUT input_type = 'directory' or multiple 'files',
GET all videos shortnames,
SAVE directory name to lastdir.txt,
SAVE infos of valid videos to list_videos.json,
GET infos in self.list_videos and statistics in self.stats_v... | This code initializes a GUI interface for a video analysis tool, setting up navigation buttons (Select, Detect, Results, Help, Exit) and interactive elements for video/ROI selection. It creates Tkinter frames, menus, and controls to manage video directories, file lists, and region-of-interest (ROI) definitions, enablin... | def __init__(self, parent, controller):
# Get attributs from parent class
(self.sasdi_version,
self.images_extensions_lower,
self.images_extensions,
self.screen_width,
self.screen_height,
self.main_fullpath
) = controller.get_parameters()
#... |
def read_geojson_file(file_path):
with open(file=file_path, mode="r", encoding="utf-8") as geojson_file:
return json.load(geojson_file, strict=False)
def read_csv_file(file_path):
if os.path.exists(file_path):
with open(file_path, "r") as csv_file:
return pd.read_csv(csv_file, dtype=... | The main task of the code is to blend CSV statistics data with GeoJSON files representing Berlin's administrative areas (districts, regions, planning areas), combining them by year/half-year. It processes multiple data sources, merges statistics into GeoJSON features, and outputs structured geographic data files along ... | def blend_data(source_path, results_path, clean=False, quiet=False):
# Make results path
os.makedirs(os.path.join(results_path), exist_ok=True)
# Initialize statistics
json_statistics = {}
# Iterate over LOR area types
for lor_area_type in ["districts", "district-regions", "planning-areas"]:
... |
def bush_initialization(network, demands, previous_bushes=None):
if not network['Initialized']:
print('Re-initialization for imported network ...')
for link in network['edges']:
network['edges'][link]['flow'] = 0
network['edges'][link]['cost'] = network['edges'][link]['ff_tt... | This code implements a network flow optimization algorithm using a bush structure to iteratively update traffic flows and minimize the Beckmann objective function. It initializes network data, loads or reloads from checkpoints, performs iterative updates with inner loops, tracks convergence, and saves progress. The goa... | def algorithmBush(network_filepath, demand_filepaths, network_type='TNTP', numClasses=1,
maxIterations=1000, convergence_gap=1e-4, reload=False):
start_time = time.time()
best_known_obj = 0
reloaded = False
if not reload:
print('\n** Importing network **')
network, dem... |
def load_model_and_tokenizer():
global model, tokenizer
download_files()
model_safe_tensors = load_file('/tmp/model_safetensors')
config = BertConfig.from_pretrained("/tmp/config.json")
model = BertForTokenClassification(config)
model.load_state_dict(model_safe_tensors)
tokenizer = BertT... | The main task of this code is to extract a company name from input text using a pre-trained model and tokenizer. It loads the model if not already loaded, processes the input text to predict results, extracts the company name from the prediction output, and returns it in a JSON response with a 200 status code. | def lambda_handler(event, context):
print("------------------STARTED EXECUTION----------------------", "\n\n")
if model == None or tokenizer == None:
load_model_and_tokenizer()
print("------------------GOT MODEL STUFF----------------------","\n\n")
print("------------------LOADED ALL MODELS----... |
def sox_create_empty_length(length, newsong):
base_empty = notes_directory+"empty.wav"
copy_over_from_assets(base_empty, newsong)
sox_pad(newsong, 0, length-0.5)
def sox_mix_at_v2(song, note, time):
temporary = "temp_sox_mix_at_v2.wav"
first_half = "temp_first_half.wav"
second_half = "temp_seco... | The function creates a new song by generating an empty audio file of specified length and then mixing individual guitar notes from a tablist into it. Each note, derived from string/fret positions in the tablist, is placed at designated time intervals using SOX audio processing commands. | def create_new_song_from_tablist(newsong, length, tablist):
sox_create_empty_length(length, newsong)
for tab_item in tablist:
item_gstring = tab_item[0]
item_fret = tab_item[1]
item_time = tab_item[2]
sox_mix_at_v2(newsong, get_note(item_gstring, item_fret) , item_time) |
def sox_create_empty_length(length, newsong):
base_empty = notes_directory+"empty.wav"
copy_over_from_assets(base_empty, newsong)
sox_pad(newsong, 0, length-0.5)
def sox_mix_at_v2(song, note, time):
temporary = "temp_sox_mix_at_v2.wav"
first_half = "temp_first_half.wav"
second_half = "temp_seco... | The code tests SOX audio mixing by creating a 5-second empty WAV file and mixing a middle-E note (octave 3) at full volume into it, verifying the functionality of the `sox_mix_at_v2` method for audio synthesis. | def test_sox_mix_at():
testfile = "test_sox_mix_at_song.wav"
sox_create_empty_length(5, testfile)
sox_mix_at_v2(testfile, get_note("E",3), 1) |
def create_done_dict(cards):
done_items = [v for k,v in cards.items() if v['history'][0][0]=='done']
done_dict = {}
for di in done_items:
project = di['labels'][0]
date_done = dateparser.parse(di['history'][0][1])
name = di['name']
if project in done_dict:
done_dict[project].append([date_don... | The main task of the code is to generate a project progress dashboard by retrieving the latest query data, calculating completed items, monthly tasks, burndown charts, and histograms, then rendering these metrics into a webpage template for visualization. | def home_page(request):
data = Query.objects.all().order_by('date')
data = data.reverse()[0]
cards = json.loads(data.payload)
# get the done dictionary
done_dict = create_done_dict(cards)
number_completed = sum([len(done_dict[di]) for di in done_dict])
# get the the items for this month
thismonth = crea... |
def get_version(folder):
"""Get the chromedriver version"""
chromedriver_path = os.path.join(folder, _get_driver_filename())
if not os.path.exists(chromedriver_path):
return None
output = subprocess.check_output(f'"{chromedriver_path}" -v', shell=True)
output_str = output.decode(encoding='as... | The main task of the code is to check if a compatible ChromeDriver exists in the specified directory, and if not, download and extract the appropriate version based on the Chrome browser's version and architecture. It ensures the correct ChromeDriver is available without redundant downloads by comparing cached and requ... | def download_only_if_needed(chrome_path=None, chromedriver_folder=None):
"""Check if there is a chromedriver in pathm and download new if needed"""
if chromedriver_folder:
dpath = chromedriver_folder
else:
dpath = ub.ensure_app_cache_dir('latest_chromedriver')
c_version = chrome_info.ge... |
def get_timenow():
time_now = datetime.datetime.now()
date_time = time_now.strftime("%d/%m/%Y %H:%M:%S")
tim = int(date_time.split(' ')[1].split(':')[0], 10) * 3600 + int(date_time.split(' ')[1].split(':')[1], 10)*60 + int(date_time.split(' ')[1].split(':')[2], 10)
return tim
def data_packet_store(pkt):... | This function processes incoming packets by checking their type. If a data packet ("1") is received, it logs details and stores the data. For beacon packets ("3"), it extracts the source ID, checks if the OBC is connected, and triggers control packet transmission if newly connected. It manages connected OBCs and logs s... | def packet_handler(pkt,te): # pkt is the received packet in hexadecimal format
arr_headers = struct.unpack_from('!s', pkt) # data packet
pkt_type = arr_headers[0].decode('utf-8') # checks the packet type
if pkt_type == "1":
# no_data_pkt_rcv += 1
print(get_timenow(),":... |
def evaluate_HIGH_CARD(cards: List[Card]) -> int:
sorted_cards = sorted(cards, key=lambda c: rank_strength(c.rank))
card_sum = 0
for i, card in enumerate(sorted_cards):
card_sum += rank_strength(card.rank) * (14 ** i)
return card_sum
def evaluate_ONE_PAIR(cards: List[Card]) -> int:
sorted_ca... | This code initializes a poker hand object by setting its rank, cards, and calculating its value using the appropriate evaluation function based on the hand's rank. The value represents the hand's strength for comparison. | def __init__(self, rank: HandRank, cards: List[Card]):
self.rank = rank
self.cards = cards
if self.rank == HandRank.HIGH_CARD:
self.value = evaluate_HIGH_CARD(self.cards)
elif self.rank == HandRank.ONE_PAIR:
self.value = evaluate_ONE_PAIR(self.cards)
elif ... |
def start(self):
self.create_shuffled_deck()
self.deal_initial_cards()
def pre_flop(self):
self.do_phase(Phase.PRE_FLOP)
def flop(self):
self.community_cards.extend(self.get_next_cards(3))
self.do_phase(Phase.FLOP)
def turn(self):
self.community_cards.extend(self.get_next... | This code simulates a poker game by sequentially executing key stages: initializing the game, handling pre-flop betting, revealing community cards on the flop, turn, and river, and finally concluding the game. The method orchestrates the flow from start to finish, likely managing player actions, card dealing, and game ... | def play(self):
self.start()
self.pre_flop()
self.flop()
self.turn()
self.river()
self.finish() |
def scroll_to_page_bottom(driver):
last_height = driver.execute_script("return document.body.scrollHeight")
wait = WebDriverWait(driver, timeout=SCROLL_TIMEOUT, poll_frequency=SCROLL_PAUSE_TIME)
def same_scroll_height(driver):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
... | This function extracts links from Google search results pages, including related searches, up to a specified recursion depth. It scrolls to the page bottom, collects links using different methods based on page structure, and recursively gathers links from related search results, returning a set of all found links. | def get_links_on_google_page(driver, related_levels, deep_search):
if related_levels < 0:
return []
links = set()
related_search_links = set()
scroll_to_page_bottom(driver)
try:
get_google_links_all_page(driver, links, related_search_links, deep_search)
except NoSuchElementExce... |
def get_search_query(names):
names_quoted = [f"\"{name}\"" for name in names]
names_q_str = "+".join(names_quoted)
return f"https://www.google.com/search?as_oq={names_q_str}"
def wait_until_captcha_solved(driver):
wait = WebDriverWait(driver, timeout=CAPTCHA_TIMEOUT, poll_frequency=CAPTCHA_POLL)
try... | The code automates searching for names on Google, extracts links, and groups them based on related levels and deep search parameters. It initializes a Chrome driver, navigates to a search query, solves CAPTCHA, retrieves links, groups them, and quits the session, returning the grouped links. | def get_numbers_and_links_for_names(names, related_levels, deep_search):
# start session
driver = webdriver.Chrome()
# wait strategy
driver.implicitly_wait(1)
driver.get(get_search_query(names))
wait_until_captcha_solved(driver)
links_grp = group_links(list(get_links_on_google_page(driver... |
def entropy(attr_countresult):
s=float(0)
div=0
for i in attr_countresult:
k1=0
div=i/float(sum(attr_countresult))
if div!=0:
lg=float(math.log(div,2))
k1=abs(lg)
if(div!=0 and k1!=0):
y1=float(multi(div,k1))
s=adder(s,y1) #############################ADDER IMPLEMENTATION 1
else:
y1=float(0... | The code calculates the information gain of a specific attribute in a dataset by determining the entropy of subsets formed by unique attribute values and comparing it to the overall entropy, returning the information gain for decision tree feature selection. | def IG(attr,attr_count,path,i):
loc=(path)
wb1 = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(i)
print("------------------------------------------------------------")
attr_entropy=0
attr_column=[]
########################################################################################
#GETTING THE column... |
def computeParticleFilter(self,show=False):
'''
Apply the particle filter on self.signalIN
'''
for itNum in range(self.param['NRepeat']):
if show:
print("Do iteration #"+str(itNum+1)+"/"+str(self.param['NRepeat']))
TMP=self.comp_oneIteration_pa... | The main task of the code is to detect saccades in a signal by analyzing the Upsilon threshold, grouping detected segments, and outputting the onset and offset indices of saccades. It processes signals via a particle filter, removes median noise, identifies threshold-exceeding regions, and aggregates results across mul... | def detectSaccades(self,show=False):
'''
Detect saccades
'''
# Run the particle filter
self.computeParticleFilter(show)
# Remove the median if desired
self.removeMedian()
# Find parts of the signal where the Upsilon is larger than the detection thres... |
def computeParticleFilter(self,show=False):
'''
Apply the particle filter on self.signalIN
'''
for itNum in range(self.param['NRepeat']):
if show:
print("Do iteration #"+str(itNum+1)+"/"+str(self.param['NRepeat']))
TMP=self.comp_oneIteration_pa... | The main task of this code is to detect saccades in each signal (or paired signals) by analyzing regions where the Upsilon metric exceeds a detection threshold. It groups these regions into saccade onsets and offsets, handles reverse signal pairs if specified, and constructs a saccade signal. The process involves filte... | def detectSaccadesSeparate(self,show=False):
'''
Detect saccades independently on each signal (or pair of signals if the reverse is set)
'''
# Run the particle filter
self.computeParticleFilter(show)
# Remove the median if desired
self.removeMedian()
... |
def _modify_request_before_signing(self, request):
if 'Authorization' in request.headers:
del request.headers['Authorization']
if 'Date' not in request.headers:
request.headers['X-Amz-Date'] = self.timestamp
if self.credentials.token:
request.headers['X-Amz-Se... | This function adds AWS v4 authentication to an HTTP request by generating a timestamp, creating a canonical request, computing a signing string, generating a cryptographic signature, and injecting the signature into the request headers to authorize API requests securely. | def add_auth(self, request):
if self.credentials is None:
raise NoCredentialsError
# Create a new timestamp for each signing event
now = datetime.datetime.utcnow()
self.timestamp = now.strftime('%Y%m%dT%H%M%SZ')
# This could be a retry. Make sure the previous
... |
def purge_previous_news_items():
date_now = datetime.now()
start_of_day = make_aware(datetime.strptime(date_now.strftime('%Y-%m-%d'),'%Y-%m-%d') + timedelta(hours=5))
print(start_of_day)
#GET ALL PREVIOUS ITEMS
items_before = NewsItem.objects.filter(date_added__lt=start_of_day)
print(items_befor... | The code's main task is to scrape and store headlines from specified news websites. It purges previous news items, fetches each site's content using HTTP headers, parses the data with BeautifulSoup, and saves collected headlines to the database as NewsItem and StoredNewsItem objects, ensuring only the latest headlines ... | def handle(self, *args, **options):
#For connecting
hdr = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Mobile Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',... |
def get_image_paths(dataroot):
paths = None # return None if dataroot is None
if isinstance(dataroot, str):
paths = sorted(_get_paths_from_images(dataroot))
elif isinstance(dataroot, list):
paths = []
for i in dataroot:
paths += sorted(_get_paths_from_images(i))
retu... | The code extracts 3D image patches from medical scans (t1, flair, label) of specified size, saves them as NIfTI files in structured directories under `out_root`, and applies preprocessing. It iterates through input images, generates patches using sliding windows, and stores them with numbered filenames for training/ana... | def GetPatch(out_root, patch_size):
"""
Get image patch
"""
t1 = get_image_paths('')
flair = get_image_paths('')
label = get_image_paths('')
mkdir(out_root)
mkdir(os.path.join(out_root, 't1'))
mkdir(os.path.join(out_root, 't2-flair'))
mkdir(os.path.join(out_root, 'label'))
... |
def receive_from_server():
"""
receives data from server and acts accordingly
"""
global alive, data
if me_position != str(fps_camera.position) or me_rotation != str(fps_camera.rotation):
send_and_create_position_rotation_message()
r_list, w_list, e_list = select.select([player_socket]... | The code's main task is to handle real-time input and game logic in a loop. It updates UI elements with server data, processes key presses for actions like respawning, quitting, shooting, and reloading, and manages game state transitions (e.g., alive/dead). It sends player actions to the server, updates weapon states, ... | def update():
"""
called every frame, handles inputs and calls a function that received data from user
"""
global feed_changed, feed, alive
receive_from_server()
if feed_changed:
feed_changed = False
feed_txt.text = feed
if not game_ended:
if held_keys['m'] and not... |
def GenerateButtonHandler(
self: object,
nrows: int = 3) -> None:
"""
Generate button handler handles errors then calls
the genetrator
:param nrows: rows of the square board
"""
# Error handling: invalid number of rows
try:
... | The main task of the code is to set up the graphical user interface (GUI) for a Qt application. It configures the main window's properties, creates UI elements like labels, spin boxes, buttons, and combo boxes, arranges them using layouts, and connects actions to handlers for generating/solving a board. Menus for closi... | def setupUi(
self: object,
MainWindow: QtWidgets.QMainWindow):
"""
Main GUI functions and handles
"""
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 620)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Fixed... |
def random_elem(self, a=0 , b=0):
if a == 0 and b == 0:
r = random.randrange(2, self.N)
while math.gcd(r, self.N) != 1:
r = random.randrange(2, self.N)
return r
else:
r = random.randrange(a, b)
while math.gcd(r, self.N) != 1:
... | The code tests RSA encryption and decryption correctness by comparing expected and actual outputs. It generates a random message, encrypts it using the public key (e, N), then decrypts with the private key (d, N). It verifies both standard and blinded decryption methods against the expected result, printing "Correct" o... | def test(self):
print(f"RSA(N = {self.N}, d = {self.d}, e = {self.e})")
print()
m = self.random_elem()
print(f"m = {m}")
c_test = pow(m, self.e, self.N)
d_test = pow(c_test, self.d, self.N)
print(f"Correct: c = {c_test}, d = {d_test}")
print()
... |
def log(self, token='', lexema='', log=''):
self.output.write(f"{token},{lexema},{log}\n")
print("{:10}".format(token), "{:10}".format(lexema), "{:10}".format(log))
def accept_token(self, expected):
self.accept(expected, self.get_current_token)
def get_last_token(self):
""" return token ... | The main task of the code is to process arithmetic or logical operators (+, -, OR) by logging the operation, validating the operator type, and pushing the identified operator token onto a stack for further processing in an expression evaluation context. | def op_soma(self):
self.log(log ='op_soma')
# op-soma => + | - | OR
self.accept_token(['OP_SUM', 'OP_SUB', 'OP_OR'])
self.stack_operators.append(self.get_last_token()) |
def log(self, token='', lexema='', log=''):
self.output.write(f"{token},{lexema},{log}\n")
print("{:10}".format(token), "{:10}".format(lexema), "{:10}".format(log))
def get_current_token(self):
""" return token """
return self.tokens[self.counter][0]
def accept_token(self, expected):
... | This function processes arithmetic and logical operators (*, /, DIV, MOD, AND) by checking the current token, appending valid operators to a stack, and accepting specified tokens for parsing. It logs 'op_mult' for tracking and handles operator recognition and storage during expression parsing. | def op_mult(self):
self.log(log ='op_mult')
#op-mult => * | / | DIV | MOD | AND
if self.get_current_token() in ['OP_MULT', 'OP_DIV', 'OP_AND']:
self.accept_token(['OP_MULT', 'OP_DIV', 'OP_AND'])
self.stack_operators.append(self.get_last_token())
self.acc... |
def log(self, token='', lexema='', log=''):
self.output.write(f"{token},{lexema},{log}\n")
print("{:10}".format(token), "{:10}".format(lexema), "{:10}".format(log))
def get_current_token(self):
""" return token """
return self.tokens[self.counter][0]
def accept_token(self, expected):
... | The method processes unary operators (+, -, NOT) by checking the current token. If it's OP_INC, OP_SNC, or NOT, it accepts the token and pushes it onto the stack_operators. This handles unary operations in parsing, logging the action for tracking. | def op_unario(self):
self.log(log ='op_unario')
#op-unario => + | - | NOT
if self.get_current_token() in ['OP_INC', 'OP_SNC']:
self.accept_token(['OP_INC', 'OP_SNC'])
self.stack_operators.append(self.get_last_token())
else:
self.accept('NOT')
... |
def log(self, token='', lexema='', log=''):
self.output.write(f"{token},{lexema},{log}\n")
print("{:10}".format(token), "{:10}".format(lexema), "{:10}".format(log))
def get_current_token(self):
""" return token """
return self.tokens[self.counter][0]
def accept_token(self, expected):
... | This function identifies and processes literal values (integers, floats, characters, strings) by checking the current token type. If a valid literal token is found, it accepts the token and pushes the value onto the stack. If not, it delegates to a method for handling boolean values, ensuring proper parsing and classif... | def literal(self):
self.log(log ='literal')
# literal => NUMINT | NUMREAL | CARACTERE | STRING | valor-verdade
if self.get_current_token() in ['INT', 'FLOAT', 'CHAR', 'STRING']:
self.accept_token(['INT', 'FLOAT', 'CHAR', 'STRING'])
self.stack_number.append(self.get_last(... |
def log(self, token='', lexema='', log=''):
self.output.write(f"{token},{lexema},{log}\n")
print("{:10}".format(token), "{:10}".format(lexema), "{:10}".format(log))
def accept(self, expected, mode=None):
""" check if a lexema or token is as expected
params:
expected - st... | This function parses a constant declaration in a programming language, handling the syntax 'CONST ID = literal ;'. It updates the symbol table with the constant's identifier and value, temporarily setting the last_type to 'CONST' during parsing, then restoring the previous type. Semantic actions include logging, symbol... | def decl_const(self):
self.log(log ='decl_const')
last = self.last_type #semantic-action
self.last_type = 'CONST' #semantic-action
# decl-const => CONST ID = literal ;
self.accept('CONST')
self.accept_token('ID')
self.add_symbol() #semantic-action
se... |
def extract_tickers_from_submission_content(submission):
"""Does not look at the comments"""
ticker_set = set()
ret = ticker_set \
.union(extract_tickers_from_text(submission.name)) \
.union(extract_tickers_from_text(submission.title)) \
.union(extract_tickers_from_text(subm... | The main task of the code is to scrape a Reddit submission, extract stock tickers from its content and comments, aggregate their frequencies, and return structured results. It expands comment threads based on thresholds, processes all comments via BFS, merges ticker counts, filters/sorts them, and packages the data int... | def scrape_submission(submission,
comment_expansion_limit=0,
comment_expansion_thresh=1):
submission_ticker_count = defaultdict(int)
post_ticker_set = extract_tickers_from_submission_content(submission)
merge_word_counts(
submission_ticker_count,
set_to_count(post_ticker_set)
)
... |
def scrape_submission(submission,
comment_expansion_limit=0,
comment_expansion_thresh=1):
submission_ticker_count = defaultdict(int)
post_ticker_set = extract_tickers_from_submission_content(submission)
merge_word_counts(
submission_ticker_count,
set_to_count(post_ticker_set)
)
... | The main task of the code is to scrape Reddit submissions from the "wallstreetbets" subreddit, analyze comments for ticker symbols, count occurrences of each ticker in comments, and save results along with timestamps and headers to an output file. It uses command-line arguments for submission IDs, output file paths, an... | def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--submission",
type=str,
nargs="+",
help="Submission ID (e.g k29omq)"
)
parser.add_argument(
"-o",
"--output",
type=str,
help="File to write results to",
... |
def SearchNodeBST(self, data):
return self._SearchNodeBST(data=data, root=self.root)
def SuccessorNodeBST(self, root: Node):
if root is None:
return None
if root.right is not None:
return self._minimum(root=root.right)
y: Node = root.parent
while y is not ... | This function deletes a node with specified data from a binary search tree (BST). It handles three cases: 1) node with no children (removes it from parent), 2) node with one child (reparents the child), 3) node with two children (replaces it with its successor node's data and recursively deletes the successor). The del... | def DelNode(self, data):
node: Node = self.SearchNodeBST(data=data)
if node is None:
return False
if node.left is None and node.right is None:
parent: Node = node.parent
if parent.left == node:
parent.left = None
else:
... |
def step_simulation(self, action):
# maybe make ref traj only send relevant idxs?
ref_pos, ref_vel = self.get_ref_state(self.phase + self.phase_add)
if not self.no_delta:
target = action + ref_pos[self.pos_idx]
else:
target = action + self.offset
self.u = pd_... | The code advances a simulation by executing the given action multiple times, updates the environment's time and phase, checks termination conditions based on height and reward thresholds, computes a reward, and returns the full state, reward, and termination status. If `return_omniscient_state` is True, it also returns... | def step(self, action, return_omniscient_state=False):
for _ in range(self.simrate):
self.step_simulation(action)
height = self.sim.qpos()[2]
self.time += 1
self.phase += self.phase_add
if self.phase > self.phaselen:
self.phase = 0
self.counter += 1
... |
def get_ref_state(self, phase=None):
if phase is None:
phase = self.phase
if phase > self.phaselen:
phase = 0
pos = np.copy(self.trajectory.qpos[phase * self.simrate])
# this is just setting the x to where it "should" be given the number
# of cycles
# pos[0] +=... | The main task of the code is to reset a simulation environment by initializing the phase, joint positions (qpos), and velocities (qvel), and optionally randomizing physical parameters like damping, mass, center of mass (COM), and friction. This enables dynamic parameter variation for robustness in reinforcement learnin... | def reset(self, return_omniscient_state=False):
self.phase = random.randint(0, self.phaselen)
self.time = 0
self.counter = 0
qpos, qvel = self.get_ref_state(self.phase)
self.sim.set_qpos(qpos)
self.sim.set_qvel(qvel)
# Randomize dynamics:
if self.dynamics_randomization... |
def setUpDatabase(db_name):
path = os.path.dirname(os.path.abspath(__file__))
conn = sqlite3.connect(path+'/'+db_name)
cur = conn.cursor()
return cur, conn
def add_to_database(cur, conn, query, db_filename, start, end):
cur.execute("CREATE TABLE IF NOT EXISTS chicago_objects (object_id INTEGER PRIMA... | The main task of the code is to process and analyze Chicago activism data by adding data chunks into a SQLite database, creating tables for names, mediums, and origins, removing duplicates, generating visualizations (century and origin counts), and writing results to files. It handles data segmentation, database manage... | def main():
cur, conn = setUpDatabase("chicago_data5.db")
add_to_database(cur, conn, "activism","chicago_data5.db", 0, 25)
add_to_database(cur, conn, "activism","chicago_data5.db", 25, 50)
add_to_database(cur, conn, "activism","chicago_data5.db", 50, 75)
add_to_database(cur, conn, "activism","chicag... |
def set_cor_mosaic():
# selected appropriate points by matplotlib
fig1 = np.array([(693, 466), (801, 595), (896, 829), (1069, 674), (1133, 886), (1192, 482), (1198, 608), (1289, 761), (1301, 571), (1423, 555), (1496, 981), (1505, 381), (1582, 546)])
fig2 = np.array([(95, 437), (218, 591), (300, 847), (503,... | The code performs two main tasks: (1) Image mosaicing by warping and merging two input images using homography computed from corresponding points, and (2) Image rectification by aligning a distorted image using predefined control points. Both processes involve loading images, applying geometric transformations, and sav... | def main():
##############
# step 1: mosaicing
##############
# read images
img_in = Image.open('data/porto1.png').convert('RGB')
img_ref = Image.open('data/porto2.png').convert('RGB')
img_size = (1608, 1067)
# shape of igs_in, igs_ref: [y, x, 3]
igs_in = np.array(img_in)
igs_r... |
def EdgeDetection(Igs, sigma):
size = int(3 * sigma + 1)
(h, w) = Igs.shape
gaussian_filter = GetGaussian(sigma, size)
smoothed_image = ConvFilter(Igs, gaussian_filter)
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
sobel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
Ix = C... | The main task of the code is to process images by performing edge detection, Hough Transform, and line segmentation. It reads grayscale images, computes edge magnitudes, applies the Hough Transform to identify lines, extracts line parameters, and visualizes results by saving edge magnitude maps, Hough transform outputs... | def main():
# read images
for img_path in glob.glob(datadir+'/*.jpg'):
# load grayscale image
filename = img_path.split('/')[-1].split('.')[0]
img = Image.open(img_path).convert("L")
print(f'open {filename}...')
Igs = np.array(img)
Igs = Igs / 255.
# Ho... |
def _SetProjectForInvocation(project_id: Text):
"""Sets the given project ID as the one to use for this invocation."""
gcloud_cmd = 'gcloud config set project {project}'.format(project=project_id)
err_msg = 'Failed to set the project ID for this invocation: {}'.format(
project_id)
_RunGcloudCommand(gcloud_c... | (The main task of the code is to automate the setup of a Google Cloud environment for a cloud alerting demo. It configures a GCP project by enabling essential services, granting permissions to the Cloud Build service account, setting up remote Terraform state storage, triggering a Cloud Build pipeline with specified pa... | def main(argv: List[Text]):
# Set the default gcloud project to a new project. Make sure the billing account is set.
project_id = ''
branch = 'main' # The Git branch to use.
config_server_type = 'in-memory'
try:
opts, args = getopt.getopt(argv, 'hp:b:c:',['project_id=', 'branch=', 'config_server_type='... |
def create_properties(self):
# Reads the neo4j edges file to determine properties it needs to create
edges = self.edges
# make sure this edges we need exist
curie_label = dict(zip(edges[':TYPE'], edges['property_label']))
curie_label = {k: v for k, v in curie_label.items() if k}
... | The main task of the code is to initialize and construct a graph structure by sequentially creating properties, classes, nodes, and edges. This method orchestrates the setup of a graph's foundational elements, ensuring all components are properly defined and connected before further operations or analyses are performed... | def run(self):
self.create_properties()
self.create_classes()
self.create_nodes()
self.create_edges() |
def categorical_log_probs(self):
"""Log probabilities for the `C` ordered class categories."""
z_values = self._z_values()
log_cdfs = self.link.log_cdf(z_values)
return tfp_math.log_sub_exp(log_cdfs[..., :-1], log_cdfs[..., 1:])
def _num_categories(self):
"""Number of ordinal cat... | This method generates `n` samples from a categorical distribution using logits, reshapes the output to match the desired batch dimensions, and returns the sampled values in the correct tensor format. | def _sample_n(self, n, seed=None):
"""Internal method to help generate `n` samples."""
logits = tf.reshape(
self.categorical_log_probs(), [-1, self._num_categories()])
draws = samplers.categorical(logits, n, dtype=self.dtype, seed=seed)
return tf.reshape(
tf.trans... |
def change_to_menu(self):
if self.builder.level_number == 1 and not self.IS_PAUSE and self.player.hp > 0:
self.builder.level_number = 2
self.builder.objects = self.builder.load_objects_from_db()
self.player.X0, self.player.Y0 = self.builder.get_start_coords()[0], self.builder... | This code manages a game loop handling user input, game state updates, and rendering. It processes events like quitting, pausing/resuming, restarting, and mouse interactions. When the game is active, it updates player movement, collision checks, and game phases, while rendering the game screen. If the game is paused or... | def run(self):
while True:
if self.menue.ISGAME == True:
for e in pg.event.get():
if e.type == pg.QUIT:
pg.quit()
quit()
if e.type == pg.KEYDOWN:
if e.key == pg.K_ESCAPE:
... |
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def dl_all_new_items(conn):
c = conn.cursor()
try:
c.execute("SELECT * FROM ph_items WHERE new='1'")
except Error as e:
print(e)
s... | The code's main task is to initiate a database connection and execute two download operations: first, downloading new items, then downloading all items. It uses a context manager to ensure proper connection handling, printing status messages for each step. | def dl_start():
conn = create_connection(database)
with conn:
print("downloading new items")
dl_all_new_items(conn)
print("downloading all items")
dl_all_items(conn) |
def getClientToken(self, session: httpx.Client) -> str:
while True:
payload = {
"client_data": {
"client_id": "d8a5ed958d274c2e8ee717e6a4b0971d",
"client_version": self.client_version,
"js_sdk_data": {
"device_brand": "unknown",
... | The main task of this code is to create multiple Spotify accounts by generating random usernames, emails, and passwords, using proxies if enabled, and handling account creation via HTTP requests. It includes checking for successful registration, updating account details, following predefined entities (profiles, playlis... | def createAccount(self):
while (self.target_settings['Use_Target'] == 'y' and Console.created < self.target_settings['Target_To']) or (self.target_settings['Use_Target'] != 'y'):
try:
if self.settings['Use_Proxy'] == 'y':
proxy = choice(self.proxies)
... |
def set_training(self, training):
self.training = training
self.model.train(self.training)
def _epoch_step(self):
self.iteration = -1
self.scheduler.step()
def _iterate(self, data, start_time):
self.iteration += 1
_, input_, target = self._parse_data(data)
loss, m... | This method executes an epoch of training or evaluation by iterating through a data loader, updating model states, resetting metrics, and collecting performance metrics. It sets the training mode, processes each data batch, and returns the aggregated metrics. | def _run_epoch(self, training=None):
if training is not None:
self.set_training(training)
self._epoch_step()
self.meters.reset()
loader = self.loaders[self.training]
start_time = time.time()
for data in loader:
self._iterate(data, start_time)
... |
def make_rest_header(title, label, header_char):
"""
Arguments:
header_char: "=" or "-".
"""
line = len(title) * header_char
rest = textwrap.dedent("""\
.. _{0}:
{1}
{line}
""").format(label, title, line=line)
return rest
def add_rest_section(rest, new_rest, prefix, sep=N... | The function generates formatted documentation for a data type by constructing headers, descriptions, tables, and post content. It uses YAML data, checks the prefix (CSV/XML) to determine naming and post content, recursively processes subtypes and extensions, and formats sections with appropriate separators and headers... | def make_type_rest(all_types, data_type, header_char, prefix):
"""
Arguments:
header_char: "=" or "-".
prefix: the label prefix (e.g. "single-xml" or "multi-xml").
"""
type_map = all_types.type_map
if prefix.split('-')[-1] == 'csv':
type_name = data_type.csv_name
else:
... |
def make_rest_header(title, label, header_char):
"""
Arguments:
header_char: "=" or "-".
"""
line = len(title) * header_char
rest = textwrap.dedent("""\
.. _{0}:
{1}
{line}
""").format(label, title, line=line)
return rest
def make_type_rest(all_types, data_type, header_ch... | This function generates a single-page reStructuredText (reST) file documenting XML or CSV elements/enumerations. It creates a header, adds a table of contents, iterates through element/enumeration types, constructs sections with sub-headers, and writes the compiled content to a specified file path, excluding sub-types ... | def update_rest_file_single_page(all_types,mode):
prefix = "single-{}".format(mode)
if mode == "xml":
path = os.path.join(common.XML_DIR, "single_page.rst")
rest = make_rest_header("XML Elements & Enumerations (Single Page)", label=prefix, header_char="=")
elif mode == "csv":
path = ... |
def make_widths(self, headers, tags_data):
widths = []
for i, header in enumerate(headers):
width = self.make_width(i, header, tags_data)
widths.append(width)
return widths
def make_divider(self, widths, fill_char=None):
if fill_char is None:
fill_char... | The main task of the code is to generate a reST table from input data, returning it as a list of text lines. It extracts tags from the provided data type, calculates column widths, constructs table headers and rows, and handles exceptions by raising an error with data details. | def make_table(self, data_type):
"""
Return the reST table for an object type.
The table is returned as a list of lines of text.
"""
try:
tags = data_type.tags
widths = self.make_widths(self.headers, tags)
lines = [self.make_divider(widths)]
... |
def update_rest_file_single_page(all_types,mode):
prefix = "single-{}".format(mode)
if mode == "xml":
path = os.path.join(common.XML_DIR, "single_page.rst")
rest = make_rest_header("XML Elements & Enumerations (Single Page)", label=prefix, header_char="=")
elif mode == "csv":
path = ... | The main task of the code is to update auto-generated reST files for data types in 'csv' and 'xml' formats. It processes either all types or a specified type, generating files with prefixes like "multi-csv" or "multi-xml". For each type, it logs updates, retrieves type data, and calls functions to update table files an... | def update_rest_files(type_name=None):
"""
Update auto-generated reST files.
"""
for mode in ['csv','xml']:
prefix = "multi-{}".format(mode)
all_types = common.get_all_types()
type_map = all_types.type_map
if type_name is None:
type_names = sorted(type_map.ke... |
def set_multiplexer(self, value):
"""Set the analog multiplexer.
Sets up the analog input in single or differential modes.
If b is specified as gnd the ADC will be in single-ended mode, referenced against Ground.
If b is specified as in1 or ref the ADC will be in differential mode.
... | This function reads the raw voltage from a specified ADC channel, applies scaling based on the programmable gain and ADC type (ADS1115 or similar), and returns the voltage in volts. It configures the multiplexer, initiates conversion, waits for completion, and calculates the final voltage by normalizing the ADC value a... | def get_voltage(self, channel=None):
"""Read the raw voltage of a channel."""
if channel is not None:
self.set_multiplexer(channel)
self.start_conversion()
self.wait_for_conversion()
value = self.get_conversion_value()
gain = self.get_programmable_gain()
... |
def _run_average(self, points_lr, colors_lr, points_hr, idx_lr2hr):
num_centroid = int(points_hr.shape[0] / self.num_point) * self.over_sample
patch_idx = self._crop_patch_average(points_hr, num_centroid)
colors_hr_list = []
enumerator = tqdm(range(num_centroid)) if self.verbose else ra... | The code maps low-resolution (lr) points to high-resolution (hr) points by computing hash indices for hr points, then delegates to mode-specific methods (`_run_average`, `_run_split`, or `_run_block`) to process colors and points. If `idx_lr2hr` is undefined, it converts `points_hr` to a tensor, computes spatial hashes... | def __call__(self, points_lr, colors_lr, points_hr, idx_lr2hr=None):
if idx_lr2hr is None:
is_numpy = False
if not torch.is_tensor(points_hr):
is_numpy = True
if is_numpy:
points_hr = torch.from_numpy(points_hr)
points_hr = torch.ca... |
def conv_message_to_arr(message):
func_mess = message.upper()
message_arr = []
for i in func_mess:
message_arr.append(ord(i) - 65)
return message_arr
def main_gen(n=512):
if n == 2:
return random.choice([2, 3])
while True:
prime_cand = prime_gen(n)
if not rabin_mi... | The code implements an ElGamal encryption scheme by generating a prime number, a generator, and key pairs (public/private). It processes each message segment to create digital signatures using the private key, then returns the prime, generator, keys, and signature array for secure message encryption and verification. | def elgamal_encrypt(message, bits):
mess_arr = conv_message_to_arr(message)
prime = main_gen(bits)
generator = random.randint(1, prime)
private_key = random.randint(1, prime)
public_key = pow(generator, private_key, prime)
sign_arr = []
index = 0
for message in mess_arr:
s1, s2... |
def Fetch_Configs(url, v):
"""
fetches the odoh config, from the url specified.
Positional arguments:
url -- url where odoh config is hosted.
"""
if v:
print(f" -- Fetch ODOH-Config from: {url}")
response = requests.get(url)
if response.status_code == 200:
byte_data = r... | The main task of the code is to perform an Oblivious DoH (ODoH) DNS query by discovering ODoH configurations via URL or DNS, constructing an encrypted DNS query, sending it over HTTP to an ODoH endpoint, and decrypting/validating the response to extract IP addresses from SVCB or DNS answers. It returns the ODoH host, r... | def dns_odoh(odoh_ddr, configFetch_method, ddrRType, resolver, odohhost, http_method, domain_name, rr_type, v, odohconfigF, dns_queryid=0, edns=False):
"""
odoh_ddr: domain of odoh target.
ddrRType: RR Type of the odoh target HTTPS/ SVCB.
resolver: which resolver to ask for target's conf.
http_metho... |
def get_crypto_data(pair, since, api):
# Making a call to the API
# The paramater passed is the type of data that we want to query 'OPEN, HIGH, LOW AND CLOSE' which are the different price points on the chart within a certain timeframe
# Within a given time period, we want to accumulate what the open pric... | The function 'buy_On_Decrease' triggers a simulated cryptocurrency buy order when a price decrease exceeds a predefined stop-loss threshold. It verifies the downward trend by rechecking metrics after a 3-second delay, ensuring the decline is sustained. If confirmed, it executes a trade using available funds, leveraging... | def buy_On_Decrease(pair, since, api, open_, close_, loop_cycle, simple_Moving_Average, price_difference, percentage_Increase, percentage_Decrease, percentage_stop_loss_equivilant, standard_deviation, bollinger_bands, STOP_LOSS, available_money, available_crypto, last_trade):
if available_money != 0:
#if pe... |
def get_crypto_data(pair, since, api):
# Making a call to the API
# The paramater passed is the type of data that we want to query 'OPEN, HIGH, LOW AND CLOSE' which are the different price points on the chart within a certain timeframe
# Within a given time period, we want to accumulate what the open pric... | The main task of the code is to execute a sell order for a cryptocurrency pair when its price shows a sustained increase above a predefined threshold. It checks for price increases, verifies their persistence after a 3-second delay, recalculates metrics, and triggers a sell if conditions are met. The function avoids tr... | def sell_On_Increase(pair, since, api, open_, close_, loop_cycle, simple_Moving_Average, price_difference, percentage_Increase, percentage_threshold_equivilant, standard_deviation, bollinger_bands, PRICE_THRESHOLD, available_money, available_crypto, last_trade):
if available_crypto != 0:
#if percentage_Inc... |
def get_crypto_data(pair, since, api):
# Making a call to the API
# The paramater passed is the type of data that we want to query 'OPEN, HIGH, LOW AND CLOSE' which are the different price points on the chart within a certain timeframe
# Within a given time period, we want to accumulate what the open pric... | The function `combinational_buy_sell` executes simulated buy/sell trades based on price thresholds and trend confirmation. If holding crypto, it sells if price increases exceed a threshold after a 3-second delay. If holding money, it buys if price drops below a stop-loss threshold. It recalculates metrics (e.g., SMA, p... | def combinational_buy_sell(pair, since, api, open_, close_, loop_cycle, simple_Moving_Average, price_difference, percentage_Increase, percentage_Decrease, percentage_threshold_equivilant, percentage_stop_loss_equivilant, standard_deviation, bollinger_bands, PRICE_THRESHOLD, STOP_LOSS, available_money, available_crypto,... |
def get_crypto_data(pair, since, api):
# Making a call to the API
# The paramater passed is the type of data that we want to query 'OPEN, HIGH, LOW AND CLOSE' which are the different price points on the chart within a certain timeframe
# Within a given time period, we want to accumulate what the open pric... | The function `analyze` evaluates cryptocurrency price data to determine trading actions (buy/sell) using technical indicators. It calculates metrics like moving averages, Bollinger Bands, and price thresholds, then applies a multi-layered strategy: selling when prices surge above thresholds, buying during drops, and ch... | def analyze(pair, since, PRICE_THRESHOLD, STOP_LOSS, api, loop_cycle):
# https://www.codegrepper.com/code-examples/python/colorama+bug+when+trying+to+change+colour+rapidly+python
data = get_crypto_data(pair[0]+pair[1], since, api)
balance = get_fake_balance()
#balance = get_balance() uncomment wh... |
def start_riding(self):
return self.start_stop(DeepRacerEnv.START)
def move(self, angle, throttle):
url = "https://" + self.host + '/api/manual_drive'
data = json.dumps({"angle": angle, "throttle": throttle})
headers = self.get_headers()
response = requests.put(url, headers=heade... | This code advances a car by applying a given action (angle, throttle) for a specified duration. It captures the environment state (image and object detection), checks if the game is over, and returns the observation, zero reward, game status, and empty info. | def step(self, action, step_duration=0.3):
"""
Advances the car for step_duration second
:param action: iterable of (angle (float), throttle(float))
:param step_duration (float or int): number of seconds to ride
:return: next observation, reward, over, info
"""
se... |
def _minmax(self, board: Board, symbol: Symbol) -> int:
moves_scenarios = self.get_moves_and_boards(board, symbol)
value_per_move = {m: self._value_from_memory(s)
for m, s in moves_scenarios}
if self.learning and random.random() < self._epsilon:
# Pick a ran... | The code implements a decision-making function for a game-playing agent. It selects a move using the minmax algorithm and, if learning is enabled, updates memory values by evaluating the next board state and future moves, applying reinforcement learning principles to improve future decisions. | def move(self, board: Board, my_symbol: Symbol) -> int:
self._symbol = self._symbol or my_symbol
move_ = self._minmax(board, my_symbol)
if self.learning:
# Imagine the board after our chosen move.
next_board = self.explore_move(board, my_symbol, move_)
next_m... |
def setHead(self, node):
if self.head is None:
self.head = node
self.tail = node
return
self.insertBefore(self.head, node)
def insertBefore(self, node, nodetoInsert):
#nodetoInsert=Node(nodetoInsert)
if nodetoInsert == self.head or nodetoInsert == self... | This method inserts a node at a specified position in a linked list. If the position is 1, it sets the new node as the head. Otherwise, it traverses the list to locate the node at the given position, then inserts the new node before it. If the position exceeds the list length, it appends the node to the tail. | def insertAtpos(self,pos,nodetoInsert):
if pos==1:
self.setHead(nodetoInsert)
return
counter=1
node=self.head
while node.next is not None and counter!=pos:
counter+=1
node=node.next
if node is not None:
self.insertBefore... |
def print_current_assumptions(self):
"""
Prints all class variables.
:return: None
"""
print("")
print(f"Revenue = ${self.revenue:,}")
print(f"Revenue Growth Rate = {self.revenue_growth_rate * 100}%")
print(f"Time in Years = {self.time_in_years}")
... | The code calculates the Discounted Cash Flow (DCF) value by summing the present values of cash flows over a specified time period and adding a terminal value. It optionally prints detailed calculations if verbose is True, toggles debug mode for output control, and returns the final DCF value formatted to two decimal pl... | def calculate(self, verbose=False):
"""
Using the current variables, calculate the DCF value.
:param verbose: True to display all calculations on CLI; False otherwise
:return: DCF value
"""
self.print_current_assumptions()
if verbose:
self._toggle_d... |
def classification():
train, test = st.tabs(['Train','Test'])
with train:
st.title("Classification / Train data")
spectra = st.file_uploader("**Upload file**", type={"csv", "txt"})
if spectra is not None:
spectra_df = pd.read_csv(spectra)... | The main task of the code is to create a Streamlit sidebar menu for navigating different AI/ML tasks, including Classification, Regressor, NLP, Deep Learning, and Resume sections. It uses radio buttons to let users select a page option, then conditionally executes corresponding functions (e.g., classification(), NLP())... | def main():
st.sidebar.title("Deep Learning/ Data Science/ AI Models")
# page_options = ["Classification", "Regressor", "NLP", "Image", "Voice", "Video", "LLMs"]
page_options = ["Chatbot & NLP" ,"Classification", "Regressor","Deep Learning", "Resume"]
choice = st.sidebar.radio("Select", page_options)
... |
def _get_error_message_from_exception(self, e):
""" This method is used to get appropriate error message from the exception.
:param e: Exception object
:return: error message
"""
error_code = PHANTOM_ERR_CODE_UNAVAILABLE
error_msg = PHANTOM_ERR_MSG_UNAVAILABLE
try... | This function executes a query against a CRITS API endpoint by validating parameters, constructing a request, fetching results, and returning paginated data with metadata. It handles query parsing, integer validation, REST calls, and result formatting for integration with Phantom, including error handling and progress ... | def _handle_run_query(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
query = {}
endpoint = param.get(CRITS_JSON_NEXT_PAGE)
# No page URI provided
if not endpo... |
def _get_filename_filepath(self, action_result, vault_id):
try:
success, message, vault_info = phrules.vault_info(vault_id=vault_id)
vault_info = list(vault_info)[0]
except IndexError:
return action_result.set_status(phantom.APP_ERROR, VAULT_ERR_FILE_NOT_FOUND), None... | The code creates a resource via a REST API by processing input parameters, handling file uploads if provided, and sending structured data. It logs progress, validates inputs, constructs a POST request with dynamic data/files, and returns success/failure status along with the resource ID from the API response. | def _create_resource(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
source = param[CRITS_JSON_SOURCE]
resource = param[CRITS_JSON_RESOURCE]
data_str = param.get(CRIT... |
def _handle_run_query(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
query = {}
endpoint = param.get(CRITS_JSON_NEXT_PAGE)
# No page URI provided
if not endpo... | The function `handle_action` determines the required action from the input parameters, delegates execution to corresponding private methods (e.g., query execution, resource management, connectivity tests), and returns a status code. It acts as a central dispatcher for handling different operations based on the action i... | def handle_action(self, param):
"""Function that handles all the actions
Args:
The json containing config, action and supporting parameters
Handle to the ph_connector, should be used/passed when making ph_connector function calls
Return:
... |
def loadDataSet(csvPath):
dataSet = pandas.read_csv(csvPath)
return dataSet
def partitionDataIntoSets(dataSet):
trainingSet = dataSet.sample(frac = TRAINING_SET_PERCENTAGE)
testSet = dataSet.drop(trainingSet.index)
return trainingSet, testSet
def naiveBayesClassifier(trai... | The code's main task is to load phishing data, split it into training and test sets, apply a Naive Bayes classifier to predict labels, and evaluate the classifier's accuracy using the test set. It performs phishing detection model training and validation in a structured machine learning pipeline. | def run():
phishingData = loadDataSet(CSV_PATH_TO_DATA)
trainingSet, testSet = partitionDataIntoSets(phishingData)
classificationLabels = naiveBayesClassifier(trainingSet, testSet)
evaluateClassifier(testSet, classificationLabels) |
def user_step(self, user_choice: str) -> None:
match user_choice:
case "w":
self.player_commands.move_up()
case "a":
self.player_commands.move_left()
case "s":
self.player_commands.move_down()
case "d":
... | This code runs a turn-based game loop where the player and monsters take alternating steps. It checks game status (win/loss), updates the map display, handles user input for movement, and clears the screen after each turn. The loop continues until the player or monsters are defeated, displaying appropriate messages and... | def run(self) -> None:
monster_status, player_status = True, True
while Game.game:
self.map.show_map()
if not player_status:
Game.game = False
input(f"{Phrase.LOSE.value}\n{Phrase.EXIT.value}")
break
monsters_last = su... |
def _get_measurements_info():
# subjects_in_csv is a dictionary
subjects_in_csv = _get_subjects_metadata()
# get the dictionary of all measurements available.
# all files with the same file name but different extensions
# correspond to the same measurement
subjects = dict()
data_fi... | The code processes ECG data from multiple subjects, validating signal lengths, preparing records with metadata (age, target HR), calculating window parameters for segmentation, and exporting processed data while tracking the longest signal. It iterates through measurements, skips invalid ones, and adjusts windowing bas... | def main():
topic_idx = 0
max_signal_length = 0
subjects = _get_measurements_info()
for subject_number in subjects:
if 'measurements' not in subjects[subject_number]:
continue
else:
print(subject_number + ':')
for measurement in subj... |
def custom_add_edge(self,x,y):
self.G.add_edge(x,y)
if self.selfloop_analysis:
if x == y:
print("add ", x, y)
def add_steiner_node(self,x,y,z):
r = self.nextroots.pop(-1)
#check if we need to make W bigger
if r >= self.S:
new_s = int(1.3*self.S)
new_w = np.zeros((new_s,new... | This function processes a list of nodes (V) by either adding edges or introducing a Steiner node to partition the graph. If V has one node, it connects x to it. For multiple nodes, it randomly selects two (y,z), creates a Steiner node linking x,y,z, then sorts remaining nodes into zones based on the Steiner node. The t... | def zone1_helper(self,V,x):
if len(V) == 0:
return []
if len(V) == 1:
self.custom_add_edge(x,V[0])
if self.debug:
print("Zone 1")
print(x,V[0])
print()
return []
p = np.random.permutation(len(V))
y = V[p[0]]
z = V[p[1]]
V_rem = []
f... |
def custom_remove_edge(self,x,y):
self.G.remove_edge(x,y)
if self.selfloop_analysis:
if x == y:
print("remove ", x, y)
def add_steiner_node(self,x,y,z):
r = self.nextroots.pop(-1)
#check if we need to make W bigger
if r >= self.S:
new_s = int(1.3*self.S)
new_w = np.zeros((... | This function processes a list of nodes (V) to determine zones by identifying a minimal node (z), modifying the graph by removing an edge between x and y, adding a Steiner node to connect x, y, and z, then sorting remaining nodes into zones. It returns the partitioned zones after these operations. | def zone2_helper(self,V,x,y):
if len(V) == 0:
return []
idx = self.W[y,V].argmin()
p = np.arange(0,len(V))
p[0] = idx
p[idx] = 0
z = V[p[0]]
V_rem = []
for i in range(1,len(V)):
V_rem.append(V[p[i]])
if self.G.has_edge(x,y): # To make sure not returning an error - emp... |
def add_steiner_node(self,x,y,z):
r = self.nextroots.pop(-1)
#check if we need to make W bigger
if r >= self.S:
new_s = int(1.3*self.S)
new_w = np.zeros((new_s,new_s))
new_w[:self.S,:self.S] = self.W
self.S = new_s
self.W = new_w
self.G.add_node(r)
self.custom_add_edg... | The main task of the code is to construct a tree structure with Steiner nodes by iteratively connecting points in zones, updating edge weights in a graph, and ensuring the result is a valid tree without self-loops. It initializes a weight matrix, adds Steiner nodes to connect points, processes zones recursively to spli... | def learn_tree(self, remove_selfloop = True):
# Create the weight matrix for the output tree.
# It is bigger than n x n since the algorith
# adds steiner nodes.
start = time.time()
self.W = np.zeros((self.S,self.S), dtype = self.d.dtype)
self.W[:self.n,:self.n] = self.d
# Pick the inital... |
def with_timing(subject, timing, pres):
to_adjust = [("two-back", "2-Back Start"),
("three-back", "3-Back Start"),
("stroop-log", "Stroop1 Practice")]
logs = read_raw(subject, pres)
time = timing[timing["File Prefix"] == subject]
for test,col in to_adjust:
df = ... | This function processes EEG data for specified experimental conditions by loading user data, filtering it, creating event markers for target trials, and generating epochs. It returns filtered EEG data, epochs, and event markers for further analysis, with optional event-only output. | def get_user_data(user, timing, eeg_data_folder, pres, tmin = -.2, tmax = .7, l_freq = 1., h_freq = 50., targets = ["two-back", "three-back"], events_only = False):
u = with_timing(user, timing, pres)
events = make_all_events(u, targets)
if events_only:
return events
# For calculating epochs w... |
def getRawData():
print(" Loading images.")
print(" Content image URL: \"%s\"." % CONTENT_IMG_PATH)
print(" Style image URL: \"%s\"." % STYLE_IMG_PATH)
cImg = load_img(CONTENT_IMG_PATH)
tImg = cImg.copy()
sImg = load_img(STYLE_IMG_PATH)
print(" Images have been loaded.")... | The main task of the code is to perform image style transfer by preprocessing three input images (content, style, and transfer) and applying a style transfer algorithm to generate a new image that combines the content of the content image with the artistic style of the style image. | def main():
print("Starting style transfer program.")
raw = getRawData()
cData = preprocessData(raw[0]) # Content image.
sData = preprocessData(raw[1]) # Style image.
tData = preprocessData(raw[2]) # Transfer image.
styleTransfer(cData, sData, tData)
print("Done. Goodbye.") |
def _check_keydown_events(self, event):
"""Respond to key presses."""
if event.key == K_RIGHT:
self.ship.moving_right = True
elif event.key == K_LEFT:
self.ship.moving_left = True
elif event.key == K_SPACE:
self._fire_bullet()
elif event.key ==... | The main task of the code is to process Pygame events such as window closure, key presses, key releases, and mouse clicks. It triggers corresponding actions: saving high scores and exiting on window closure, delegating key events to _check_keydown_events/_check_keyup_events, and checking mouse clicks on the play button... | def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
# closing the window quits the game
if event.type == QUIT:
self.stats.save_high_score()
sys.exit()
# check certain event pased on ... |
def _check_fleet_edges(self):
"""Respond appropriately if any aliens have reached an edge"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""Respond to the Ship being hit by an Al... | This method updates alien positions by checking fleet edges and moving aliens. It detects collisions between the player's ship and aliens, triggering a ship-hit response, and checks if any aliens reach the screen's bottom, likely initiating game-ending logic. | def _update_aliens(self):
"""
Check if the fleet is at an edge,
then update the positions of all aliens in the fleet.
"""
self._check_fleet_edges()
self.aliens.update()
# look for Alien-Ship collisions
if pygame.sprite.spritecollideany(self.ship, self.ali... |
def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
# closing the window quits the game
if event.type == QUIT:
self.stats.save_high_score()
sys.exit()
# check certain event pased on ... | The code defines a method `run_game` that initiates the main game loop. It continuously checks for events, updates game elements like the ship, bullets, and aliens if the game is active, and refreshes the screen to render changes. The loop runs indefinitely, maintaining game state and responsiveness until terminated. | def run_game(self):
"""Starts the main game loop."""
while True:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen() |
def highest_intersecting_brick_below(bn):
"""Find highest intersecting brick that is below brick bn"""
brick = bricks[bn]
brick_bottom = min_end(brick,'z')
highest_z = 0
highest = 'ground'
for tb, test_brick in enumerate(bricks):
if tb == bn:
continue # skip same brick... | This function determines the position and support status of a brick when dropped. It checks for the highest intersecting brick below the target brick (bn). If none exists, the brick is placed on the ground (z=1) and marked as ground-supported. Otherwise, it's positioned atop the highest brick, adjusting its z-coordinat... | def drop_brick(bn):
brick = bricks[bn]
hb = highest_intersecting_brick_below(bn)
if hb == 'ground':
drop_to_z(bn,1)
brick[0] = 'S' # brick is supported by the ground
brick[3].append('ground')
else:
high_brick = bricks[hb]
hbz = max_end(high_brick,'z')
... |
def update():
""" Updates the particle and button """
start_button.update()
gen_button.update()
def events():
""" Checks for and handle events """
global graph, running, simulating
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if event.ty... | The main task of the code is to simulate an ant colony's iteration by exploring a graph using current pheromone trails, updating the best path if a shorter distance is found, and refreshing the visualization. It iterates through each ant, checks simulation status, updates pheromones, and initializes a new ant batch aft... | def run_iteration():
""" Runs the ant search on the current batch of ants (i.e. explores the graph using
the current pheromone trails. This function also draws the best path onto the screen."""
global ants, best_path, best_path_distance, simulating
for ant in ants:
# Checks if the simulation... |
def run_iteration():
""" Runs the ant search on the current batch of ants (i.e. explores the graph using
the current pheromone trails. This function also draws the best path onto the screen."""
global ants, best_path, best_path_distance, simulating
for ant in ants:
# Checks if the simulation... | The code defines a main game loop that runs while 'running' is True. It controls the frame rate with clock.tick(FPS), executes simulation steps if enabled, updates game state, processes events, and renders the game screen. The loop ensures continuous game execution, handling simulation logic, state changes, user input,... | def run():
""" Main 'game' loop """
while running:
clock.tick(FPS)
if simulating:
run_iteration()
update()
events()
paint() |
def get_target_angle(self):
location = self.actor.get_actor_location()
angle = self.actor.GetTargetAngleFromPos(FVector(self.target_x, self.target_y, location.z))[0]
nangle = angle / 360 + .5
return nangle
def get_target_dist(self):
location = self.actor.get_actor_location()
... | This code executes a single time step in a reinforcement learning environment, gathering observations, selecting actions via a policy with exploration noise, applying actions to an agent (e.g., a bipedal walker), calculating rewards based on proximity to a target, balance, and joint positions, and updating a replay buf... | def tick(self, delta_time):
self.ep_frame+=1
self.total_frame += 1
#############get observation#############
obs = self.actor.update_observation()[0]
# if self.first_frame:
# obs2 = obs+obs
# self.first_frame = False
# else:
# obs2 = ... |
def getKnownCollisionObjects(self):
self._mutex.acquire()
l = copy.deepcopy(self._collision)
self._mutex.release()
return l
def removeCollisionObject(self, name, use_service=True):
""" Remove an object. """
o = CollisionObject()
o.header.stamp = rospy.Time.now()
... | The code's main task is to clear all collision and attached objects from the environment. It iterates through known collision objects, removing each, then does the same for attached objects. Finally, it waits for synchronization to ensure all removals are completed. | def clear(self):
for name in self.getKnownCollisionObjects():
self.removeCollisionObject(name, True)
for name in self.getKnownAttachedObjects():
self.removeAttachedObject(name, True)
self.waitForSync() |
def run(self, sum_qry=None, **kwargs):
"""Run the built query.
* If the ``sum_qry`` argument is not given value,
run underlying query as it is.
* If a value is given, enclose the underlying query into a with
clause, attach the summary query after it, run the full query.
... | The function `cols` retrieves column names from a subquery table. It accepts an `out` parameter to control output mode: `None` returns column names as a list, `1` prints the full query, and `2` returns the query as a string. It handles SQL queries by executing or formatting them based on the mode, enabling users to ins... | def cols(self, out=None):
"""Fetch column names of the sub query table.
Args
--------
out: int
Output mode. None to run full query, 1 to print full query,
2 to return full query as str. Default None.
Returns
-------
Column names as list o... |
def run(self, sum_qry=None, **kwargs):
"""Run the built query.
* If the ``sum_qry`` argument is not given value,
run underlying query as it is.
* If a value is given, enclose the underlying query into a with
clause, attach the summary query after it, run the full query.
... | The function `dist` generates SQL queries to count distinct values in specified columns (or concatenated column combinations) of a database table. It accepts column names as arguments, constructs `count(distinct ...)` expressions, and returns results as a pandas Series. The `out` parameter controls output mode: `None` ... | def dist(self, *args, out=None):
"""Count number of distinct occurances of data.
Works on specified columns, or combination of columns, of the sub query table.
Args
----------
*args : str or [str]
Either column names as str, or iterator of column name str.
o... |
def run(self, sum_qry=None, **kwargs):
"""Run the built query.
* If the ``sum_qry`` argument is not given value,
run underlying query as it is.
* If a value is given, enclose the underlying query into a with
clause, attach the summary query after it, run the full query.
... | The main task of the code is to fetch the top 5 rows from a sub-query table using SQL, with flexibility in output mode. It constructs a query (`SELECT * FROM x LIMIT 5` or Oracle-compatible `ROWNUM <= 5`), then executes, prints, or returns the query as a string based on the `out` parameter (None, 1, or 2). The function... | def head(self, out=None):
"""Fetch top 5 rows of the sub query table.
Args
-------
out: int
Output mode. None to run full query, 1 to print full query,
2 to return full query as str. Default None.
Returns
-------
pandas.DataFrame
... |
def run(self, sum_qry=None, **kwargs):
"""Run the built query.
* If the ``sum_qry`` argument is not given value,
run underlying query as it is.
* If a value is given, enclose the underlying query into a with
clause, attach the summary query after it, run the full query.
... | The function `len` calculates the number of rows in a database table by executing a SQL `COUNT(1)` query. It accepts an `out` parameter to control output mode: `None` returns the count as an integer, `1` prints the SQL query, and `2` returns the query as a string. This method is used to determine the size of a dataset ... | def len(self, out=None):
"""Length of the sub query table.
Args
-------
out: int
Output mode. None to run full query, 1 to print full query,
2 to return full query as str. Default None.
Returns
-------
int
Examples
------... |
def run(self, sum_qry=None, **kwargs):
"""Run the built query.
* If the ``sum_qry`` argument is not given value,
run underlying query as it is.
* If a value is given, enclose the underlying query into a with
clause, attach the summary query after it, run the full query.
... | The `mimx` method retrieves the maximum and minimum values of a specified column from a database table named 'x' using SQL. It accepts a column name `col` and an optional `out` parameter to control output mode: `None` (default) returns results as a pandas Series, `1` prints the query, and `2` returns the query as a str... | def mimx(self, col, out=None):
"""Fetch maximum and minimum values of a column.
Args
----------
col : str
Column name as str.
out: int
Output mode. None to run full query, 1 to print full query,
2 to return full query as str. Default None.
... |
def run(self, sum_qry=None, **kwargs):
"""Run the built query.
* If the ``sum_qry`` argument is not given value,
run underlying query as it is.
* If a value is given, enclose the underlying query into a with
clause, attach the summary query after it, run the full query.
... | The `top` method fetches the first row of a subquery result, supporting three output modes: executing the query (default), printing it, or returning it as a string. It constructs SQL queries with dialect-specific syntax (`rownum<=1` for Oracle-compatible, `limit 1` otherwise) and returns the result as a pandas Series w... | def top(self, out=None):
"""Fetch top row of the sub query table.
Args
-------
out: int
Output mode. None to run full query, 1 to print full query,
2 to return full query as str. Default None.
Returns
-------
pandas.Series
Exampl... |
def run(self, sum_qry=None, **kwargs):
"""Run the built query.
* If the ``sum_qry`` argument is not given value,
run underlying query as it is.
* If a value is given, enclose the underlying query into a with
clause, attach the summary query after it, run the full query.
... | The `valc` method generates and executes a SQL query to compute value counts of specified columns, with optional custom aggregations and sorting. It groups data by `group_by`, calculates row counts (if `n=True`), applies user-defined aggregations (`agg`), and sorts results (`order_by`). The output mode (`out`) controls... | def valc(self, group_by, agg=None, order_by=None, n=True, out=None):
"""Value count of a column or combination of columns.
A value count is a
group by query, with total number of row of each group calculated.
Also allow custom summary calculation, and custom order by clauses
to ... |
def cols(self, out=None):
"""Fetch column names of the sub query table.
Args
--------
out: int
Output mode. None to run full query, 1 to print full query,
2 to return full query as str. Default None.
Returns
-------
Column names as list o... | The code calculates an Oracle-specific hash for table columns to detect data changes. It accepts column names or defaults to all columns, constructs a SQL query using `ora_hash`, and returns the hash value, prints the query, or returns the query string based on the `out` parameter. The hash is sensitive to data changes... | def hash(self, *args, out=None):
"""Calculate a simple oracle hash for table.
Arrive at a indicative hash value for a number of columns or all columns of
a sub query table.
Hash value is a number or symbol that is calculated from data
, and is sensitive to any small changes in d... |
def crop_image(self, image, lines=None):
"""
Method to crop image. Crops horizontally by crop_range_w. Crops the specified number of lines
vertically if `lines` is defined. Else crops by crop_range_h.
:param image: Image to be cropped
:param lines: Number of rows of pixels in cr... | The code processes an input image to determine left and right wheel speed fractions (0-1) for navigation, using different lane detection methods (e.g., one-row, line prediction, many-rows, hybrid). It crops the image, applies Canny edge detection, and calculates speeds based on detected lanes. Returns speed fractions a... | def get_speed_fractions(self, image):
"""
Method to get left and right speeds as fractions.
:param image: Image to be used to make the decision.
:return: Left wheel speed, Right wheel speed (range: 0 - 1; None if couldn't find edges), canny image.
"""
cropped, h, w = se... |
def total_spin(spinorbs, nspat):
return sum(spins(spinorbs, nspat))
def spin(spinorb, nspat):
return spinorb%2 if nspat is None else spinorb//nspat
def spat(spinorb, nspat):
return spinorb//2 if nspat is None else spinorb%nspat | This function computes the overlap of a spin-adapted CI vector after applying a sequence of spin-resolved creation and destruction operators, ensuring spin conservation. It transforms the input CI vector by sequentially annihilating electrons from specified orbitals (desinds) and creating them in others (creinds), whil... | def pyscf_spin_resolved_element(civec, nelec, ncas, creinds, desinds):
'''
make_rdm methods should never call this method with spin-symmetry
non-conserving orbital indices
'''
assert total_spin(creinds, None)==total_spin(desinds, None)
ciket = civec.copy()
fcre = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.