code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function validate_password self str begin return call make_password str end function
def validate_password(self, str) -> str: return make_password(str)
Python
nomic_cornstack_python_v1
function evaluate system=string grep begin if system == string grep begin with open string output/bool_retrieval_json_output.json as system begin set data = load json system end end else if system == string index begin with open string output/index_based_bool_retrieval.json as system begin set data = load json system e...
def evaluate(system='grep'): if system == 'grep': with open('output/bool_retrieval_json_output.json') as system: data = json.load(system) elif system == 'index': with open('output/index_based_bool_retrieval.json') as system: data = json.load(system) elif system == 'lu...
Python
nomic_cornstack_python_v1
function solution array commands begin set answer = list for tuple i j k in commands begin set temp = array at slice i - 1 : j : append answer sorted temp at k - 1 end return answer end function
def solution(array, commands): answer = [] for i, j, k in commands: temp = array[i - 1:j] answer.append(sorted(temp)[k - 1]) return answer
Python
zaydzuhri_stack_edu_python
function delete_table self begin set table_1 = call Table string Sensor delete print string Table status : sensor : table_status set table_2 = call Table string Courses delete print string Table status course : table_status end function
def delete_table(self): self.table_1 = dynamodb.Table('Sensor') self.table_1.delete() print("Table status : sensor : ", self.table_1.table_status) self.table_2 = dynamodb.Table('Courses') self.table_2.delete() print("Table status course : ", self.table_2.table_status)
Python
nomic_cornstack_python_v1
function one_hot org_input begin comment Create the embedding list for f in range num_feature begin set num_cat_value = schema at f if num_cat_value == 1 begin pass end else if num_cat_value > 1 begin set embed_dict at f = call Variable call identity num_cat_value dtype=float32 trainable=false name=string embed_ + stri...
def one_hot(org_input): # Create the embedding list for f in range(Config.num_feature): num_cat_value = Config.schema[f] if num_cat_value == 1: pass elif num_cat_value > 1: embed_dict[f] = tf.Variable(np.identity( n...
Python
nomic_cornstack_python_v1
function taskdetail_create name tsk td_id=none begin return call taskdetail_create name tsk td_id end function
def taskdetail_create(name, tsk, td_id=None): return IMPL.taskdetail_create(name, tsk, td_id)
Python
nomic_cornstack_python_v1
import math function complex_modulus real imaginary begin set real_squared = real ^ 2 set imaginary_squared = imaginary ^ 2 set modulus_square = real_squared + imaginary_squared set modulus = square root modulus_square return modulus end function comment Calculate the modulus of (7/4 + 3i) set real_part = 7 / 4 set ima...
import math def complex_modulus(real, imaginary): real_squared = real ** 2 imaginary_squared = imaginary ** 2 modulus_square = real_squared + imaginary_squared modulus = math.sqrt(modulus_square) return modulus # Calculate the modulus of (7/4 + 3i) real_part = 7 / 4 imaginary_part = 3 result = com...
Python
dbands_pythonMath
import pandas as pd comment load and clean data set crimes = read csv string Crimes_-_2001_to_present.csv set community_populations = read csv string community_populations.csv set socio = read csv string Census_Data_-_Selected_socioeconomic_indicators_in_Chicago__2008___2012.csv set socio = drop missing socio subset=li...
import pandas as pd # load and clean data crimes = pd.read_csv('Crimes_-_2001_to_present.csv') community_populations = pd.read_csv('community_populations.csv') socio = pd.read_csv('Census_Data_-_Selected_socioeconomic_indicators_in_Chicago__2008___2012.csv') socio = socio.dropna(subset=['Community Area Number']) # co...
Python
zaydzuhri_stack_edu_python
function _parse_file_blocks fh begin comment first line is n_atoms set n_atoms = integer strip read line fh comment second line is comments set comments = split strip read line fh set molecule = list comment next n_atom lines are element positions for i in range n_atoms begin append molecule split replace strip read l...
def _parse_file_blocks(fh): n_atoms = int(fh.readline().strip()) # first line is n_atoms comments = fh.readline().strip().split() # second line is comments molecule = [] for i in range(n_atoms): # next n_atom lines are element positions molecule.append(fh.readline().stri...
Python
nomic_cornstack_python_v1
function encode_file self path begin set waveform = call load_audio path set batch = unsqueeze waveform 0 set rel_length = tensor list 1.0 set results = call encode_batch batch rel_length return results at string embeddings end function
def encode_file(self, path): waveform = self.load_audio(path) batch = waveform.unsqueeze(0) rel_length = torch.tensor([1.0]) results = self.encode_batch(batch, rel_length) return results['embeddings']
Python
nomic_cornstack_python_v1
function enforce_time_limit self site begin string Raises `brozzler.ReachedTimeLimit` if appropriate. if time_limit and time_limit > 0 and call elapsed > time_limit begin debug string site FINISHED_TIME_LIMIT! time_limit=%s elapsed=%s %s time_limit call elapsed site raise ReachedTimeLimit end end function
def enforce_time_limit(self, site): ''' Raises `brozzler.ReachedTimeLimit` if appropriate. ''' if (site.time_limit and site.time_limit > 0 and site.elapsed() > site.time_limit): self.logger.debug( "site FINISHED_TIME_LIMIT! time_limit=%s " ...
Python
jtatman_500k
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import os call system string apt-get install figlet call system string clear call system string figlet Zafiyet Analiz print string Sunucu Zafiye Analizi Aracına Hoşgeldin instagram = zumrudu_anka_team print string Bu Araç Treangle Tarafından Oluşturulmuştur set...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os os.system("apt-get install figlet") os.system("clear") os.system("figlet Zafiyet Analiz") print("Sunucu Zafiye Analizi Aracına Hoşgeldin instagram = zumrudu_anka_team") print("Bu Araç Treangle Tarafından Oluşturulmuştur ") hedefip = input("Hedef Ip girin :...
Python
zaydzuhri_stack_edu_python
function show_privileges self begin print string Privileges of the admin: for privilege in privileges begin print title privilege end end function
def show_privileges(self): print("\nPrivileges of the admin:") for privilege in self.privileges: print(privilege.title())
Python
nomic_cornstack_python_v1
comment Copyright (c) 2021. Clinton Fernandes (clintonf@gmail.com import argparse from fernet_encrypt_decrypt import * function create_arguments begin string Parses command line arguments. :return: { argparse } set parser = call ArgumentParser call add_argument string message help=string message to encrypt call add_arg...
# Copyright (c) 2021. Clinton Fernandes (clintonf@gmail.com import argparse from fernet_encrypt_decrypt import * def create_arguments() -> argparse: f""" Parses command line arguments. :return: {argparse} """ parser = argparse.ArgumentParser() parser.add_argument("message", help="message...
Python
zaydzuhri_stack_edu_python
function saiWaitFdbAge timeout begin print string Waiting for fdb entry to age set aging_interval_buffer = 10 sleep timeout + aging_interval_buffer end function
def saiWaitFdbAge(timeout): print("Waiting for fdb entry to age") aging_interval_buffer = 10 time.sleep(timeout + aging_interval_buffer)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Mon Jan 27 22:06:52 2020 @author: Cylita string This file is run to create the metrics to be used to validate the approach using GloVe embeddings and Word Mover's Distance (see Data Viz notebook). comment required functions and py files impor...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 27 22:06:52 2020 @author: Cylita """ ''' This file is run to create the metrics to be used to validate the approach using GloVe embeddings and Word Mover's Distance (see Data Viz notebook). ''' #required functions and py files import pandas as p...
Python
zaydzuhri_stack_edu_python
import numpy as np from numpy import genfromtxt set X = array 0 float64 set dat = call genfromtxt string chb_01_4.csv dtype=float delimiter=string , set numrows = length dat set numcols = length dat at 0 set j = 0 while j < numcols - 1 begin set i = 0 while i < numrows begin if i == 0 ? j == 0 begin set X = transpose d...
import numpy as np from numpy import genfromtxt X = np.array(0,np.float64) dat = genfromtxt('chb_01_4.csv',dtype =(float), delimiter=',') numrows = len(dat) numcols = len(dat[0]) j = 0 while j<(numcols-1): i = 0 while i<numrows: if ((i == 0)&(j == 0)): X = dat[i:i+256,j].transpose() y = dat[i,23] else : ...
Python
zaydzuhri_stack_edu_python
import numpy as np import csv import matplotlib.pyplot as plt class AdaBoost begin function __init__ self training_set begin set training_set = training_set set N = length training_set set weights = ones N / N set RULES = list set ALPHA = list set HORIZONTAL_LINES = list set VERTICAL_LINES = list end function funct...
import numpy as np import csv import matplotlib.pyplot as plt class AdaBoost: def __init__(self, training_set): self.training_set = training_set self.N = len(self.training_set) self.weights = np.ones(self.N) / self.N self.RULES = [] self.ALPHA = [] self.HORIZONTAL_...
Python
zaydzuhri_stack_edu_python
function mul x y begin string Multiply arguments and return the result. return x * y end function
def mul(x, y): """Multiply arguments and return the result. """ return x * y
Python
zaydzuhri_stack_edu_python
if otavio < min ian bruno begin print string Otavio end else if bruno < min ian otavio begin print string Bruno end else if ian < min otavio bruno begin print string Ian end else begin print string Empate end
if otavio < min(ian, bruno): print("Otavio") elif bruno < min(ian, otavio): print("Bruno") elif ian < min(otavio, bruno): print("Ian") else: print("Empate")
Python
zaydzuhri_stack_edu_python
function grid_slice amin amax shape bmin bmax begin string Give a slice such that [amin, amax] is in [bmin, bmax]. Given a grid with shape, and begin and end coordinates amin, amax, what slice do we need to take such that it minimally covers bmin, bmax. amin, amax = 0, 1; shape = 4 0 0.25 0.5 0.75 1 | | | | | bmin, bma...
def grid_slice(amin, amax, shape, bmin, bmax): """Give a slice such that [amin, amax] is in [bmin, bmax]. Given a grid with shape, and begin and end coordinates amin, amax, what slice do we need to take such that it minimally covers bmin, bmax. amin, amax = 0, 1; shape = 4 0 0.25 0.5 0.75 1 ...
Python
jtatman_500k
function GetnetCDFInfobyName in_filename var_name begin comment Open netCDF file set src_ds = open in_filename if src_ds is none begin print string Open failed exit end if length call GetSubDatasets > 1 begin comment If exists more than one var in the NetCDF set subdataset = string NETCDF:" + in_filename + string ": + ...
def GetnetCDFInfobyName(in_filename,var_name): #Open netCDF file src_ds = gdal.Open(in_filename) if src_ds is None: print("Open failed") sys.exit() if len(src_ds.GetSubDatasets()) > 1: #If exists more than one var in the NetCDF subdataset = 'NETCDF:"'+in_filename+'":'+var...
Python
nomic_cornstack_python_v1
function read_file filename begin with open filename as fobj begin return read lines fobj end end function
def read_file(filename): with open(filename) as fobj: return fobj.readlines()
Python
nomic_cornstack_python_v1
function get_key val begin for tuple key value in items D begin if val == value begin return key end end end function for i in range 3 begin set s = input if s at 1 == string > begin set D at s at 0 = D at s at 0 + 1 end comment print("IF",D[s[0]]) if s at 1 == string < begin set D at s at - 1 = D at s at - 1 + 1 end e...
def get_key(val): for key, value in D.items(): if val == value: return key for i in range(3): s=input() if s[1]=='>': D[s[0]]+=1 #print("IF",D[s[0]]) if s[1]=='<': D[s[-1]]+=1 #print("ELSE",get_key(D[s[-1]])) if D['A']==1 and D['B']...
Python
zaydzuhri_stack_edu_python
import os from flask import Flask , render_template , request from models import * set app = call Flask __name__ set config at string SQLALCHEMY_DATABASE_URI = call getenv string DATABASE_URL set config at string SQLALCHEMY_TRACK_MODIFICATIONS = false call init_app app function main begin set flights = all for flight i...
import os from flask import Flask, render_template, request from models import * app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL") app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) def main(): flights = Flight.query.all() for flight in flights: ...
Python
zaydzuhri_stack_edu_python
import tkinter as tk import numpy as np class GridFrame extends Frame begin function __init__ self parent grid_size=5 size=32 live_color=string black dead_color=string white begin set numerical_grid = zeros tuple grid_size grid_size set rows = grid_size set columns = grid_size set size = size set live_color = live_colo...
import tkinter as tk import numpy as np class GridFrame(tk.Frame): def __init__(self, parent, grid_size=5, size=32, live_color="black", dead_color="white"): self.numerical_grid = np.zeros((grid_size,grid_size)) self.rows = grid_size self.columns = grid_size self.size = size ...
Python
zaydzuhri_stack_edu_python
string * @author nhphung from abc import ABC , abstractmethod , ABCMeta from dataclasses import dataclass from typing import List , Tuple from AST import * from Visitor import * from StaticError import * from functools import * import copy class Type extends ABC begin set __metaclass__ = ABCMeta decorator staticmethod ...
""" * @author nhphung """ from abc import ABC, abstractmethod, ABCMeta from dataclasses import dataclass from typing import List, Tuple from AST import * from Visitor import * from StaticError import * from functools import * import copy class Type(ABC): __metaclass__ = ABCMeta @staticmethod def getTypeF...
Python
zaydzuhri_stack_edu_python
function SetTransformInput self _arg begin return call itkResampleImageFilterVIUS3VIUS3_SetTransformInput self _arg end function
def SetTransformInput(self, _arg: 'itkDataObjectDecoratorTD33') -> "void": return _itkResampleImageFilterPython.itkResampleImageFilterVIUS3VIUS3_SetTransformInput(self, _arg)
Python
nomic_cornstack_python_v1
function find_common_elements list1 list2 begin comment Remove duplicates from list1 set list1 = call remove_duplicates list1 comment Remove duplicates from list2 set list2 = call remove_duplicates list2 comment Sort both lists set list1 = call sort_list list1 set list2 = call sort_list list2 comment Find common elemen...
def find_common_elements(list1, list2): # Remove duplicates from list1 list1 = remove_duplicates(list1) # Remove duplicates from list2 list2 = remove_duplicates(list2) # Sort both lists list1 = sort_list(list1) list2 = sort_list(list2) # Find common elements common_elements = [] ...
Python
jtatman_500k
function delete self begin try begin call delete_loadbalancer call _remove_cached_info end except CalledProcessError begin raise call OpenStackLBError action=string delete end end function
def delete(self): try: self._impl.delete_loadbalancer() self._remove_cached_info() except subprocess.CalledProcessError: raise OpenStackLBError(action="delete")
Python
nomic_cornstack_python_v1
string Используя словарь, напишите программу, которая выведет на экран название дня недели по его номеру. (1 - «Monday») set day = integer input string Введите номер дня недели (1-Monday...7-Sunday): if day < 1 or day > 7 begin print string Введен некорректный номер! end else begin set week = dict 1 string Monday ; 2 s...
""" Используя словарь, напишите программу, которая выведет на экран название дня недели по его номеру. (1 - «Monday») """ day = int(input("Введите номер дня недели (1-Monday...7-Sunday): ")) if day < 1 or day > 7: print("Введен некорректный номер!") else: week = { 1: "Monday", ...
Python
zaydzuhri_stack_edu_python
import io import sys set stdout = call StringIO set buffer = call StringIO import app import re import os import pytest decorator call it string Use the function print() function test_for_file_output capsys begin set path = directory name path absolute path path __file__ + string /app.py with open path string r as cont...
import io import sys sys.stdout = buffer = io.StringIO() import app import re import os import pytest @pytest.mark.it('Use the function print()') def test_for_file_output(capsys): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: content = content_file.re...
Python
zaydzuhri_stack_edu_python
function twos_complement_8bit b begin if b >= 256 begin raise call ValueError string b must fit inside 8 bits end if b ? 1 ? 7 begin comment Negative number, calculate its value using two's-complement. return b - 1 ? 8 end else begin comment Positive number, do not touch. return b end end function
def twos_complement_8bit(b: int) -> int: if b >= 256: raise ValueError("b must fit inside 8 bits") if b & (1 << 7): # Negative number, calculate its value using two's-complement. return b - (1 << 8) else: # Positive number, do not touch. return b
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment coding: utf-8 import sys import time from bilingual_data import Bicorpus , Bidictionary from _nlg import solvenlg , verifnlg comment ...!....1....!....2....!....3....!....4....!....5....!....6....!....7....!....8 set __author__ = string Yves Lepage <yves.lepage@waseda.jp> set tuple __da...
#!/usr/bin/python # coding: utf-8 import sys import time from bilingual_data import Bicorpus, Bidictionary from _nlg import solvenlg, verifnlg #...!....1....!....2....!....3....!....4....!....5....!....6....!....7....!....8 ################################################################################ __author__ ...
Python
zaydzuhri_stack_edu_python
from board import SCL , SDA import busio from PIL import Image , ImageDraw , ImageFont import adafruit_ssd1306 import RPi.GPIO as GPIO import pygame from gpiozero import Button import time import random import game_func as func comment button_config set attack_pin = 18 set down_pin = 22 set up_pin = 27 set start_pin = ...
from board import SCL, SDA import busio from PIL import Image, ImageDraw, ImageFont import adafruit_ssd1306 import RPi.GPIO as GPIO import pygame from gpiozero import Button import time import random import game_func as func # button_config attack_pin = 18 down_pin = 22 up_pin = 27 start_pin = 17 # GIP.PUD_UP mode ->...
Python
zaydzuhri_stack_edu_python
function send_order_update self fields mapped=false begin debug string { self } send_order_update( { fields } ) set symbol = fields at string symbol if not get fields string cusip begin if mapped begin debug string { self } order update is still missing CUSIP after mapping, continuing... end else begin debug string { s...
def send_order_update(self, fields, mapped=False): self.debug(f"{self} send_order_update({fields})") symbol = fields['symbol'] if not fields.get('cusip'): if mapped: self.debug(f"{self} order update is still missing CUSIP after mapping, continuing...") els...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python set bins = list 0.0 0.21 0.42 0.63 0.84 1.05 1.37 1.52 1.74 1.95 2.18 2.4 set x = string \slide{ $\mu^{%s}$: bin %d ($%.2f<\%s<%.2f$) } { \colb[T] \column{.5\textwidth} C-side (top: W; bottom: Z) \centering \includegraphics[width=0.66\textwidth]{dates/20130306/figures/etaphi/W_%d_C_stack_l_...
#!/usr/bin/env python bins = [0.0,0.21,0.42,0.63,0.84,1.05,1.37,1.52,1.74,1.95,2.18,2.4] x=r""" \slide{ $\mu^{%s}$: bin %d ($%.2f<\%s<%.2f$) } { \colb[T] \column{.5\textwidth} C-side (top: W; bottom: Z) \centering \includegraphics[width=0.66\textwidth]{dates/20130306/figures/etaphi/W_%d_C_stack_l_%s_%s} \\ \include...
Python
zaydzuhri_stack_edu_python
comment ************************************************************************************************** comment Created by Carrik McNerlin comment May 5, 2021 comment This file contains functions pertaining to the boards. comment That includes creating both the hidden and the user board, printing a board, and reveal...
#************************************************************************************************** # Created by Carrik McNerlin # May 5, 2021 # # This file contains functions pertaining to the boards. # That includes creating both the hidden and the user board, printing a board, and revealing spaces. #****************...
Python
zaydzuhri_stack_edu_python
function convert_file filepath new_extension begin if filepath and new_extension begin set path = call Path filepath if exists path begin try begin set new_path = call Path parents at 0 name + new_extension rename new_path debug string Converted file ' { path } ' to ' { new_extension } ' return true end except OSError ...
def convert_file(filepath: str, new_extension: str) -> bool: if filepath and new_extension: path = Path(filepath) if path.exists(): try: new_path = Path(path.parents[0], path.name + new_extension) path.rename(new_path) ...
Python
nomic_cornstack_python_v1
function printProb n begin set probs = list comprehension list 0 * 6 * n + 1 for i in range 2 set flag = 0 for i in range 6 begin set probs at flag at i = 1 end for i in range 2 n + 1 begin for j in range i begin set probs at 1 - flag at i = 0 end for j in range i 6 * i + 1 begin set probs at 1 - flag at i = 0 for k in...
def printProb(n): probs = [[0] * (6 * n + 1) for i in range(2)] flag = 0 for i in range(6): probs[flag][i] = 1 for i in range(2, n+1): for j in range(i): probs[1-flag][i] = 0 for j in range(i, 6 * i + 1): probs[1-flag][i] = 0 for k in range(1, ...
Python
zaydzuhri_stack_edu_python
class Root begin function __init__ self functions builtin_functions types begin set functions = functions set builtin_functions = builtin_functions set types = types end function decorator property function all_functions self begin return dict none functions ; none builtin_functions end function end class
class Root: def __init__(self, functions, builtin_functions, types): self.functions = functions self.builtin_functions = builtin_functions self.types = types @property def all_functions(self): return { **self.functions, **self.builtin_functions ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string @author: Luca Tonin, Felix Bauer blob detection in track_robot(frame) inspired by https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/ Call program with following options: --config <the yaml configuration file> -p show preview window with ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: Luca Tonin, Felix Bauer blob detection in track_robot(frame) inspired by https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/ Call program with following options: --config <the yaml configuration file> -p show preview window with robo...
Python
zaydzuhri_stack_edu_python
function getCoordinates self imgPath begin set exif_data = load piexif imgPath set lon = none set lat = none set alt = none if string GPS in exif_data begin set gps_data = exif_data at string GPS set gps_latitude = call get_if_exist gps_data GPSLatitude set gps_latitude_ref = call get_if_exist gps_data GPSLatitudeRef s...
def getCoordinates(self, imgPath): exif_data = piexif.load(imgPath) lon = None lat = None alt = None if "GPS" in exif_data: gps_data = exif_data["GPS"] gps_latitude = self.get_if_exist( gps_data, piexif.GPSIFD.GPSLatitude) gps_l...
Python
nomic_cornstack_python_v1
function default_order self field lineup begin print string We're going to default to the first nine players... set dugout = list set order_list = list 0 1 2 3 4 5 6 7 8 for number in order_list begin append dugout lineup at integer number end end function
def default_order(self, field, lineup): print("We're going to default to the first nine players...") field.dugout = [] order_list = [0,1,2,3,4,5,6,7,8] for number in order_list: field.dugout.append(lineup[int(number)])
Python
nomic_cornstack_python_v1
from pigPlayer import PigPlayer function wantsContinue prompt begin string Checks if the response a user gives indicates they want to continue. assume the user has to give a Y to mean yes and N to mean no set ans = input prompt set out = false while ans != string Y and ans != string N begin set ans = input prompt end i...
from pigPlayer import PigPlayer def wantsContinue(prompt): '''Checks if the response a user gives indicates they want to continue. assume the user has to give a Y to mean yes and N to mean no''' ans = input(prompt) out = False while ans != 'Y' and ans != 'N': ans = input(prompt) if ans...
Python
zaydzuhri_stack_edu_python
function convenience_calc_log_likelihood self params begin string Calculates the log-likelihood for this model and dataset. set tuple shapes intercepts betas = call convenience_split_params params set args = list betas design_3d alt_id_vector rows_to_obs rows_to_alts rows_to_mixers choice_vector utility_transform set k...
def convenience_calc_log_likelihood(self, params): """ Calculates the log-likelihood for this model and dataset. """ shapes, intercepts, betas = self.convenience_split_params(params) args = [betas, self.design_3d, self.alt_id_vector, ...
Python
jtatman_500k
import re import sys with open string ../input/02.txt as stream begin set num_ok1 = 0 set num_ok2 = 0 for line in stream begin set match = match string (\d+)-(\d+) (\w): (\w+) line if not match begin exit string No match for line: { line } end set lower = integer call group 1 set upper = integer call group 2 set char =...
import re import sys with open('../input/02.txt') as stream: num_ok1 = 0 num_ok2 = 0 for line in stream: match = re.match(r'(\d+)-(\d+) (\w): (\w+)', line) if not match: sys.exit(f'No match for line:\n{line}') lower = int(match.group(1)) upper = int(match.group(2...
Python
zaydzuhri_stack_edu_python
function chunked_insert model items chunk_size=150 begin comment https://www.sqlite.org/limits.html#max_compound_select with call atomic begin for idx in range 0 length items chunk_size begin execute call insert_many items at slice idx : idx + chunk_size : end end end function
def chunked_insert(model, items, chunk_size=150): # https://www.sqlite.org/limits.html#max_compound_select with db.atomic(): for idx in range(0, len(items), chunk_size): model.insert_many(items[idx:idx+chunk_size]).execute()
Python
nomic_cornstack_python_v1
function get_fov self begin return call _get_view_data string fov * deg end function
def get_fov(self): return self._get_view_data("fov") * u.deg
Python
nomic_cornstack_python_v1
function get_dominant_color self roi begin set average = mean mean roi axis=0 axis=0 set pixels = call float32 reshape roi - 1 3 set n_colors = 1 set criteria = tuple TERM_CRITERIA_EPS + TERM_CRITERIA_MAX_ITER 200 0.1 set flags = KMEANS_RANDOM_CENTERS set tuple _ labels palette = k means pixels n_colors none criteria 1...
def get_dominant_color(self, roi): average = roi.mean(axis=0).mean(axis=0) pixels = np.float32(roi.reshape(-1, 3)) n_colors = 1 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1) flags = cv2.KMEANS_RANDOM_CENTERS _, labels, palette = cv2.kmeans(pixe...
Python
nomic_cornstack_python_v1
function event_attach self eventtype callback *args **kwds begin if not is instance eventtype EventType begin raise call VLCException string %s required: %r % tuple string EventType eventtype end comment callable() if not has attribute callback string __call__ begin raise call VLCException string %s required: %r % tupl...
def event_attach(self, eventtype, callback, *args, **kwds): if not isinstance(eventtype, EventType): raise VLCException("%s required: %r" % ('EventType', eventtype)) if not hasattr(callback, '__call__'): # callable() raise VLCException("%s required: %r" % ('callable', callba...
Python
nomic_cornstack_python_v1
function cache_node_type self begin return get pulumi self string cache_node_type end function
def cache_node_type(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "cache_node_type")
Python
nomic_cornstack_python_v1
function construct_cards tokens begin set md = call Render set headers : Tuple at tuple str str str = tuple string string string set cards : List at str = list for token in tokens begin if token at 0 == HEADER_1 begin set headers = tuple token at 1 string string end else if token at 0 == HEADER_2 begin set header...
def construct_cards(tokens: List[Tuple[Token, str]]) -> List[str]: md = Render() headers: Tuple[str, str, str] = ("", "", "") cards: List[str] = [] for token in tokens: if token[0] == Token.HEADER_1: headers = (token[1], "", "") elif token[0] == Token.HEADER_2: h...
Python
nomic_cornstack_python_v1
function render_plotly_ui transformed_df begin set tuple c1 c2 = call columns 2 set bill_to_tip_figure = call build_bill_to_tip_figure transformed_df set size_to_time_figure = call build_size_to_time_figure transformed_df set day_figure = call build_day_figure transformed_df with c1 begin set bill_to_tip_selected = cal...
def render_plotly_ui(transformed_df: pd.DataFrame) -> Dict: c1, c2 = st.columns(2) bill_to_tip_figure = build_bill_to_tip_figure(transformed_df) size_to_time_figure = build_size_to_time_figure(transformed_df) day_figure = build_day_figure(transformed_df) with c1: bill_to_tip_selected = plo...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment encoding: utf-8 string @Author: yangwenhao @Contact: 874681044@qq.com @Software: PyCharm @File: AcatterHist.py @Time: 2019/5/14 16:22 @Overview: import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter comment Fixing random state for reproducibi...
#!/usr/bin/env python # encoding: utf-8 """ @Author: yangwenhao @Contact: 874681044@qq.com @Software: PyCharm @File: AcatterHist.py @Time: 2019/5/14 16:22 @Overview: """ import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter # Fixing random state for reproducibility np.random.s...
Python
zaydzuhri_stack_edu_python
from utils.decoder import Decoder from itertools import product from colorama import Fore import argparse function banner begin print WHITE print string ( ( ( )\ ) ( )\ ( )\ ) (()/( ( )\ ) ( ( ((((_)( ))\ (()/( ( /(_)) ))\ ( ( (()/( ))\ )( )\ _ )\ /((_) ((_)) )\(_))_ /((_) )\ )\ ((_))/((_)(()\ (_)_\(_)(_))( _| | ((_)| ...
from utils.decoder import Decoder from itertools import product from colorama import Fore import argparse def banner(): print(Fore.WHITE) print("\n\ ( \n\ ( ( )\ ) ( \n\ )\ ( )\ ) (...
Python
zaydzuhri_stack_edu_python
function toggle_value self begin call handle_modified if text_value not in conf at string cols_selected begin append conf at string cols_selected text_value set value=join string conf at string cols_selected end else begin remove conf at string cols_selected text_value set value=join string conf at string cols_select...
def toggle_value(self): self.handle_modified() if self.text_value not in conf["cols_selected"]: conf["cols_selected"].append(self.text_value) self.var_selected.set( value="\n".join(conf["cols_selected"])) else: conf["cols_selected"].remove(self...
Python
nomic_cornstack_python_v1
comment -*- coding: gbk -*- import ConfigParser import os import sys comment iniöд class MyConfig begin string configParser wrapper class set __iniFile = string set __confInstance = none set __outFp = none comment ʼ function __init__ self filePath begin set __iniFile = strip filePath call loadFormFile end function com...
# -*- coding: gbk -*- import ConfigParser import os import sys #iniöд class MyConfig: "configParser wrapper class" __iniFile = "" __confInstance = None __outFp = None #ʼ def __init__(self,filePath): self.__iniFile = filePath.strip() self.loadFormFile() #Ƿװسɹ def isLoa...
Python
zaydzuhri_stack_edu_python
function get self item default=NO_DEFAULT begin try begin return annotate dict_ at item end except KeyError begin if default is NO_DEFAULT begin raise end return default end end function
def get(self, item, default=NO_DEFAULT): try: return util.annotate(self.dict_[item]) except KeyError: if default is NO_DEFAULT: raise return default
Python
nomic_cornstack_python_v1
function findSequence seq begin set his = dict for item in seq begin if item not in his begin set his at item = 0 end else begin set his at item = his at item + 1 end end set num = list for tuple key value in items his begin append num value end sort num reverse=true set begin = 0 set end = 1 while true begin if num ...
def findSequence(seq): his = {} for item in seq: if item not in his: his[item] = 0 else: his[item] = his[item] + 1 num = [] for key, value in his.items(): num.append(value) num.sort(reverse=True) begin = 0 end = 1 while True: i...
Python
zaydzuhri_stack_edu_python
from pymongo import MongoClient set client = call MongoClient string localhost 27017 set db = inventory_db set collection = inventory set inventory = list dict string product_name string Apple ; string quantity 10 ; string price 3.99 dict string product_name string Banana ; string quantity 20 ; string price 2.99 dict s...
from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client.inventory_db collection = db.inventory inventory = [ { "product_name": "Apple", "quantity": 10, "price": 3.99 }, { "product_name": "Banana", "quantity": 20, "price": 2.99 }, { "product_name": "...
Python
flytech_python_25k
comment Raspberry PI GPIO hooked to Laser Array, Servo motor and flashing LEDs comment Used in lab as toy intrusion detection setup import RPi.GPIO as GPIO import time import os call setmode BCM call setwarnings false comment Set pin 16 as an output, and set servo1 as pin 16 as PWM setup GPIO 16 OUT comment setup relay...
# Raspberry PI GPIO hooked to Laser Array, Servo motor and flashing LEDs # Used in lab as toy intrusion detection setup import RPi.GPIO as GPIO import time import os GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #Set pin 16 as an output, and set servo1 as pin 16 as PWM GPIO.setup(16, GPIO.OUT) #setup relay output...
Python
zaydzuhri_stack_edu_python
function getInstance cls number data=none begin set CLASS = call getClass number if not CLASS begin raise exception string Tag %s is not found % number end return call CLASS data end function
def getInstance(cls, number, data = None): CLASS = cls.getClass(number) if not CLASS: raise Exception('Tag %s is not found' % number) return CLASS(data)
Python
nomic_cornstack_python_v1
function stratify_array array num_percentiles=4 begin set percentiles = list comprehension ii * 100 / num_percentiles for ii in list range 0 num_percentiles + 1 set stratif_labels = copy np array for ii in range 0 length percentiles - 1 begin set lo = percentiles at ii set hi = percentiles at ii + 1 set plo = call perc...
def stratify_array(array, num_percentiles=4): percentiles = [ii*100/num_percentiles for ii in list(range(0,num_percentiles+1))] stratif_labels = np.copy(array) for ii in range(0,len(percentiles)-1): lo = percentiles[ii] hi = percentiles[ii+1] plo = np.percen...
Python
nomic_cornstack_python_v1
async function trader self msg arg=none *args begin set trading_table = await call get_trading_table set self_delete = false if not arg begin set content = string • + join string • generator expression capitalize place for place in keys trading_table set content = string Places you can trade: { content } end else begin...
async def trader(self, msg, arg=None, *args): trading_table = await self.get_trading_table() self_delete = False if not arg: content = '• '+'\n• '.join(place.capitalize() for place in trading_table.keys()) content = f'Places you can trade:\n{content}' else: ...
Python
nomic_cornstack_python_v1
function grant_the_hint txt begin set textList = split txt set hint = string set hintList = list set textLen = length textList set hintLvl = 0 while hint != txt begin for i in range textLen begin if i != 0 begin set hintList = hintList + string end set wordLen = length textList at i for j in range wordLen begin if h...
def grant_the_hint(txt): textList = txt.split() hint = '' hintList = [] textLen = len(textList) hintLvl = 0 while(hint != txt): for i in range(textLen): if(i!=0): hintList += ' ' wordLen = len(textList[i]) for j in range(wordLen): if(hintLvl > j): hint += '_' ...
Python
zaydzuhri_stack_edu_python
string print("=====0000=====") while True: num1=int(input()) num2=int(input()) if num1 in range(0,10**9+1): if num2 in range(0,10**9+1): result=num1+num2 print(result) break else: print("Input Num 2 Again!") continue else: print("Input Num 1 Again!") continue#0000 print("=====0001=====") while True: unit_sc=int(input("...
''' print("=====0000=====") while True: num1=int(input()) num2=int(input()) if num1 in range(0,10**9+1): if num2 in range(0,10**9+1): result=num1+num2 print(result) break else: print("Input Num 2 Again!") continue else: ...
Python
zaydzuhri_stack_edu_python
import numpy as np seed 14 from data_handling import * import sys class FF_NeuralNetwork begin string This is the main class handling all the work from variable init, to feed-forwarding the network and then tuning the paramenters by back-propagation for the simple feed-forward neural network. comment ATTRIBUTES #######...
import numpy as np np.random.seed(14) from data_handling import * import sys class FF_NeuralNetwork(): ''' This is the main class handling all the work from variable init, to feed-forwarding the network and then tuning the paramenters by back-propagation for the simple feed-forward neural network. ...
Python
zaydzuhri_stack_edu_python
comment 8. Faça um Programa que peça os 3 lados de um triângulo. O comment programa deverá informar se os valores podem ser um triângulo. comment Indique, caso os lados formem um triângulo, se o mesmo é: comment equilátero, isósceles ou escaleno. comment Dicas: comment - Três lados formam um triângulo quando a soma de ...
# 8. Faça um Programa que peça os 3 lados de um triângulo. O # programa deverá informar se os valores podem ser um triângulo. # Indique, caso os lados formem um triângulo, se o mesmo é: # equilátero, isósceles ou escaleno. # Dicas: # - Três lados formam um triângulo quando a soma de quaisquer dois # lados for maior que...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 import csv import sys import vcf import argparse function chunks l n begin string Yield successive n-sized chunks from l. for i in range 0 length l n begin yield l at slice i : i + n : end end function function getCsqHeader vcf_file begin set reader = reader open vcf_...
#!/usr/bin/env python # coding: utf-8 import csv import sys import vcf import argparse def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def getCsqHeader(vcf_file): reader = vcf.Reader(open(vcf_file, 'r')) csq_info = reader.infos['CSQ...
Python
zaydzuhri_stack_edu_python
import time import Board print string ********************************************************** ********功能:幻尔科技树莓派扩展板,串口舵机控制例程******* ********************************************************** ---------------------------------------------------------- Official website:http://www.lobot-robot.com/pc/index/index Online m...
import time import Board print(''' ********************************************************** ********功能:幻尔科技树莓派扩展板,串口舵机控制例程******* ********************************************************** ---------------------------------------------------------- Official website:http://www.lobot-robot.com/pc/index/index Online mal...
Python
zaydzuhri_stack_edu_python
function get_auxiliary_datasets h5_object aux_dset_name=none begin warn string pyUSID.io.hdf_utils.get_auxiliary_datasets has been moved to sidpy.hdf.hdf_utils.get_auxiliary_datasets. This copy in pyUSID willbe removed in future release. Please update your import statements return call get_auxiliary_datasets h5_object ...
def get_auxiliary_datasets(h5_object, aux_dset_name=None): warn('pyUSID.io.hdf_utils.get_auxiliary_datasets has been moved to ' 'sidpy.hdf.hdf_utils.get_auxiliary_datasets. This copy in pyUSID will' 'be removed in future release. Please update your import statements') return hut.get_auxiliary_...
Python
nomic_cornstack_python_v1
set test = string 1。2 set r1 = call isdecimal set r2 = is digit test print r1 r2
test = "1。2" r1 = test.isdecimal() r2 = test.isdigit() print(r1, r2)
Python
zaydzuhri_stack_edu_python
function test_chunker self begin set chunker = call StringChunker sieve_function call assert_chunker_sample chunker SUNA_ASCII_SAMPLE call assert_chunker_fragmented_sample chunker SUNA_ASCII_SAMPLE call assert_chunker_combined_sample chunker SUNA_ASCII_SAMPLE call assert_chunker_sample_with_noise chunker SUNA_ASCII_SAM...
def test_chunker(self): chunker = StringChunker(Protocol.sieve_function) self.assert_chunker_sample(chunker, SUNA_ASCII_SAMPLE) self.assert_chunker_fragmented_sample(chunker, SUNA_ASCII_SAMPLE) self.assert_chunker_combined_sample(chunker, SUNA_ASCII_SAMPLE) self.assert_chunker_s...
Python
nomic_cornstack_python_v1
comment Author: Enda Lynch comment Programme to output name and Age comment Input name and age values set name = input string What is your name?: set age = input string What is your age?: comment display based on inputs print string Your Name is name + string , + string your age is age + string . comment or use the .fo...
#Author: Enda Lynch #Programme to output name and Age #Input name and age values name = input ('What is your name?: ') age = input ('What is your age?: ') #display based on inputs print ('Your Name is ' , (name) + ',' + ' your age is ', (age) + '.') # or use the .format print ('Your name is {}, you are {} years o...
Python
zaydzuhri_stack_edu_python
function get_all_from_queue Q begin try begin while true begin yield call get_nowait end end except Empty begin raise StopIteration end end function
def get_all_from_queue(Q): try: while True: yield Q.get_nowait( ) except queue.Empty: raise StopIteration
Python
nomic_cornstack_python_v1
function split_data self begin set tuple X_train X_test y_train y_test = train test split X y random_state=7 return tuple X_train X_test y_train y_test end function
def split_data(self): X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=7) return X_train, X_test, y_train, y_test
Python
nomic_cornstack_python_v1
function get_and_send_attachments self session mid message_payload_parts context m_chat_id begin set store_dir_1 = get current directory for part in message_payload_parts begin if part at string filename begin set attachment_id = part at string body at string attachmentId set response = get session string https://www.g...
def get_and_send_attachments(self, session, mid, message_payload_parts, context, m_chat_id): store_dir_1 = os.getcwd() for part in message_payload_parts: if part['filename']: attachment_id = part['body']['attachmentId'] response = session.get(f'http...
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution begin function maxDepth self root begin if not root begin return 0 end else begin return max call maxDepth left call maxDepth right + 1...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 else: return max(self.maxDepth(r...
Python
zaydzuhri_stack_edu_python
string prob1.py: Problem 1. HW2. Information Theory : 2019. set __author__ = string Dilawar Singh set __copyright__ = string Copyright 2017-, Dilawar Singh set __version__ = string 1.0.0 set __maintainer__ = string Dilawar Singh set __email__ = string dilawars@ncbs.res.in set __status__ = string Development import nump...
"""prob1.py: Problem 1. HW2. Information Theory : 2019. """ __author__ = "Dilawar Singh" __copyright__ = "Copyright 2017-, Dilawar Singh" __version__ = "1.0.0" __maintainer__ = "Dilawar Singh" __email__ = "dilawars@ncbs.res.in" __status__ = "Development" ...
Python
zaydzuhri_stack_edu_python
function get_number_of_teapot_requests cls begin return count where requested_teapot == true end function comment noqa
def get_number_of_teapot_requests(cls): return PotMaker.select().where( PotMaker.requested_teapot == True # noqa ).count()
Python
nomic_cornstack_python_v1
function select_attack attack_name dataset a_index other begin print string Find + attack_name set csvFileArray = list with open dataset string r as file begin set reader = reader file delimiter=string , for row in reader begin if row at a_index == attack_name begin append csvFileArray row end else begin append other ...
def select_attack(attack_name, dataset, a_index, other): print ('\n Find '+attack_name) csvFileArray = [] with open(dataset, 'r') as file: reader = csv.reader(file, delimiter = ',') for row in reader: if row[a_index] == attack_name : csvFileArray.append(...
Python
nomic_cornstack_python_v1
function binarysearch s e v begin set mid = s + e // 2 if e == s + 1 begin return s + 1 end set i = 0 while i < length v - 1 begin if i == length v - 2 and v at i + 1 - v at i > mid begin break end if v at i + 1 - v at i > mid * 2 begin break end set i = i + 1 end if i == length v - 1 begin return call binarysearch s m...
def binarysearch(s,e,v): mid = (s+e)//2 if e == s+1: return s+1 i = 0 while i < len(v)-1: if i == len(v)-2 and v[i+1]-v[i] > mid: break if v[i+1] - v[i] > mid*2: break i += 1 if i == len(v)-1: return binarysearch(s,mid,v) return bin...
Python
zaydzuhri_stack_edu_python
function ConsistentTrees_ASCII_099 begin comment scale(0) set dt = list tuple string a float32 tuple string haloid_CT int64 tuple string a_desc float32 tuple string descID int64 tuple string n_prog int32 tuple string hostid_LM int64 tuple string hostid_MM int64 tuple string desc_hostid_MM int64 tuple string is_phantom ...
def ConsistentTrees_ASCII_099(): dt= [('a' , np.float32), #scale(0) ('haloid_CT' , np.int64), #id(1) ('a_desc' , np.float32), #desc_scale(2) ('descID' , np.int64), #desc_id(3) ('n_prog' , np.int...
Python
nomic_cornstack_python_v1
string tank → kick → know → wheel → land → dream → mother → robot → tank flag부분은 [0,0]을 판별하기 위한 변수인데 break가 되서 나간건지 아니면 그냥 iterate할 words가 남아있지 않아서 나간건지를 구별하기 위한 변수!! num은 차례를 계산하기 위한 변수 -> answer[0], answer[1]에 사용될 것! dictionary는 이미 말했던 걸 다시 말하지 않는지를 체크하기 위한 list 0부터 len(words)-1까지 돌면서 num값을 1만큼 먼저 증가시켜 준다. 그리고 끝말잇기할때...
''' tank → kick → know → wheel → land → dream → mother → robot → tank flag부분은 [0,0]을 판별하기 위한 변수인데 break가 되서 나간건지 아니면 그냥 iterate할 words가 남아있지 않아서 나간건지를 구별하기 위한 변수!! num은 차례를 계산하기 위한 변수 -> answer[0], answer[1]에 사용될 것! dictionary는 이미 말했던 걸 다시 말하지 않는지를 체크하기 위한 list 0부터 len(words)-1까지 돌면서 num값을 1만큼 먼저 증가시켜 준다. 그리고 끝말잇기할때 이...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import requests , os function supplier_image_upload url image_directory begin set files = list directory image_directory for image_name in files begin if not starts with image_name string . and string jpeg in image_name begin set image_path = image_directory + image_name with open image_pa...
#!/usr/bin/env python3 import requests, os def supplier_image_upload(url, image_directory): files = os.listdir(image_directory) for image_name in files: if not image_name.startswith('.') and 'jpeg' in image_name: image_path = image_directory + image_name with open(image_path, 'r...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import tensorflow as tf function t begin set writer = call TFRecordWriter string abc.tfrecords set example = call Example features=call Features feature=dict string label call Feature float_list=call FloatList value=list 1.0 2.0 3.0 3.0 4.0 write writer call Se...
#!/usr/bin/env python # -*- coding: utf-8 -*- import tensorflow as tf def t(): writer = tf.python_io.TFRecordWriter("abc.tfrecords") example = tf.train.Example(features=tf.train.Features(feature={ 'label': tf.train.Feature(float_list=tf.train.FloatList(value=[1.0, 2.0, 3.0, 3.0, 4.0])) })) wr...
Python
zaydzuhri_stack_edu_python
function mixed self theta=array list begin comment This is where the OO-approach helps me here, since we can comment draw on other instance-level parameters that the other comment methods do not need. comment Loop through the methods to evaluate set lnPriors = theta * 0.0 for iPar in range size np theta begin set thisM...
def mixed(self, theta=np.array([])): ### This is where the OO-approach helps me here, since we can ### draw on other instance-level parameters that the other ### methods do not need. ### Loop through the methods to evaluate lnPriors = theta*0. for iPar in range...
Python
nomic_cornstack_python_v1
import pyttsx3 import speech_recognition as sr import webbrowser as web set engine = call init string sapi5 set voices = call getProperty string voices call setProperty string voice id function speak audio begin call say audio call runAndWait end function function main begin comment path ="C:/Program Files (x86)/Google...
import pyttsx3 import speech_recognition as sr import webbrowser as web engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voice',voices[0].id) def speak(audio): engine.say(audio) engine.runAndWait() def main(): #path ="C:/Program Files (x86)/Goo...
Python
zaydzuhri_stack_edu_python
function get_section_url self classification_id begin set hierarchy = call get_hierarchy classification_id comment return the last url found set filtered = list filter lambda c -> get c string url hierarchy return get list dict + filtered at slice - 1 : : at 0 string url end function
def get_section_url(self, classification_id): hierarchy = self.get_hierarchy(classification_id) # return the last url found filtered = list(filter(lambda c: c.get('url'), hierarchy)) return ([{}] + filtered)[-1:][0].get('url')
Python
nomic_cornstack_python_v1
comment converts all png files in a folder to non-indexed png files. comment requires the third-party software Imagemagick. import os set files = list for filename in list directory begin if string .png in filename begin append files filename end end for f in files begin comment overwrite existing file: call system fo...
#converts all png files in a folder to non-indexed png files. #requires the third-party software Imagemagick. import os files=[] for filename in os.listdir(): if ".png" in filename: files.append(filename) for f in files: #overwrite existing file: os.system("convert {} -colorspace srgb PNG32:{}".format(f,f)...
Python
zaydzuhri_stack_edu_python
comment https://www.acmicpc.net/problem/11049 import sys if __name__ == string __main__ begin set n_array = integer read line stdin set arrays = list comprehension tuple map int split read line stdin for _ in range n_array comment cost_memo(row, col), col ~ row 까지 행렬을 곱했을 때 최소값 저장 set cost_memo = list comprehension lis...
# https://www.acmicpc.net/problem/11049 import sys if __name__ == '__main__': n_array = int(sys.stdin.readline()) arrays = [tuple(map(int, sys.stdin.readline().split())) for _ in range(n_array)] # cost_memo(row, col), col ~ row 까지 행렬을 곱했을 때 최소값 저장 cost_memo = [[0] * n_array for _ in range(n_array)] ...
Python
zaydzuhri_stack_edu_python
function test_cache_func begin decorator cache times=1 function test begin return list end function set reference_1 = call test set reference_2 = call test set reference_3 = call test assert reference_1 is reference_2 assert reference_2 is not reference_3 end function
def test_cache_func(): @cache(times=1) def test(): return list() reference_1 = test() reference_2 = test() reference_3 = test() assert reference_1 is reference_2 assert reference_2 is not reference_3
Python
nomic_cornstack_python_v1
from src.consts import MapObject from enum import Enum from src import temporary_map import random import pygame class Color begin function __init__ self value begin set value = value end function end class function random_color_generator begin comment RGB color return call Color tuple random integer 1 254 random integ...
from src.consts import MapObject from enum import Enum from src import temporary_map import random import pygame class Color: def __init__(self, value): self.value = value def random_color_generator(): # RGB color return Color((random.randint(1, 254), random.randint(200, 254), random.randint(1, ...
Python
zaydzuhri_stack_edu_python
function get_previous_shot_number self shot_number begin set previous_shot = call aggregate max string number at string number__max return previous_shot end function
def get_previous_shot_number(self, shot_number): previous_shot = self.model.objects.filter(number__lt=shot_number).aggregate(models.Max('number'))['number__max'] return previous_shot
Python
nomic_cornstack_python_v1
function _detect_correlation self begin set correlations = list set shifted_correlations = list call normalize call normalize set tuple a b = call align time_series_b set tuple a_values b_values = tuple values values set tuple a_avg b_avg = tuple call average call average set tuple a_stdev b_stdev = tuple call stdev ...
def _detect_correlation(self): correlations = [] shifted_correlations = [] self.time_series_a.normalize() self.time_series_b.normalize() a, b = self.time_series_a.align(self.time_series_b) a_values, b_values = a.values, b.values a_avg, b_avg = a.average(), b.avera...
Python
nomic_cornstack_python_v1
class Solution begin function maxArea self height begin string Thought process Goal: Find container with most water. Trick is to have best width vs height combo between two bounds. Start with sliding window approach. Reecord current max rectangle. Shorten window by moving smaller bar's index repeat return max -> O(len(...
class Solution: def maxArea(self, height: List[int]) -> int: """ Thought process Goal: Find container with most water. Trick is to have best width vs height combo between two bounds. Start with sliding window approach. Reecord current max rectangle. Shorten w...
Python
zaydzuhri_stack_edu_python
class Student extends object begin set count = 0 function __init__ self name begin set name = name set count = count + 1 end function end class if count != 0 begin print string 测试失败! end else begin set bart = call Student string Bart if count != 1 begin print string 测试失败! end else begin set lisa = call Student string B...
class Student(object): count = 0 def __init__(self, name): self.name = name Student.count +=1 if Student.count != 0: print('测试失败!') else: bart = Student('Bart') if Student.count != 1: print('测试失败!') else: lisa = Student('Bart') if Student.count != 2: ...
Python
zaydzuhri_stack_edu_python
import pytest function test_get_valid_fields marshmayama_instance begin set expected_results = dict string userId dict string attributes dict string required false ; string attribute string user_id ; string missing none ; string type string String ; string anonymousId dict string attributes dict string required false ;...
import pytest def test_get_valid_fields(marshmayama_instance): expected_results = { "userId": { "attributes":{ "required": False, "attribute": "user_id", "missing": None }, "type": "String", ...
Python
zaydzuhri_stack_edu_python
function show self derivations=false short=true failures=false style=none begin if content is none begin return call build_display_tree derivations=derivations style=style end else if is instance content CompositionResult begin if short begin return show style=style failures=failures end else begin return call tree der...
def show(self,derivations=False, short=True, failures=False, style=None): if self.content is None: return self.build_display_tree(derivations=derivations, style=style) elif isinstance(self.content, CompositionResult): if short: return self.content.show(style=style...
Python
nomic_cornstack_python_v1