code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
string Declarando a classe class Carro extends object begin string Método Construtor function _init_ self caminho begin set caminho = caminho end function string Metodo function andar self begin print string Andando pela caminho end function end class class Fusca extends Carro begin function __init__ self caminho begin...
'''Declarando a classe''' class Carro(object): '''Método Construtor ''' def _init_(self, caminho) : self.caminho = caminho '''Metodo''' def andar (self) : print('Andando pela', self.caminho) class Fusca(Carro): ...
Python
zaydzuhri_stack_edu_python
function _runCallbacks self name begin if name in _callbacks begin for callback in _callbacks at name begin call callback end end end function
def _runCallbacks(self, name): if name in self._callbacks: for callback in self._callbacks[name]: callback()
Python
nomic_cornstack_python_v1
function parse self stream offset=0 begin set stack = list set result = call _parse stream offset set error = none while 1 begin if is instance result GeneratorType begin comment Push a new coroutine onto the stack and prepare to comment initialize it. append stack result set result = none end else if stack begin comm...
def parse(self, stream, offset=0): stack = [] result = self._parse(stream, offset) error = None while 1: if isinstance(result, types.GeneratorType): # Push a new coroutine onto the stack and prepare to # initialize it. stack.app...
Python
nomic_cornstack_python_v1
function gen_cols other_cols begin set cols = list comprehension call col s for s in group_keys set cols = cols + other_cols return cols end function
def gen_cols(other_cols): cols = [col(s) for s in self.group_keys] cols += other_cols return cols
Python
nomic_cornstack_python_v1
function get_rubric_terms self begin comment osid.assessment.AssessmentQueryInspector return end function
def get_rubric_terms(self): return # osid.assessment.AssessmentQueryInspector
Python
nomic_cornstack_python_v1
comment tuple with animals set zoo = tuple string whale string shark string dolphin string penguin string lion string tiger string bear string alligator string ducks string manatee comment check to determine if animal is in the zoo set animal_to_find = string tiger if animal_to_find in zoo begin print string { animal_t...
# tuple with animals zoo = ("whale", "shark", "dolphin", "penguin", "lion", "tiger", "bear", "alligator", "ducks", "manatee") # check to determine if animal is in the zoo animal_to_find = "tiger" if animal_to_find in zoo: print(f'{animal_to_find} was found in the zoo tuple.') # find index of animal print(...
Python
zaydzuhri_stack_edu_python
function on_draw self begin comment clear the screen to begin drawing call start_render comment draw each object call draw for bullet in bullets begin call draw end comment TODO: iterate through your targets and draw them... for target in targets begin call draw end call draw_score end function
def on_draw(self): # clear the screen to begin drawing arcade.start_render() # draw each object self.rifle.draw() for bullet in self.bullets: bullet.draw() # TODO: iterate through your targets and draw them... for target in self.targets: ta...
Python
nomic_cornstack_python_v1
import numpy as np comment flower database from sklearn.datasets import load_iris from sklearn import tree from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix import matplotlib as mpl import matplotlib.pyplot as plt comment load ir...
import numpy as np from sklearn.datasets import load_iris # flower database from sklearn import tree from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix import matplotlib as mpl import matplotlib.pyplot as plt # iris = load_iris()...
Python
zaydzuhri_stack_edu_python
function vertices self values begin string Assign vertex values to the mesh. Parameters -------------- values : (n, 3) float Points in space set _data at string vertices = call asanyarray values order=string C dtype=float64 end function
def vertices(self, values): """ Assign vertex values to the mesh. Parameters -------------- values : (n, 3) float Points in space """ self._data['vertices'] = np.asanyarray(values, order='C', ...
Python
jtatman_500k
function input self begin return input end function
def input(self): return input()
Python
nomic_cornstack_python_v1
import sys set input = lambda -> right strip read line stdin call setrecursionlimit max 1000 10 ^ 9 set write = lambda x -> write stdout x + string set tuple k x = list map int split input set ans = list range x - k + 1 x + k print join string map str ans
import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") k,x = list(map(int, input().split())) ans = list(range(x-k+1, x+k)) print(" ".join(map(str, ans)))
Python
zaydzuhri_stack_edu_python
set a = eval input print a ^ 0.5 comment 保留四位小数 print format string {:.4f} a ^ 0.5
a=eval(input()) print(a**0.5) print("{:.4f}".format(a**0.5))#保留四位小数
Python
zaydzuhri_stack_edu_python
comment 0导包 from PyQt5.Qt import * import sys comment 1.创建一个应用程序对象 set app = call QApplication argv comment 2.1创建控件 set window = call QWidget comment 2.2设置控件 call setWindowTitle string 按钮可用信号 call resize 500 500 set btn = call QPushButton window call setText string 可用信号 move 200 200 call setCheckable 1 call connect lam...
# 0导包 from PyQt5.Qt import * import sys # 1.创建一个应用程序对象 app = QApplication(sys.argv) # 2.1创建控件 window = QWidget() # 2.2设置控件 window.setWindowTitle("按钮可用信号") window.resize(500, 500) btn = QPushButton(window) btn.setText("可用信号") btn.move(200, 200) btn.setCheckable(1) btn.pressed.connect(lambda : print("按钮被按下")) btn.rele...
Python
zaydzuhri_stack_edu_python
function _sel_context self cr uid voucher_id context=none begin set company_currency = call _get_company_currency cr uid voucher_id context set current_currency = call _get_current_currency cr uid voucher_id context end function
def _sel_context(self, cr, uid, voucher_id, context=None): company_currency = self._get_company_currency(cr, uid, voucher_id, context) current_currency = self._get_current_currency(cr, uid, voucher_id, context)
Python
nomic_cornstack_python_v1
for line in lines begin set target = strip line set features = split target string set df at j = tuple decimal features at 0 decimal features at 1 set j = j + 1 end for i in range 10 begin print get df i string None end import pylab , random import matplotlib.pyplot as plt function distance x y p=2 begin set dist = 0 f...
for line in lines: target=line.strip() features=target.split(' ') df[j]=(float(features[0]),float(features[1])) j+=1 for i in range(10): print(df.get(i,"None")) import pylab, random import matplotlib.pyplot as plt def distance(x,y,p=2): dist=0 for i in range(len(x)): dist+=(abs(x[i...
Python
zaydzuhri_stack_edu_python
for i in range nkc at 0 - nkc at 2 - 1 begin set arr = list for j in range nkc at 2 begin append arr arrN at i + cont set cont = cont + 1 end set cont = 0 append matriz arr set matriz at i = sum matriz at i end for i in range nkc at 1 begin set menor = min matriz set pos = index matriz menor set num = pos - nkc at 2 -...
for i in range(nkc[0]-(nkc[2]-1)): arr = [] for j in range(nkc[2]): arr.append(arrN[i+cont]) cont += 1 cont = 0 matriz.append(arr) matriz[i] = sum(matriz[i]) for i in range(nkc[1]): menor = min(matriz) pos = matriz.index(menor) num = pos - (nkc[2]-1) arr...
Python
zaydzuhri_stack_edu_python
class TrieNode extends object begin function __init__ self begin set is_end = false set child = list 0 * 26 end function end class class WordDictionary extends object begin function __init__ self begin string Initialize your data structure here. set __root = call TrieNode end function function addWord self word begin s...
class TrieNode(object): def __init__(self): self.is_end = False self.child = [0] * 26 class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.__root = TrieNode() def addWord(self, word): """ Adds a...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string @author: 肖 # 69课(3)---可以再去看看---这是完整版---同时可以试试改成xpath版本的 这里是爬取智联的案例--- 如果使用urllib获取会得到js加密的源代码,没有任何意义,因此需要借助浏览器来执行---selenium,PhantomJS 如何知道是js加密的源码:1.源代码与检查下的代码之间差距过大; 2.使用xpath,bs4时是无法解析的(理由还是差距过多,需要动态加载) import urllib.request from selenium import webdriver from bs4 import Beautifu...
# -*- coding: utf-8 -*- """ @author: 肖 # 69课(3)---可以再去看看---这是完整版---同时可以试试改成xpath版本的 这里是爬取智联的案例--- 如果使用urllib获取会得到js加密的源代码,没有任何意义,因此需要借助浏览器来执行---selenium,PhantomJS 如何知道是js加密的源码:1.源代码与检查下的代码之间差距过大; 2.使用xpath,bs4时是无法解析的(理由还是差距过多,需要动态加载) """ import urllib.request from selenium import webdriver from bs4 import Beautiful...
Python
zaydzuhri_stack_edu_python
function train_classifier self features_2 size begin comment Compute features +ve instances set features_1 = call compute_features size comment Form labels set target = list for i in range length features_1 + length features_2 begin if i < length features_1 begin append target 1 end else begin append target 0 end end ...
def train_classifier(self,features_2,size): #Compute features +ve instances features_1 = self.compute_features(size) #Form labels target = [] for i in range(len(features_1)+len(features_2)): if i <len(features_1): target.append(1) else: target.append(0) #Train data - concatenate +ve and -ve...
Python
nomic_cornstack_python_v1
function bulk_by_sample self request begin if method == string POST begin set hamming = if expression string hamming_distance in GET then true else false set validator = call validate_list_of_ids data max_query=500 if validator at string has_errors begin return call Response dict string message validator at string mess...
def bulk_by_sample(self, request): if request.method == 'POST': hamming = True if 'hamming_distance' in request.GET else False validator = validate_list_of_ids(request.data, max_query=500) if validator['has_errors']: return Response({ "mess...
Python
nomic_cornstack_python_v1
comment Importing the Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt comment Importing the Dataset set dataset = read csv string Countrywise.csv set d = iloc at tuple slice : : slice 5 : : set X = loc at ? all axis=1
#Importing the Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #Importing the Dataset dataset=pd.read_csv("Countrywise.csv") d=dataset.iloc[:, 5:] X=d.loc[~(d==0).all(axis=1)]
Python
zaydzuhri_stack_edu_python
function test_process_id_map_errors self begin set tuple header mapping_data comments errors warnings = call process_id_map errors_mapping_fp set expected_header = list string SampleID string BarcodeSequence string LinkerPrimerSequence string Treatment string ReversePrimer string NotDescription set expected_mapping_dat...
def test_process_id_map_errors(self): header, mapping_data, comments, errors, warnings =\ process_id_map(self.errors_mapping_fp) expected_header = [ 'SampleID', 'BarcodeSequence', 'LinkerPrimerSequence', 'Treatment', 'Re...
Python
nomic_cornstack_python_v1
function geoeas_to_npGS datain gridspecs begin comment Check that gridspecs is a list of ``GridSpec`` objects if not is instance gridspecs list begin if not is instance gridspecs GridSpec begin raise call RuntimeError format string gridspecs arguments ({}) improperly defined. gridspecs end comment Make sure we have a l...
def geoeas_to_npGS(datain, gridspecs): # Check that gridspecs is a list of ``GridSpec`` objects if not isinstance(gridspecs, list): if not isinstance(gridspecs, GridSpec): raise RuntimeError('gridspecs arguments ({}) improperly defined.'. format(gridspecs)) gridspecs = [gridspecs] # ...
Python
nomic_cornstack_python_v1
from operator import mul class Solution extends object begin function productExceptSelf self nums begin string :type nums: List[int] :rtype: List[int] set zero_count = count nums 0 if zero_count > 1 begin return list 0 * length nums end else if zero_count == 1 begin set idx = index nums 0 set ans = list 0 * length nums...
from operator import mul class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ zero_count = nums.count(0) if zero_count > 1: return [0]*len(nums) elif zero_count == 1: idx = nums.in...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup function extract_links_from_url url begin comment make a request to the URL set r = get requests url comment create a beautiful soup object set soup = call BeautifulSoup content string html5lib comment find and return hyperlinks(a tags) return list comprehension link at str...
import requests from bs4 import BeautifulSoup def extract_links_from_url(url): # make a request to the URL r = requests.get(url) # create a beautiful soup object soup = BeautifulSoup(r.content,'html5lib') # find and return hyperlinks(a tags) return [link['href'] for link i...
Python
iamtarun_python_18k_alpaca
import random function play_game player1 player2 begin set choices = list string rock string paper string scissors set player1_choice = random choice choices set player2_choice = random choice choices end function comment If player 1 chooses rock
import random def play_game(player1, player2): choices = ['rock', 'paper', 'scissors'] player1_choice = random.choice(choices) player2_choice = random.choice(choices) # If player 1 chooses rock
Python
iamtarun_python_18k_alpaca
function issue_closed issue_key server=none username=none password=none begin string Check if the issue is closed. issue_key The JIRA iD of the ticket to close. Returns: - ``True``: the ticket exists and it is closed. - ``False``: the ticket exists and it has not been closed. - ``None``: the ticket does not exist. CLI ...
def issue_closed(issue_key, server=None, username=None, password=None): ''' Check if the issue is closed. issue_key The JIRA iD of the ticket to close. Returns: - ``True``: the ticket exists and it is closed. - ``False``: the ticket e...
Python
jtatman_500k
function get_ertr_ipv6 self mac offset=2 begin call sendline string show cable modem { mac } cpe call expect prompt set mac = call EUI mac set ertr_mac = call EUI integer mac + offset set dialect = mac_cisco set output = replace replace before string string string string set ertr_ipv6 = search string ( { AllValidIpv6...
def get_ertr_ipv6(self, mac: str, offset: int = 2) -> Optional[str]: self.sendline(f"show cable modem {mac} cpe") self.expect(self.prompt) mac = netaddr.EUI(mac) ertr_mac = netaddr.EUI(int(mac) + offset) ertr_mac.dialect = netaddr.mac_cisco output = self.before.replace("\...
Python
nomic_cornstack_python_v1
function __getitem__ self i begin if memory_management is not none begin if percent > memory_management begin info string Managing memory. Unloading database. call unload_all end end return db at i end function
def __getitem__(self, i): if self.memory_management is not None: if psutil.virtual_memory().percent > self.memory_management: logging.info("Managing memory. Unloading database.") self.unload_all() return self.db[i]
Python
nomic_cornstack_python_v1
comment using center(width[fillchar]) function for aligning center the variable set user_type = string Student user print call center 50 comment using replace(function) for modifying the value print replace user_type string Student user string Teacher user comment using capitalize function for replacing the 1st string ...
# using center(width[fillchar]) function for aligning center the variable user_type = "Student user" print(user_type.center(50)) # using replace(function) for modifying the value print(user_type.replace("Student user", "Teacher user")) # using capitalize function for replacing the 1st string of the variables i...
Python
zaydzuhri_stack_edu_python
import pandas import csv import os import re import subprocess import sys function summarizeImages path csv=false begin set deployments = call DataFrame columns=list string path string deployment set images = call DataFrame columns=list string path string deployment string datetime string size string image for tuple di...
import pandas import csv import os import re import subprocess import sys def summarizeImages(path,csv=False): deployments = pandas.DataFrame(columns=['path','deployment']) images = pandas.DataFrame(columns=['path','deployment','datetime','size','image']) for dirName, subdirList, fileList in os.walk(path):...
Python
zaydzuhri_stack_edu_python
function check_handle self begin if terminate begin if pbar begin close pbar end raise call InterruptedError string TERMINATION SIGNAL end end function
def check_handle(self): if self.sighandle.terminate: if self.pbar: self.pbar.close() raise InterruptedError('TERMINATION SIGNAL')
Python
nomic_cornstack_python_v1
from abstract_test import AbstractTestContract , accounts class TestContract extends AbstractTestContract begin string run test with python -m unittest contracts.tests.event_factory.test_get_shares function __init__ self *args **kwargs begin call __init__ *args keyword kwargs set deploy_contracts = list event_factory_n...
from ..abstract_test import AbstractTestContract, accounts class TestContract(AbstractTestContract): """ run test with python -m unittest contracts.tests.event_factory.test_get_shares """ def __init__(self, *args, **kwargs): super(TestContract, self).__init__(*args, **kwargs) self.dep...
Python
zaydzuhri_stack_edu_python
from datetime import date function age_finder dob begin set dob_list = split dob string / 2 set start_time = call date integer dob_list at 2 integer dob_list at 1 integer dob_list at 0 set end_time = today set age = year - year - tuple month day < tuple month day return age end function comment main_pgm set aadhar = in...
from datetime import date def age_finder(dob): dob_list = dob.split('/',2) start_time = date(int(dob_list[2]),int(dob_list[1]),int(dob_list[0])) end_time = date.today() age = end_time.year - start_time.year - ((end_time.month,end_time.day) < (start_time.month,start_time.day)) ...
Python
zaydzuhri_stack_edu_python
function square_digits number begin string This function takes positive integers as input and returns an integer in which every digit of the input is squared int he same order. set numStr = string number set newStr = string for i in numStr begin set j = integer i set j = j ^ 2 set newStr = newStr + string j end return...
def square_digits(number): """ This function takes positive integers as input and returns an integer in which every digit of the input is squared int he same order. """ numStr = str(number) newStr = '' for i in numStr: j = int(i) j **= 2 newStr += str(...
Python
zaydzuhri_stack_edu_python
class Mensagem extends object begin set content : string set channel : string function __init__ self content channel begin set content = content set channel = channel end function end class function MakeMensagem content channel begin set mensagem = call Mensagem content channel return mensagem end function async func...
class Mensagem(object): content: "" channel: "" def __init__(self, content, channel): self.content = content self.channel = channel def MakeMensagem(content, channel): mensagem = Mensagem(content, channel) return mensagem async def mandarMensagem(msg, channel): msg = MakeMensagem(msg, channel) ...
Python
zaydzuhri_stack_edu_python
function soma a b begin return a + b end function function subtrai a b begin return a - b end function function mult a b begin return a * b end function function divisao a b begin return a / b end function print string Programa para calculos simples set num1 = decimal input string Digite um numero: set num2 = decimal i...
def soma( a, b): return a + b def subtrai(a, b): return a - b def mult(a, b): return a * b def divisao(a, b): return a / b print('Programa para calculos simples') num1 = float(input('Digite um numero: ')) num2 = float(input('Digite um outro numero: ')) print('Os numero digitados foram: %.2f e %.2f' ...
Python
zaydzuhri_stack_edu_python
function search_post self pax checkin checkout client_nationality currency **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string callback begin return call search_post_with_http_info pax checkin checkout client_nationality currency keyword kwargs end else begin set data = call search_po...
def search_post(self, pax, checkin, checkout, client_nationality, currency, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.search_post_with_http_info(pax, checkin, checkout, client_nationality, currency, **kwargs) else: (data) = ...
Python
nomic_cornstack_python_v1
from module import Character set bob = call Character function test_vitals begin assert call vitals == string Your health level is at 20 end function function test_energy begin assert call energy == 20 end function function test_haveInjury begin call haveInjury == string Your health level has been lowered to 20 end fun...
from module import Character bob = Character() def test_vitals(): assert bob.vitals() == "Your health level is at 20" def test_energy(): assert bob.energy() == 20 def test_haveInjury(): bob.haveInjury() == "Your health level has been lowered to 20" def test_hurt(): bob.hurt() assert bob.health == 10...
Python
zaydzuhri_stack_edu_python
function start_batch job input_args begin set mysampleslist = input_args at string mysampleslist for sample in mysampleslist begin call addChildJobFn runFASTQSORT input_args sample cores=12 disk=string 200000000000 end end function
def start_batch(job, input_args): mysampleslist = input_args['mysampleslist'] for sample in mysampleslist: job.addChildJobFn(runFASTQSORT, input_args, sample, cores=12, disk='200000000000')
Python
nomic_cornstack_python_v1
import cv2 import numpy as np function preenche img begin set imgfloodfill = copy img set tuple h w = shape at slice : 2 : set mask = zeros tuple h + 2 w + 2 uint8 call floodFill imgfloodfill mask tuple 0 0 255 set imgInvertida = call bitwise_not imgfloodfill set imgFinal = img ? imgInvertida return imgFinal end func...
import cv2 import numpy as np def preenche(img): imgfloodfill = img.copy() h, w = img.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) cv2.floodFill(imgfloodfill, mask, (0,0), 255); imgInvertida = cv2.bitwise_not(imgfloodfill) imgFinal = img | imgInvertida return imgFinal def redimensiona(img, escala=40): e...
Python
zaydzuhri_stack_edu_python
function get_tiles self begin set tiles = list for x in range position at 0 if expression is_horizontal then position at 0 + CAR_LENGTH else position at 0 + CAR_WIDTH begin for y in range position at 1 if expression is_horizontal then position at 1 + CAR_WIDTH else position at 1 + CAR_LENGTH begin append tiles tuple x...
def get_tiles(self): tiles = [] for x in range(self.position[0], self.position[0] + CAR_LENGTH if self.is_horizontal else self.position[0] + CAR_WIDTH): for y in range(self.position[1], self.position[1] + CAR_WIDTH if self.is_horizontal else...
Python
nomic_cornstack_python_v1
async function fleet_get_async fleet_id namespace=none x_additional_headers=none **kwargs begin if namespace is none begin set tuple namespace error = call get_services_namespace if error begin return tuple none error end end set request = call create fleet_id=fleet_id namespace=namespace return await call run_request_...
async def fleet_get_async( fleet_id: str, namespace: Optional[str] = None, x_additional_headers: Optional[Dict[str, str]] = None, **kwargs ): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = FleetGet.create( ...
Python
nomic_cornstack_python_v1
function key_not_starts_with self key_not_starts_with begin set _key_not_starts_with = key_not_starts_with end function
def key_not_starts_with(self, key_not_starts_with): self._key_not_starts_with = key_not_starts_with
Python
nomic_cornstack_python_v1
function new_review_view request begin set data = dict string success false ; string msg string if method == string POST begin comment check if the user has already logged in. comment if user has not logged in, return an error msg to frontend. comment if user has logged in, let user create a new review if not get sess...
def new_review_view(request): data = {'success': False, 'msg': ''} if request.method == 'POST': # check if the user has already logged in. # if user has not logged in, return an error msg to frontend. # if user has logged in, let user create a new review if not request.session.ge...
Python
nomic_cornstack_python_v1
function check_vowels sentence begin set vowels = string aeiou set consonants = string bcdfghjklmnpqrstvwxz set sentence = lower sentence comment remove spaces set sentence = replace sentence string string for i in range length sentence - 1 begin if sentence at i in vowels begin if sentence at i + 1 in consonants and ...
def check_vowels(sentence): vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxz' sentence = sentence.lower() sentence = sentence.replace(' ', '') # remove spaces for i in range(len(sentence) - 1): if sentence[i] in vowels: if sentence[i+1] in consonants and sentence[i+1] != 'y...
Python
greatdarklord_python_dataset
function subject self subject begin set _subject = subject end function
def subject(self, subject): self._subject = subject
Python
nomic_cornstack_python_v1
function zbToJcd x begin string 把坐标转换成交叉点的编号 set jcd = round x - MIN / CELL + 1 if jcd < 1 begin set jcd = 1 end else if jcd > 19 begin set jcd = 19 end return jcd end function function jcdTozb jcd begin return MIN + jcd - 1 * CELL end function function xiuzheng x begin set jcd = call zbToJcd x return call jcdTozb jcd ...
def zbToJcd(x): """把坐标转换成交叉点的编号""" jcd = round((x - MIN) / CELL + 1) if jcd < 1: jcd = 1 elif jcd > 19: jcd = 19 return jcd def jcdTozb(jcd): return MIN + (jcd - 1) * CELL def xiuzheng(x): jcd = zbToJcd(x) return jcdTozb(jcd)
Python
zaydzuhri_stack_edu_python
function apply_non_max_suppression boxes scores iou_thresh=0.45 top_k=200 begin set selected_indices = zeros shape=length scores if boxes is none or length boxes == 0 begin return selected_indices end set x_min = boxes at tuple slice : : 0 set y_min = boxes at tuple slice : : 1 set x_max = boxes at tuple slice :...
def apply_non_max_suppression(boxes, scores, iou_thresh=.45, top_k=200): selected_indices = np.zeros(shape=len(scores)) if boxes is None or len(boxes) == 0: return selected_indices x_min = boxes[:, 0] y_min = boxes[:, 1] x_max = boxes[:, 2] y_max = boxes[:, 3] areas = (x_max - x_min...
Python
nomic_cornstack_python_v1
function log_posterior self t T=none begin set tuple t T = call _prep_t_T t T set tuple mu alpha theta = call get_params return call call _log_posterior t T list mu alpha theta end function
def log_posterior(self, t, T=None): t, T = self._prep_t_T(t, T) mu, alpha, theta = self.get_params() return self._log_posterior(t, T)([mu, alpha, theta])
Python
nomic_cornstack_python_v1
function add_executor *args **kwargs begin global tables global metadata set table = get kwargs string table set row = list comprehension strip c for c in get kwargs string row set data = get tables table set meta_cols = get get metadata table string cols set seq = get get metadata table string seq set uniq = get get m...
def add_executor(*args, **kwargs): global tables global metadata table = kwargs.get("table") row = [c.strip() for c in kwargs.get("row")] data = tables.get(table) meta_cols = metadata.get(table).get("cols") seq = metadata.get(table).get("seq") uniq = metadata.get(table).get("uniq") ...
Python
nomic_cornstack_python_v1
comment import the top level of domain name in settings, package mangager if not available comment this program gets the shortened domain name from tld import get_tld function get_domain_name url begin set domain_name = call get_tld url return domain_name end function print call get_domain_name string https://www.espn....
# import the top level of domain name in settings, package mangager if not available # this program gets the shortened domain name from tld import get_tld def get_domain_name(url): domain_name = get_tld(url) return domain_name print(get_domain_name('https://www.espn.com'))
Python
zaydzuhri_stack_edu_python
function calc_power volts amps pf begin try begin set s = volts * amps set p = s * pf set q = square root s ^ 2 - p ^ 2 return tuple p q s end except tuple ValueError TypeError begin return tuple none none none end end function
def calc_power(volts, amps, pf): try: s = volts * amps p = s * pf q = math.sqrt(s**2 - p**2) return (p, q, s) except (ValueError, TypeError): return (None, None, None)
Python
nomic_cornstack_python_v1
from __future__ import print_function import json import requests import datetime import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import json import sys function get_all_request url token p...
from __future__ import print_function import json import requests import datetime import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import json import sys def get_all_request(url, token, par...
Python
zaydzuhri_stack_edu_python
set t = integer input while t != 0 begin set n = integer input set monkey = list map int split input set steps = set insert monkey 0 0 for i in range 1 n + 1 begin if monkey at i == 0 begin continue end set count = 0 set current = i set block = i while true begin set current = monkey at current set monkey at block = 0 ...
t=int(input()) while(t!=0): n=int(input()) monkey=list(map(int,input().split())) steps=set() monkey.insert(0,0) for i in range(1,n+1): if(monkey[i]==0): continue count=0 current=i block=i while(True): current=monkey[current] ...
Python
zaydzuhri_stack_edu_python
function find_most_frequent_element list begin set count_map = dict set max_element = list at 0 set max_count = 1 for num in list begin if num in count_map begin set count_map at num = count_map at num + 1 end else begin set count_map at num = 1 end end for num in count_map begin if count_map at num > max_count begin ...
def find_most_frequent_element(list): count_map = {} max_element= list[0] max_count = 1 for num in list: if num in count_map: count_map[num] += 1 else: count_map[num] = 1 for num in count_map: if count_map[num] > max_count: max_element = num max_count = count_map[num] return max_element
Python
jtatman_500k
function GetArchiveTagForBranch issue_num branch_name existing_tags pattern begin set proposed_tag = format pattern keyword dict string issue issue_num ; string branch branch_name for suffix_num in count itertools 1 begin if suffix_num == 1 begin set to_check = proposed_tag end else begin set to_check = string %s-%d % ...
def GetArchiveTagForBranch(issue_num, branch_name, existing_tags, pattern): proposed_tag = pattern.format(**{'issue': issue_num, 'branch': branch_name}) for suffix_num in itertools.count(1): if suffix_num == 1: to_check = proposed_tag else: to_check = '%s-%d' % (proposed_tag, suffix_num) i...
Python
nomic_cornstack_python_v1
function push_logs resp image_id begin try begin while true begin try begin set data = next resp set status = get data string status if string id not in data begin call sprint status end else begin set _id = get data string id if string exists in status begin warning string { _id } : { status } continue end else if str...
def push_logs(resp: Iterator, image_id: str): try: while True: try: data = next(resp) status = data.get('status') if 'id' not in data: sprint(status) else: ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- class NodeList begin function __init__ self data=none begin set data = data set next = none end function function mostrar self begin print data if next != none begin call mostrar end end function function size self begin set cantidad = 0 if next == none begin set cantidad = 1 end else begi...
# -*- coding: utf-8 -*- class NodeList: def __init__(self, data = None): self.data = data self.next = None def mostrar(self): print(self.data) if self.next != None: self.next.mostrar() def size(self): cantidad = 0 if self.next == None: ...
Python
zaydzuhri_stack_edu_python
function Run self begin if not start and not stop and not cmd begin raise call VMError string Must specify one of start, stop, or cmd. end if start begin start self end if cmd begin return call RemoteCommand cmd end if stop begin call Stop end end function
def Run(self): if not self.start and not self.stop and not self.cmd: raise VMError('Must specify one of start, stop, or cmd.') if self.start: self.Start() if self.cmd: return self.RemoteCommand(self.cmd) if self.stop: self.Stop()
Python
nomic_cornstack_python_v1
function mle_iid_exp t begin with catch warnings begin simple filter string ignore set res = minimize fun=lambda params t -> - call log_like_iid_exp_log_params params t x0=array list 1 1 args=tuple t method=string Powell end if success begin return x end else begin raise call RuntimeError string Convergence failed with...
def mle_iid_exp(t): with warnings.catch_warnings(): warnings.simplefilter("ignore") res = scipy.optimize.minimize( fun=lambda params, t: -log_like_iid_exp_log_params(params, t), x0=np.array([1, 1]), args=(t,), method='Powell' ) if res...
Python
nomic_cornstack_python_v1
import re import sys import logging import nltk import joblib import numpy as np import pandas as pd from sqlalchemy import create_engine from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from sklearn.model_selection import train_test_split , GridSearchCV ...
import re import sys import logging import nltk import joblib import numpy as np import pandas as pd from sqlalchemy import create_engine from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from sklearn.model_selection import train_test_split, GridSearchCV f...
Python
zaydzuhri_stack_edu_python
function _copy_to_redshift table bucket_key_pair begin set query_cmd = string for _ in bucket_key_pair begin set tuple bucket key = _ comment s3://<bucket_name>/symbols/DOX.csv set file = string s3:// + bucket + string / + key set query_cmd = query_cmd + string copy %s from '%s' credentials '<your_iam_role_to_write_to...
def _copy_to_redshift(table, bucket_key_pair): query_cmd = "" for _ in bucket_key_pair: bucket, key = _ # s3://<bucket_name>/symbols/DOX.csv file = 's3://' + bucket + '/' + key query_cmd = query_cmd + """ copy %s from '%s' credentials '<your_iam_role_to_write_to_Redshift...
Python
nomic_cornstack_python_v1
from atoms import Atoms class NoSuchModelError extends Exception begin function __init__ self name begin set message = format string Model "{}" does not exist name call __init__ message set name = name end function end class class ModelAlreadyExistsError extends Exception begin function __init__ self name begin set mes...
from atoms import Atoms class NoSuchModelError(Exception): def __init__(self, name): message = "Model \"{}\" does not exist".format(name) super(NoSuchModelError, self).__init__(message) self.name = name class ModelAlreadyExistsError(Exception): def __init__(self, name...
Python
zaydzuhri_stack_edu_python
comment pylint: disable=unused-argument function _read_mptcp_remove self bits size kind begin set adid = list for _ in size begin append adid call _read_unpack 1 end set data = dictionary kind=kind length=size + 1 subtype=call MPTCPOption 4 removeaddr=dictionary addr_id=tuple adid return data end function
def _read_mptcp_remove(self, bits, size, kind): # pylint: disable=unused-argument adid = [] for _ in size: adid.append(self._read_unpack(1)) data = dict( kind=kind, length=size + 1, subtype=MPTCPOption(4), removeaddr=dict( ...
Python
nomic_cornstack_python_v1
comment 6, 代理模式 string # 代理重视实现代理对象的接口 1, 需要一个更接近客户的虚拟资源的时候,它可以替代另一个网络中的实际资源,如远程代理 2,需要监控对资源的访问时,如网络代理和实例计数代理 3,需要保护资源或对象(保护代理),因为直接访问资源将导致安全问题或危机资源,例如反向代理服务 4,需要从开销大的计算或网络操作中优化对结果的访问,以便不必每次都指向计算,如缓存代理 from abc import ABCMeta , abstractmethod class Employee begin string An Employee class function __init__ self name age...
# 6, 代理模式 """ # 代理重视实现代理对象的接口 1, 需要一个更接近客户的虚拟资源的时候,它可以替代另一个网络中的实际资源,如远程代理 2,需要监控对资源的访问时,如网络代理和实例计数代理 3,需要保护资源或对象(保护代理),因为直接访问资源将导致安全问题或危机资源,例如反向代理服务 4,需要从开销大的计算或网络操作中优化对结果的访问,以便不必每次都指向计算,如缓存代理 """ from abc import ABCMeta, abstractmethod class Employee(metaclass=ABCMeta): """An Employee class""" def __init__(...
Python
zaydzuhri_stack_edu_python
function on_square integer_number begin if integer_number > 0 and integer_number < 65 begin return 1 ? integer_number - 1 end else begin raise call ValueError string Invalid Square end end function function total_after integer_number begin if integer_number > 0 and integer_number < 65 begin return 1 ? integer_number - ...
def on_square(integer_number): if integer_number > 0 and integer_number < 65: return 1<<integer_number-1 else: raise ValueError("Invalid Square") def total_after(integer_number): if integer_number > 0 and integer_number < 65: return (1<<(integer_number)) - 1 else: raise...
Python
zaydzuhri_stack_edu_python
import scipy.io.wavfile as wavio import numpy.fft as nfft import numpy import matplotlib.pyplot as plt call discontinuity_eval function fft_that_file begin set tuple poop samples = read wavio string /home/carl/Downloads/audiocheck.net_sin_1000Hz_-3dBFS_3s.wav set length = length samples set t = array range 0 length / p...
import scipy.io.wavfile as wavio import numpy.fft as nfft import numpy import matplotlib.pyplot as plt discontinuity_eval() def fft_that_file(): poop, samples = wavio.read('/home/carl/Downloads/audiocheck.net_sin_1000Hz_-3dBFS_3s.wav') length = len(samples) t = numpy.arange(0, (length/poop), (1/poop)) ...
Python
zaydzuhri_stack_edu_python
import config import logging import numpy set train_file_path = string set test_file_path = string set train_data_features = list set train_data_target = list set test_data_features = list set test_data_target = list string Takes 2 args and returns array of length 2 First: first line from csv to put in array Last...
import config import logging import numpy train_file_path = "" test_file_path = "" train_data_features = [] train_data_target = [] test_data_features = [] test_data_target = [] """ Takes 2 args and returns array of length 2 First: first line from csv to put in array Last: last line from csv to put in array Element...
Python
zaydzuhri_stack_edu_python
function test_should_not_retry check instance begin with patch string datadog_checks.php_fpm.php_fpm.requests as r begin set side_effect = call FooException string Generic http error here with raises FooException begin call _process_status instance at string status_url none list none 10 true false end end end function
def test_should_not_retry(check, instance): with mock.patch('datadog_checks.php_fpm.php_fpm.requests') as r: r.get.side_effect = FooException("Generic http error here") with pytest.raises(FooException): check._process_status(instance['status_url'], None, [], None, 10, True, False)
Python
nomic_cornstack_python_v1
comment TODO: Better name, serializePage, pageData function getPage self begin comment Get all parameters from page set param_dict = call getState if _data begin set param_dict at string data_name = string name set param_dict at string data_id = string id end return param_dict end function
def getPage(self) -> dict: # TODO: Better name, serializePage, pageData # Get all parameters from page param_dict = self.getState() if self._data: param_dict['data_name'] = str(self._data.name) param_dict['data_id'] = str(self._data.id) return param_dict
Python
nomic_cornstack_python_v1
function alignHoriz self value begin set __dict__ at string alignHoriz = value set _needSetText = true end function
def alignHoriz(self, value): self.__dict__['alignHoriz'] = value self._needSetText = True
Python
nomic_cornstack_python_v1
function add_key self new_key begin if new_key not in keys begin append keys call format_key new_key end return end function
def add_key(self, new_key): if new_key not in self.keys: self.keys.append(self.format_key(new_key)) return
Python
nomic_cornstack_python_v1
comment flake8: noqa: E226 from random import random from random import randint from cymunk import Body , Circle , Space , Segment , Vec2d from kivy.app import App from kivy.base import EventLoop from kivy.clock import Clock from kivy.core.window import Keyboard , Window from kivy.logger import Logger from kivy.uix.scr...
# flake8: noqa: E226 from random import random from random import randint from cymunk import Body, Circle, Space, Segment, Vec2d from kivy.app import App from kivy.base import EventLoop from kivy.clock import Clock from kivy.core.window import Keyboard, Window from kivy.logger import Logger from kivy.uix.screenmanage...
Python
zaydzuhri_stack_edu_python
from openspending.model import Dataset from openspending.test import DatabaseTestCase , helpers as h class MockEntry extends dict begin set name = string testentry set label = string An Entry function __init__ self begin set self at string name = name set self at string label = label end function end class function mak...
from openspending.model import Dataset from openspending.test import DatabaseTestCase, helpers as h class MockEntry(dict): name = "testentry" label = "An Entry" def __init__(self): self['name'] = self.name self['label'] = self.label def make_dataset(): return Dataset(name='testdataset...
Python
zaydzuhri_stack_edu_python
function publish self trigger_name payload begin call publish trigger_name payload end function
def publish(self, trigger_name, payload): self.pubsub.publish(trigger_name, payload)
Python
nomic_cornstack_python_v1
function save self begin set config_file = DEFAULT_CONFIG_LOCAL for filename in CONFIG_LOCAL begin if is file path filename begin set config_file = filename break end end with open config_file string w as f begin try begin set stream = dump call to_dict indent=2 default_flow_style=false write f stream end except Except...
def save(self) -> bool: config_file = self.DEFAULT_CONFIG_LOCAL for filename in self.CONFIG_LOCAL: if os.path.isfile(filename): config_file = filename break with open(config_file, "w") as f: try: stream = yaml.dump(self.to_...
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- comment author = sw import numpy as np import os , cv2 , copy , random import xml.etree.ElementTree as ET class load_data extends object begin function __init__ self BASE_DIR CLASS begin comment print(self.data_path) set BASE_DIR = BASE_DIR set img_size = 448 set CLASS = CLASS set n_class =...
# -*- coding:utf-8 -*- # author = sw import numpy as np import os,cv2,copy,random import xml.etree.ElementTree as ET class load_data(object): def __init__(self,BASE_DIR,CLASS): # print(self.data_path) self.BASE_DIR = BASE_DIR self.img_size = 448 self.CLASS = CLASS self.n_cla...
Python
zaydzuhri_stack_edu_python
comment Write a Python file that uploads an image to your comment Twitter account. Make sure to use the comment hashtags #UMSI-206 #Proj3 in the tweet. comment You will demo this live for grading. import tweepy import nltk import glob import random import os from TwitterAPI import TwitterAPI comment print("""No output ...
# Write a Python file that uploads an image to your # Twitter account. Make sure to use the # hashtags #UMSI-206 #Proj3 in the tweet. # You will demo this live for grading. import tweepy import nltk import glob import random import os from TwitterAPI import TwitterAPI #print("""No output necessary although you ca...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import os from threading import Thread from bst import * from rbt import * from util import * set allPermList = list string 15K string 30K string 45K string 60K string 75K string 90K string 105K string 120K string 135K string 150K set types = list string Perm string Sorted function main be...
# -*- coding: utf-8 -*- import os from threading import Thread from bst import * from rbt import * from util import * allPermList = ["15K", "30K", "45K", "60K", "75K", "90K", "105K", "120K", "135K", "150K"] types = ["Perm", "Sorted"] def main(): sys.setrecursionlimit(15000) search = "" exitVar = False ...
Python
zaydzuhri_stack_edu_python
function get_utma self *args **kwargs begin set user_id = get kwargs string user_id if not has attribute self string _utma or string force in kwargs and string user_id in kwargs begin try begin set ga = get objects user_id=user_id set _utma = utma set _ip = ip end except DoesNotExist begin set _utma = none end if not _...
def get_utma(self, *args, **kwargs): user_id = kwargs.get('user_id') if not hasattr(self, '_utma') or ('force' in kwargs and 'user_id' in kwargs): try: ga = Pygawrapper.objects.get(user_id=user_id) _utma = ga.utma _ip = ga.ip except...
Python
nomic_cornstack_python_v1
string https://www.ericthecoder.com/2021/02/15/chaquopy-sqlite3-tutorial-android-python-tutorial/ https://towardsdatascience.com/android-app-for-notion-automation-using-chaquopy-863e72fa4ecd import json function desconto x begin return x - 10 end function function preco x begin set y = call gui_getdesconto 2 return x -...
""" https://www.ericthecoder.com/2021/02/15/chaquopy-sqlite3-tutorial-android-python-tutorial/ https://towardsdatascience.com/android-app-for-notion-automation-using-chaquopy-863e72fa4ecd """ import json def desconto(x): return x - 10 def preco(x): y = gui_getdesconto(2) return x - y def valorTotal(x): ...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf class LearningStrategy begin function __init__ self begin pass end function function schedule self epoch begin pass end function end class class StepLearningStrategy begin function __init__ self build_dict begin set initial_lr = build_dict at string initial_lr set steps = build_dict at string st...
import tensorflow as tf class LearningStrategy: def __init__(self): pass def schedule(self, epoch): pass class StepLearningStrategy: def __init__(self, build_dict): self.initial_lr = build_dict["initial_lr"] self.steps = build_dict["steps"] def schedule(self, epoch)...
Python
zaydzuhri_stack_edu_python
function get_lambda_latest_version_num fn_arn region begin set client = call client string lambda region_name=region set response = call list_versions_by_function FunctionName=fn_arn for v in response at string Versions begin if v at string Version == string $LATEST begin set latest_hash = v at string CodeSha256 break ...
def get_lambda_latest_version_num(fn_arn: str, region: str) -> int: client = boto3.client('lambda', region_name=region) response = client.list_versions_by_function(FunctionName=fn_arn) for v in response['Versions']: if v['Version'] == '$LATEST': latest_hash = v['CodeSha256'] ...
Python
nomic_cornstack_python_v1
set f = lambda c -> if expression c == string 9 then string 1 else string 9 print join string list map f input
f = lambda c : "1" if c == "9" else "9" print(''.join(list(map(f, input()))))
Python
zaydzuhri_stack_edu_python
function _parse_args self cmd begin if bfield begin append cmd string -b end if cless begin append cmd string -cl end if cless_only begin append cmd string -clo end if spec_rel begin append cmd string -s end if gen_rel begin append cmd string -g end if transforms begin append cmd string -t end if shear begin append cmd...
def _parse_args(self, cmd): if self.bfield: cmd.append("-b") if self.cless: cmd.append("-cl") if self.cless_only: cmd.append("-clo") if self.spec_rel: cmd.append("-s") if self.gen_rel: cmd.append("-g") if self.tr...
Python
nomic_cornstack_python_v1
function rounded_padding_box self begin return call rounded_box border_top_width border_right_width border_bottom_width border_left_width end function
def rounded_padding_box(self): return self.rounded_box( self.border_top_width, self.border_right_width, self.border_bottom_width, self.border_left_width)
Python
nomic_cornstack_python_v1
function add_distance_dimension routing distance_evaluator begin comment here distance_evaluator is dist_mtx set distance = string Distance comment assume no limitation on robot travel distance set maximum_distance = 1000000000000 call AddDimension distance_evaluator 0 maximum_distance true distance comment null slack ...
def add_distance_dimension(routing, distance_evaluator): # here distance_evaluator is dist_mtx distance = "Distance" maximum_distance = 1000000000000 # assume no limitation on robot travel distance routing.AddDimension( distance_evaluator, 0, # null slack maximum_distance,...
Python
nomic_cornstack_python_v1
string Author: Firoj Kumar Date: 01-05-2020 This program is check number positive or negative statement program ! set a = integer input string enter no= if a > 0 begin print string no is possitive end else if a == 0 begin print string no is zero end else begin print string no is negative end string output enter no = -1...
""" Author: Firoj Kumar Date: 01-05-2020 This program is check number positive or negative statement program !""" a=int(input("enter no=")) if (a>0): print("no is possitive") elif (a==0): print("no is zero") else: print("no is negative") """output enter no = -1 no is negative """
Python
zaydzuhri_stack_edu_python
string This program renames a list of files placed in a directory based on the file created date. i.e. the iterator will start with the file thiat is created first and rename subsequently import os comment the directory in which the files are placed goes here set dir = string D:\Aswin\RenameMe\ set filenames = list dir...
''' This program renames a list of files placed in a directory based on the file created date. i.e. the iterator will start with the file thiat is created first and rename subsequently ''' import os dir = "D:\\Aswin\\RenameMe\\" #the directory in which the files are placed goes here filenames = os.listdir(dir) filen...
Python
zaydzuhri_stack_edu_python
import pygame call init comment 创建游戏主窗口 set screen = call set_mode tuple 480 700 0 32 comment 1.加载图像数据 set bg = load image string ./images/background.png set hero = load image string ./images/me1.png comment 2.blit绘制图像 call blit bg tuple 0 0 call blit hero tuple 150 300 comment 3.更新屏幕的显示 update display comment 创建时钟对象 s...
import pygame pygame.init() # 创建游戏主窗口 screen = pygame.display.set_mode((480, 700), 0, 32) # 1.加载图像数据 bg = pygame.image.load('./images/background.png') hero = pygame.image.load('./images/me1.png') # 2.blit绘制图像 screen.blit(bg, (0, 0)) screen.blit(hero, (150, 300)) # 3.更新屏幕的显示 pygame.display.update() # 创建时钟对象 clo...
Python
zaydzuhri_stack_edu_python
function mark_completed self begin call clear_flag call expand_name string requests-pending end function
def mark_completed(self): clear_flag(self.expand_name('requests-pending'))
Python
nomic_cornstack_python_v1
import random set i = range 1 46 set a = sorted random sample i 6 comment 차집합 function difference j k begin set _k = set k return list comprehension item for item in j if item not in _k end function while true begin set first_Question = input string 모든 번호를 자동 추첨 하실겁니까?[y/n] if first_Question != string y and first_Quest...
import random i= range(1,46) a=sorted(random.sample(i,6)) def difference(j,k): #차집합 _k=set(k) return [item for item in j if item not in _k] while True: first_Question = input('모든 번호를 자동 추첨 하실겁니까?[y/n]') if first_Question !='y' and first_Question !='n': print('[y/n]중에서 골라주세요.') elif...
Python
zaydzuhri_stack_edu_python
function _getLilyDurationAligned self alignBeat begin comment Hmmm... didn't seem to get it right. Poke further into this call _dbg format string - - - - - - - - alignBeat = {} alignBeat if alignBeat == none begin set alignBeat = call getBeatNum if alignBeat == none begin return call _getLilyDuration end end if duratio...
def _getLilyDurationAligned(self, alignBeat): # Hmmm... didn't seem to get it right. Poke further into this _dbg(" - - - - - - - - alignBeat = {}".format(alignBeat)) if alignBeat == None: alignBeat = self.getBeatNum() if alignBeat == None: ...
Python
nomic_cornstack_python_v1
function getSplitType self begin raise call AbstractMethodException __class__ end function
def getSplitType(self): raise AbstractMethodException(self.__class__)
Python
nomic_cornstack_python_v1
function get_output_list file_row begin set data = list set list_mammo = call get_row_nr file_row string mammo_params set list_us = call get_row_nr file_row string us_params set list_mri = call get_row_nr file_row string mri_params set all_params = list_mammo + list_us + list_mri for x in range length all_params begin...
def get_output_list(file_row): data = [] list_mammo = get_row_nr(file_row, 'mammo_params') list_us = get_row_nr(file_row, 'us_params') list_mri = get_row_nr(file_row, 'mri_params') all_params = list_mammo + list_us + list_mri for x in range(len(all_params)): d = {'Name': '', 'Condition d...
Python
nomic_cornstack_python_v1
function plot_accuracy_score score C_range gamma_range kernel_range begin set titles = list comprehension format string {} SVM Accuracy Score x for x in kernel_range set tuple fig axes = call subplots nrows=1 ncols=length kernel_range figsize=tuple 10 5 for tuple index tuple ax title in enumerate zip axes titles begin ...
def plot_accuracy_score(score, C_range, gamma_range, kernel_range): titles = ['{} SVM Accuracy Score'.format(x) for x in kernel_range] fig, axes = plt.subplots(nrows=1, ncols=len(kernel_range), figsize=(10, 5)) for index, (ax, title) in enumerate(zip(axes, titles)): im = ax.imshow(score[:, :, index], vmin=0.5,...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment width set w = 320 comment height set h = 240 comment counter set c = 0 comment size set size = tuple w h comment filename set filename = string ./new-image-02.pbm set bit = string 0 with open filename string w as fd begin write fd string P1 write fd str...
#!/usr/bin/env python # -*- coding: utf-8 -*- w = 320 # width h = 240 # height c = 0 # counter size=(w,h) # size filename = "./new-image-02.pbm" # filename bit = "0" with open(filename, "w") as fd: f...
Python
zaydzuhri_stack_edu_python
import random string http://montypython.wikia.com/wiki/Cheese_Shop_sketch 43 cheeses are mentioned in the in the "Cheese Shop" sketch (from Monty Python's Flying Circus) set cheeses_43 = tuple string Red Leicester string Tilsit string Caerphilly string Bel Paese string Red Windsor string Stilton string Emmental string ...
import random '''http://montypython.wikia.com/wiki/Cheese_Shop_sketch 43 cheeses are mentioned in the in the "Cheese Shop" sketch (from Monty Python's Flying Circus) ''' cheeses_43 = ( 'Red Leicester', 'Tilsit', 'Caerphilly', 'Bel Paese', 'Red Windsor', 'Stilton', 'Emmental', 'Gruyèr...
Python
zaydzuhri_stack_edu_python
function test_issues_with_field_without_issues self get_query_url_mock begin set jira_filter = call JiraFilter string http://jira/ string username string password field_name=string customfield_11700 set return_value = dict string searchUrl string http://jira/search ; string viewUrl string http://jira/view ; string tota...
def test_issues_with_field_without_issues(self, get_query_url_mock): jira_filter = JiraFilter('http://jira/', 'username', 'password', field_name='customfield_11700') get_query_url_mock.return_value = \ {"searchUrl": "http://jira/search", "viewUrl": "http://jira/view", "total": "5", "issues":...
Python
nomic_cornstack_python_v1