code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function __eq__ self other begin if not is instance other QualityAssuranceChecksDto begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, QualityAssuranceChecksDto): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
function plot_multiplicity_hist multiplicity ax=none outfile=none quartils=false **kwargs begin from matplotlib.ticker import MaxNLocator set ax = if expression ax is none then call gca else ax call set_visible false call set_visible false set m = sort np multiplicity set xmin = min set xmax = max if string label not i...
def plot_multiplicity_hist(multiplicity, ax=None, outfile=None, quartils=False, **kwargs): from matplotlib.ticker import MaxNLocator ax = plt.gca() if ax is None else ax ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) m = np.sort(multiplicity) xmin = multiplicity.min(...
Python
nomic_cornstack_python_v1
function connect begin set scope = list string https://spreadsheets.google.com/feeds string https://www.googleapis.com/auth/drive set creds = call from_json_keyfile_name string client_secret.json scope set client = call authorize creds return client end function
def connect(): scope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] creds = ServiceAccountCredentials.from_json_keyfile_name( 'client_secret.json', scope) client = gspread.authorize(creds) return client
Python
nomic_cornstack_python_v1
string author: roberto.polli@par-tec.it This class tests the SFTP Volume access. To access: - the container jboss63 - with the volumes "/shared", "/var/log" # sftp -P 10022 jboss63@localhost # no password for now # pwd / # ls /shared /var from dockerdns.sftp import unix from twisted.python import log from nose.tools im...
""" author: roberto.polli@par-tec.it This class tests the SFTP Volume access. To access: - the container jboss63 - with the volumes "/shared", "/var/log" # sftp -P 10022 jboss63@localhost # no password for now # pwd / # ls /shared /var """ from dockerdns.sftp impo...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Matthew Page CSCS1240 Spring 2014 comment attempting to work through the recurring problem I have on my one desktop comment to create a programming solution that has a script that checks local IP address comment of the machine and compares it with router settings for ssh port forwar...
#!/usr/bin/env python # Matthew Page CSCS1240 Spring 2014 # attempting to work through the recurring problem I have on my one desktop # to create a programming solution that has a script that checks local IP address # of the machine and compares it with router settings for ssh port forward for # given local IP address,...
Python
zaydzuhri_stack_edu_python
import random comment 定义fight函数实现游戏逻辑 function fight enemy_hp enemy_power begin set my_hp = 1000 set my_power = 200 comment 敌人的血量和攻击力 print string 敌人的血量 { enemy_hp } ,攻击力为 { enemy_power } comment 加入循环,游戏进行多轮 while true begin set my_hp = my_hp - enemy_power set enemy_hp = enemy_hp - my_power comment 判断谁的血量小于等于0 if my_hp...
import random # 定义fight函数实现游戏逻辑 def fight(enemy_hp,enemy_power): my_hp = 1000 my_power = 200 # 敌人的血量和攻击力 print(f"敌人的血量{enemy_hp},攻击力为{enemy_power}") # 加入循环,游戏进行多轮 while True: my_hp = my_hp - enemy_power enemy_hp = enemy_hp - my_power #判断谁的血量小于等于0 if my_hp <= 0: ...
Python
zaydzuhri_stack_edu_python
set num = integer input string set dup = num set sum = 0 while num > 0 begin set sum = sum + 1 set num = num // 10 end print sum
num=int(input("")) dup=num sum=0 while(num>0): sum=sum+1 num=num//10 print(sum)
Python
zaydzuhri_stack_edu_python
function recentered_at image x y begin return call centered_at image array tuple x y call get_image_rect image end function
def recentered_at(image, x, y): return centered_at( image, numpy.array((x, y)), get_image_rect(image))
Python
nomic_cornstack_python_v1
function two_sum arr k begin comment Store unique elements and also provide O(1) contains check. set hm = set arr for e in arr begin if k - e in hm begin return true end end return false end function
def two_sum(arr: list, k: int) -> bool: hm = set(arr) # Store unique elements and also provide O(1) contains check. for e in arr: if k - e in hm: return True return False
Python
nomic_cornstack_python_v1
comment !pip3 install --upgrade tensorflow comment alternatively in the terminal: comment python3 -m pip install --upgrade tensorflow import tensorflow as tf __version__ comment Create some nonlinear toy data. import matplotlib.pyplot as plt import numpy as np set ct = ones 20 comment variable, 20 rows set X1 = call no...
#!pip3 install --upgrade tensorflow #alternatively in the terminal: #python3 -m pip install --upgrade tensorflow import tensorflow as tf tf.__version__ ############################################# #Create some nonlinear toy data. import matplotlib.pyplot as plt import numpy as np ct = np.ones(20) X1 = np.random.nor...
Python
zaydzuhri_stack_edu_python
comment 整数NをK進数に変換し、その桁数を出力する set result = string set i = 0 set k = 0 while T != 0 begin set result = string T % K + result set T = T // K end print length result
# 整数NをK進数に変換し、その桁数を出力する result = "" i = 0 k = 0 while (T != 0): result = str(T%K)+result T = T//K print (len(result))
Python
zaydzuhri_stack_edu_python
string Class that helps with pulling the request from the given URL Used to fetch the HTML import requests class HTMLFetcher begin function __init__ self begin pass end function decorator staticmethod function get_from_url url begin set req = get requests url return text end function end class
""" Class that helps with pulling the request from the given URL Used to fetch the HTML """ import requests class HTMLFetcher: def __init__(self): pass @staticmethod def get_from_url(url): req = requests.get(url) return req.text
Python
zaydzuhri_stack_edu_python
import sys function main begin set temp = list with open argv at 1 as input begin for line in input begin set data = split line string append temp data end end comment use this part first comment f=open('final-peaks-no-offtargets.txt', 'w') comment f3=open('off-target-peaks.txt', 'w') comment for x in range(0, len(tem...
import sys def main(): temp=[] with open(sys.argv[1]) as input: for line in input: data=line.split('\t') temp.append(data) #use this part first #f=open('final-peaks-no-offtargets.txt', 'w') #f3=open('off-target-peaks.txt', 'w') #for x in range(0, len(temp)): # if temp[x][4]=='FALSE\n': # for i in r...
Python
zaydzuhri_stack_edu_python
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns call set_style string darkgrid print string Importing Covid Conf Analysis set URL = string https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confir...
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns sns.set_style('darkgrid') print('Importing Covid Conf Analysis') URL = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv' REC...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt function generate n begin set x = random integer 2 size=n set a = cumulative sum np x + random integer 2 size=n set w = call mod x + call floor_divide random integer 3 size=n 2 2 return tuple x a w end function function guess a w=none lookahead=10 begin set n = length ...
import numpy as np import matplotlib.pyplot as plt def generate(n): x = np.random.randint(2, size=n) a = np.cumsum(x) + np.random.randint(2, size=n) w = np.mod(x + np.floor_divide(np.random.randint(3, size=n), 2), 2) return x, a, w def guess(a, w=None, lookahead=10): n = len(a) x_ = np.zeros...
Python
zaydzuhri_stack_edu_python
comment BOLETA DE VENTA MERCADO SANTA ANITA import os set carne = argv at 1 set P_U = decimal argv at 2 set unidad_1 = integer argv at 3 set TOTAL = P_U * unidad_1 print string ############################################### # print string # MERCADO ´´SANTA ANITA´´ # print string # print string # TIPO DE CARNE: + carne...
# BOLETA DE VENTA MERCADO SANTA ANITA import os carne =(os.sys.argv[1]) P_U = float(os.sys.argv[2]) unidad_1 = int(os.sys.argv[3]) TOTAL = P_U * unidad_1 print ( " ############################################### # " ) print ( " # MERCADO ´´SANTA ANITA´´ # " ) print ( " # " ) print ( " # TIPO DE CARNE: " ...
Python
zaydzuhri_stack_edu_python
function improve_policy self num_improvements begin set policy = call get_policy set batch_size = config at string train_batch_size set env_batch_size = integer batch_size * config at string real_data_ratio set model_batch_size = batch_size - env_batch_size set stats = dict for _ in range num_improvements begin set sa...
def improve_policy(self, num_improvements: int) -> Dict[str, float]: policy = self.get_policy() batch_size = self.config["train_batch_size"] env_batch_size = int(batch_size * self.config["real_data_ratio"]) model_batch_size = batch_size - env_batch_size stats = {} for _ ...
Python
nomic_cornstack_python_v1
while true begin set choice = input string 메뉴를 입력하세요 : if choice in menu begin set price = menu at choice print choice + string 는 + string price + string 원 입니다. end else begin print choice + string 메뉴는 없습니다 end end
while True: choice= input("메뉴를 입력하세요 : ") if choice in menu: price = menu[choice] print(choice + "는 " + str(price) + "원 입니다.") else: print(choice + " 메뉴는 없습니다")
Python
zaydzuhri_stack_edu_python
function publish_data_to_predictorqueue self data begin set response = none set corr_id = string uuid 4 call basic_publish exchange=string routing_key=string Predictor properties=call BasicProperties reply_to=callback_queue correlation_id=corr_id body=data while response is none begin call process_data_events end retu...
def publish_data_to_predictorqueue(self, data): self.response = None self.corr_id = str(uuid.uuid4()) self.channel.basic_publish( exchange='', routing_key='Predictor', properties=pika.BasicProperties( reply_to=self.callback_queue, ...
Python
nomic_cornstack_python_v1
function Display self unused_args result begin call PrettyPrint result end function
def Display(self, unused_args, result): util.PrettyPrint(result)
Python
nomic_cornstack_python_v1
function sendMessage self message timeout=0.1 begin comment flush the read buffer first comment read as many chars as are in the buffer set prevOut = read com call inWaiting end function
def sendMessage(self, message, timeout=0.1): #flush the read buffer first prevOut = self.com.read(self.com.inWaiting())#read as many chars as are in the buffer
Python
nomic_cornstack_python_v1
function _add_to_dict t container name value begin if name in container begin raise exception string %s '%s' already exists % tuple t name end else begin set container at name = value end end function
def _add_to_dict(t, container, name, value): if name in container: raise Exception("%s '%s' already exists" % (t, name)) else: container[name] = value
Python
nomic_cornstack_python_v1
function compare_averages filename begin set df = read csv filename set df = df at list string name string handedness string avg comment because count() does not count NaN-s comment print(df["handedness"].count()) set df at string handedness = replace df at string handedness string NaN drop missing df axis=0 subset=li...
def compare_averages(filename): df = pandas.read_csv(filename) df = df[["name","handedness","avg"]] #because count() does not count NaN-s #print(df["handedness"].count()) df["handedness"] = df["handedness"].replace("", numpy.NaN) df.dropna(axis = 0, subset=["handedness"],inplace=True) r...
Python
nomic_cornstack_python_v1
try begin from matplotlib import pyplot as plt end except Exception as mnfe begin print mnfe exit end set DEBUG = false if DEBUG begin from numpy import arange from math import sin end class Graphics begin function __init__ self begin set style = list string r string g string b string r-- string g-- string b-- string r...
try: from matplotlib import pyplot as plt except Exception as mnfe: print(mnfe) exit() DEBUG = False if DEBUG: from numpy import arange from math import sin class Graphics: def __init__(self): self.style = [ 'r', 'g', 'b', 'r--', 'g--', 'b--', 'r:', 'g:', 'b:'] def draw(self,...
Python
zaydzuhri_stack_edu_python
function test_valid_validatefile syn genie_config begin set validation_statusdf = call DataFrame set error_trackerdf = call DataFrame set entity = call Entity name=string data_clinical_supp_SAGE.txt id=string syn1234 md5=string 44444 path=string /path/to/data_clinical_supp_SAGE.txt set entity at string modifiedOn = str...
def test_valid_validatefile(syn, genie_config): validation_statusdf = pd.DataFrame() error_trackerdf = pd.DataFrame() entity = synapseclient.Entity( name="data_clinical_supp_SAGE.txt", id="syn1234", md5="44444", path="/path/to/data_clinical_supp_SAGE.txt", ) entity["m...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np function image_feature_extract frame blur_flag feature_enhance_flag begin set blur = call cvtColor frame COLOR_BGR2GRAY if blur_flag begin set blur = call GaussianBlur blur tuple 3 3 0 end set lower = array list 0 0 0 set upper = array list 254 254 254 set mask = call inRange frame lower u...
import cv2 import numpy as np def image_feature_extract(frame, blur_flag, feature_enhance_flag): blur = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if blur_flag: blur = cv2.GaussianBlur(blur, (3, 3), 0) lower = np.array([0, 0, 0]) upper = np.array([254, 254, 254]) mask = cv2.inRa...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string 383 Necklace Matching -- Bonus 2 Got the idea to _canonicalize_ from `skeeto`, who did it in Golang. from __future__ import print_function from sys import argv function canonicalize s begin set strlen = length s set t = s * 2 for i in range 1 strlen beg...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 383 Necklace Matching -- Bonus 2 Got the idea to _canonicalize_ from `skeeto`, who did it in Golang. """ from __future__ import print_function from sys import argv def canonicalize(s): strlen = len(s) t = s*2 for i in range(1,strlen): if s > t[i:(...
Python
zaydzuhri_stack_edu_python
import math print square root 4 from math import sqrt print square root 4
import math print(math.sqrt(4)) from math import sqrt print(sqrt(4))
Python
zaydzuhri_stack_edu_python
function print_word_likelihood_report ref lls bucket_type=string freq bucket_cutoffs=none freq_count_file=none freq_corpus_file=none label_corpus=none label_set=none case_insensitive=false begin set case_insensitive = if expression case_insensitive == string True then true else false set bucketer = call create_word_buc...
def print_word_likelihood_report(ref, lls, bucket_type='freq', bucket_cutoffs=None, freq_count_file=None, freq_corpus_file=None, label_corpus=None, label_set=None, case_insensitive=False): case_insensitive = True if case_insensitive == 'Tru...
Python
nomic_cornstack_python_v1
function read self pin name=none begin import RPi.GPIO as GPIO call _init_board set name = name or pin set pin = call _get_pin_number pin if pin not in _initialized_pins begin setup GPIO pin IN set _initialized_pins at pin = IN end set val = input pin return dict string name name ; string pin pin ; string value val ; s...
def read(self, pin: Union[int, str], name: Optional[str] = None) -> Dict[str, Any]: import RPi.GPIO as GPIO self._init_board() name = name or pin pin = self._get_pin_number(pin) if pin not in self._initialized_pins: GPIO.setup(pin, GPIO.IN) self._initia...
Python
nomic_cornstack_python_v1
function _min_distance segments shapelet begin set J = length segments set distances = zeros J for j in range J begin set distances at j = sum segments at j - shapelet ^ 2 end return min distances end function
def _min_distance(segments, shapelet): J = len(segments) distances = np.zeros(J) for j in range(J): distances[j] = sum((segments[j]-shapelet) ** 2) return min(distances)
Python
nomic_cornstack_python_v1
function strtodatetime isostr begin set tuple left dot fraction = call partition string . set dt = string parse time left string %Y-%m-%dT%H:%M:%S set dt = replace dt tzinfo=UTC return dt end function
def strtodatetime(isostr): left, dot, fraction = isostr.partition('.') dt = datetime.datetime.strptime(left, "%Y-%m-%dT%H:%M:%S") dt = dt.replace(tzinfo=pytz.UTC) return dt
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Spyder Editor This is a temporary script file. import cv2 import numpy as np function image_resize image_name width=1500 height=1500 inter=INTER_AREA begin set image = call imread image_name 0 set dim = none set tuple h w = shape at slice : 2 : if width is none and height is none ...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import cv2 import numpy as np def image_resize(image_name, width = 1500, height = 1500, inter = cv2.INTER_AREA): image= cv2.imread(image_name,0) dim = None (h, w) = image.shape[:2] if width is None and height is None: ...
Python
zaydzuhri_stack_edu_python
import tushare as ts import pymysql set token = string 39eb03a5cc204699bd6338d9ae4cd1d11289f653ddfe4dd061c5c363 set pro = call pro_api token set stock_exchange = list string SSE string SZSE set data = list for exchange in stock_exchange begin set df = call trade_cal exchange=exchange start_date=string 2020101 end_date...
import tushare as ts import pymysql token = '39eb03a5cc204699bd6338d9ae4cd1d11289f653ddfe4dd061c5c363' pro = ts.pro_api(token) stock_exchange = ['SSE', 'SZSE'] data = [] for exchange in stock_exchange: df = pro.trade_cal(exchange=exchange, start_date='2020101', end_date='20210101') data.append(df) conn = pymy...
Python
zaydzuhri_stack_edu_python
function get_batch self batch_size=10 begin set start = end set start = start set end = min start + batch_size num_samples set eff_batch = end - start if end >= num_samples begin set end = 0 end set end = end set data_out_lst = list set latent_net_ids = list for i in range eff_batch begin append data_out_lst data_lst...
def get_batch(self, batch_size=10): self.start = self.end start = self.start end = min(start + batch_size, self.num_samples) eff_batch = end - start if end >= self.num_samples: end = 0 self.end = end data_out_lst = [] latent_net_ids = [] ...
Python
nomic_cornstack_python_v1
function compute_uncertainty self y begin return variance np y end function
def compute_uncertainty(self, y): return np.var(y)
Python
nomic_cornstack_python_v1
function _process_clashes self sites_cart fsc0 begin set clashes_to_be_removed = list for tuple i_seq j_seq_list in call iteritems _mult_clash_dict begin set n_multiples = length j_seq_list if n_multiples <= 1 begin continue end for i in range n_multiples - 1 begin for j in range i + 1 n_multiples begin set multiple_1 ...
def _process_clashes(self, sites_cart, fsc0): clashes_to_be_removed = list() for i_seq, j_seq_list in six.iteritems(self._mult_clash_dict): n_multiples = len(j_seq_list) if n_multiples <= 1: continue for i in range(n_multiples-1): for j in range(i+1, n_multiples): multiple_1 ...
Python
nomic_cornstack_python_v1
string Price a European option by the implicit method of finite difference import numpy as np import scipy.linalg as linalg from FDExplicitEu import FDExplicitEu class FDImplicitEu extends FDExplicitEu begin function _setup_coefficients_ self begin set a = 0.5 * r * dt * i_values - sigma ^ 2 * dt * i_values ^ 2 set b =...
"""Price a European option by the implicit method of finite difference""" import numpy as np import scipy.linalg as linalg from FDExplicitEu import FDExplicitEu class FDImplicitEu(FDExplicitEu): def _setup_coefficients_(self): self.a=0.5*(self.r*self.dt*self.i_values- (self....
Python
zaydzuhri_stack_edu_python
set baseUrl = string www.example.com set product = string apple set url = baseUrl + string /product/ + product print url
baseUrl = "www.example.com" product = "apple" url = baseUrl + "/product/" + product print(url)
Python
greatdarklord_python_dataset
import arcpy import os from collections import OrderedDict comment Helper functions that are shared by the various types of K functions. class KFunctionHelper extends object begin comment Initialize the helper class. function __init__ self begin set permutations = ordered dictionary list tuple string 0 Permutations (No...
import arcpy import os from collections import OrderedDict ### # Helper functions that are shared by the various types of K functions. ### class KFunctionHelper(object): ### # Initialize the helper class. ### def __init__(self): self.permutations = OrderedDict([ ("0 Permutations (No Co...
Python
zaydzuhri_stack_edu_python
function loadConfiguration conf begin set config = config parser read config conf comment Validate contents if string general not in config begin error string No general section in the configuration file. end if string distribution not in config at string general begin error string No distribution function set in the c...
def loadConfiguration(conf): config = configparser.ConfigParser() config.read(conf) # Validate contents if 'general' not in config: smutil.error("No general section in the configuration file.") if 'distribution' not in config['general']: smutil.error("No distribution function set in...
Python
nomic_cornstack_python_v1
import torch import unittest from CNN import Conv , AvgPool from OtherLayers import BatchNorm2d set RANDOM_SEED = 1 class TestLayers extends TestCase begin string Класс для тестирования целевых для этого задания модулей. decorator staticmethod function _generate_test_data shape minval=- 10 maxval=10 begin string Генери...
import torch import unittest from CNN import Conv, AvgPool from OtherLayers import BatchNorm2d RANDOM_SEED = 1 class TestLayers(unittest.TestCase): """Класс для тестирования целевых для этого задания модулей.""" @staticmethod def _generate_test_data(shape, minval=-10, maxval=10): """Генерирует ...
Python
zaydzuhri_stack_edu_python
function collate_fn batch begin set tuple img label shapes = zip *batch for tuple i l in enumerate label begin comment add target image index for build_targets() set l at tuple slice : : 0 = i end return tuple stack img 0 call cat label 0 shapes end function
def collate_fn(batch): img, label, shapes = zip(*batch) for i, l in enumerate(label): l[:, 0] = i # add target image index for build_targets() return torch.stack(img, 0), torch.cat(label, 0), shapes
Python
nomic_cornstack_python_v1
from __future__ import absolute_import from __future__ import print_function from callbacks import supports_callbacks function print_one begin print string 1 end function function print_a begin print string a end function function print_foo begin print string foo end function function print_bar begin print string bar e...
from __future__ import absolute_import from __future__ import print_function from callbacks import supports_callbacks def print_one(): print("1") def print_a(): print("a") def print_foo(): print('foo') def print_bar(): print('bar') @supports_callbacks def target(): pass target.add_callback(pr...
Python
zaydzuhri_stack_edu_python
function rpc_login username password begin if not username and not password begin return false end else begin set validate_user = call validate_username username set validate_bt = call validate_to_biomedtown username password if validate_bt is false begin return false end else begin if validate_user is not true begin s...
def rpc_login(username, password): if not username and not password: return False else: validate_user = validate_username(username) validate_bt = validate_to_biomedtown(username, password) if validate_bt is False: return False else: if validate_...
Python
nomic_cornstack_python_v1
import time set start_time = time function my_sieve n begin set dumb_list = range 0 n set limit = integer n ^ 0.5 for i in call xrange 2 limit begin if dumb_list at i begin set dumb = n - 1 / i - 1 set dumb_list at slice i + i : : i = list 0 * dumb end end return filter none dumb_list end function set list_prime = cal...
import time start_time = time.time() def my_sieve(n): dumb_list = range(0, n) limit = int(n ** 0.5) for i in xrange(2, limit): if dumb_list[i]: dumb = (n - 1) / i - 1 dumb_list[i + i :: i] = [0] * dumb return filter(None, dumb_list) list_prime = my_sieve(1000) def factorize(number, dumb_list): dumb =...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup set tuple queue visited = tuple list list
import requests from bs4 import BeautifulSoup queue, visited = [], []
Python
iamtarun_python_18k_alpaca
function test_update_existing_dotted_a_record_succeeds shared_zone_test_context begin set client = ok_vinyldns_client set zone = ok_zone set recordsets = call list_recordsets_by_zone zone at string id record_name_filter=string dotted.a status=200 at string recordSets set update_rs = recordsets at 0 set update_rs at str...
def test_update_existing_dotted_a_record_succeeds(shared_zone_test_context): client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.ok_zone recordsets = client.list_recordsets_by_zone(zone["id"], record_name_filter="dotted.a", status=200)["recordSets"] update_rs = recordse...
Python
nomic_cornstack_python_v1
import os function mult a b begin set l = length a comment recursion end at 16 bit (2 bytes) if l == 2 begin set result = call to_bytes 4 byteorder=string big return result end set ah = a at slice 0 : integer l / 2 : set al = a at slice integer l / 2 : l : set bh = b at slice 0 : integer l / 2 : set bl = b at slice ...
import os def mult(a, b): l = len(a) # recursion end at 16 bit (2 bytes) if (l == 2): result = (int.from_bytes(a, byteorder = 'big')*int.from_bytes(b, byteorder = 'big')).to_bytes(4, byteorder = 'big') return result ah = a[0:int(l/2)] al = a[int(l/2): l] bh = b[0:int(l/2)] ...
Python
zaydzuhri_stack_edu_python
import tkinter as tk from tkinter import * import datetime import numpy as np import matplotlib.pyplot as plt import pandas as pd from fractions import Fraction from tkinter import Listbox import tkinter import matplotlib from tkinter import messagebox call use string TkAgg from matplotlib.backends.backend_tkagg import...
import tkinter as tk from tkinter import * import datetime import numpy as np import matplotlib.pyplot as plt import pandas as pd from fractions import Fraction from tkinter import Listbox import tkinter import matplotlib from tkinter import messagebox matplotlib.use('TkAgg') from matplotlib.backends.backen...
Python
zaydzuhri_stack_edu_python
string a ideia e calcular quanto vai sobrar no fim do mes print salario - despesas print string fim de verdade
""" a ideia e calcular quanto vai sobrar no fim do mes """ print (salario - despesas) print ('fim de verdade')
Python
zaydzuhri_stack_edu_python
from Parser import * from Node import * class KnowledgeBase begin string Knowledge base that stores information in propositional logic function __init__ self begin set clauses = list set parser = call Parser end function function feed_sentence self data begin set sentence = process data append clauses sentence end fun...
from Parser import * from Node import * class KnowledgeBase: """ Knowledge base that stores information in propositional logic """ def __init__(self): self.clauses = [] self.parser = Parser() def feed_sentence(self, data): sentence = self.parser.process(data) self.c...
Python
zaydzuhri_stack_edu_python
function even_odd n begin if n % 2 == 0 begin return true end else begin return false end end function
def even_odd(n): if n % 2 == 0: return True else: return False
Python
iamtarun_python_18k_alpaca
string Title: Object Detection with RetinaNet Author: [Srihari Humbarwadi](https://twitter.com/srihari_rh) Date created: 2020/05/17 Last modified: 2020/07/14 Description: Implementing RetinaNet: Focal Loss for Dense Object Detection. string ## Introduction Object detection a very important problem in computer vision. H...
""" Title: Object Detection with RetinaNet Author: [Srihari Humbarwadi](https://twitter.com/srihari_rh) Date created: 2020/05/17 Last modified: 2020/07/14 Description: Implementing RetinaNet: Focal Loss for Dense Object Detection. """ """ ## Introduction Object detection a very important problem in computer vision. H...
Python
zaydzuhri_stack_edu_python
from django.utils.translation import ugettext_lazy as _ , ugettext import xlwt function get_styles begin set bold = call easyfont string bold true, height 220, name Helvetica Neue set brown = call easyfont string color_index brown, name Helvetica Neue, height 220 set italic = call easyfont string color_index gray50, it...
from django.utils.translation import ugettext_lazy as _, ugettext import xlwt def get_styles(): bold = xlwt.easyfont('bold true, height 220, name Helvetica Neue') brown = xlwt.easyfont('color_index brown, name Helvetica Neue, height 220') italic = xlwt.easyfont('color_index gray50, italic true, name Helve...
Python
zaydzuhri_stack_edu_python
function today tz=none begin return call date end function
def today(tz=None): return now(tz=tz).date()
Python
nomic_cornstack_python_v1
function storage_encrypted self begin return get pulumi self string storage_encrypted end function
def storage_encrypted(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "storage_encrypted")
Python
nomic_cornstack_python_v1
function _define_decoder self begin raise NotImplementedError end function
def _define_decoder(self): raise NotImplementedError
Python
nomic_cornstack_python_v1
class Laboratorio begin function __init__ self numero horario dia nmonitores begin set numero = numero set monitores = list numero set horario = horario set dia = dia set nmonitores = nmonitores end function function adicionamonitor self monitor begin append monitores monitor end function end class
class Laboratorio: def __init__(self, numero, horario, dia, nmonitores): self.numero = numero self.monitores = [numero] self.horario = horario self.dia = dia self.nmonitores = nmonitores def adicionamonitor(self,monitor): self....
Python
zaydzuhri_stack_edu_python
import numpy as np import csv function read_paper txt_name begin set f = open txt_name set entry = dict set paper_time_dict = dict set count = 0 while true begin set line = read line f if line == string begin set author_set = split author_set string , set entry at paper_index = author_set set paper_time_dict at pape...
import numpy as np import csv def read_paper(txt_name): f = open(txt_name) entry = {} paper_time_dict = {} count = 0 while True: line = f.readline() if line == '\n': author_set = author_set.split(',') entry[paper_index] = author_set paper_time_di...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sys function solve N begin set l = length string N set k = dict for i in range 1 10 begin for j in range 1 10 begin set k at string i + string j = 0 end end for x in range 1 N + 1 begin set s = string x if s at - 1 != string 0 begin set k at s at 0 + s at - 1 = k at s at 0 + s at -...
#!/usr/bin/env python3 import sys def solve(N: int): l = len(str(N)) k = {} for i in range(1,10): for j in range(1,10): k[str(i)+str(j)] = 0 for x in range(1, N+1): s = str(x) if s[-1] != "0": k[s[0]+s[-1]] += 1 k_new = {} for i in range(1,10): ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt comment has m=442 sample stars with X and Y coordinates given n=2 labels, or features set dataset = call genfromtxt string dataset_LATTE.txt set features = dataset at tuple slice : : slice : 2 : set m = shape at 0 set n = shape at 0 comment feature scaling functio...
import numpy as np import matplotlib.pyplot as plt # has m=442 sample stars with X and Y coordinates given n=2 labels, or features dataset=np.genfromtxt("dataset_LATTE.txt") features=dataset[:,:2] m=features.shape[0] n=features[0].shape[0] #feature scaling def rescale(x): return (x-np.mean(x))/np.std(x) r...
Python
zaydzuhri_stack_edu_python
function calculate_total_paintings begin comment Existing paintings set philip_existing_paintings = 20 set amelia_existing_paintings = 45 comment Number of weeks set weeks = 5 comment Calculate Philip's weekly output comment (Mon + Tue) + (Wed) + (Thu + Fri) set philip_weekly_paintings = 3 * 2 + 2 + 5 * 2 comment Total...
def calculate_total_paintings(): # Existing paintings philip_existing_paintings = 20 amelia_existing_paintings = 45 # Number of weeks weeks = 5 # Calculate Philip's weekly output philip_weekly_paintings = (3 * 2) + 2 + (5 * 2) # (Mon + Tue) + (Wed) + (Thu + Fri) # Total p...
Python
dbands_pythonMath
function bubble_sort_descending arr begin set n = length arr for i in range n begin for j in range 0 n - i - 1 begin if arr at j < arr at j + 1 begin set tuple arr at j arr at j + 1 = tuple arr at j + 1 arr at j end end end end function comment Test the function set lst = list 5 10 3 8 1 7 2 9 4 6 call bubble_sort_desc...
def bubble_sort_descending(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] < arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] # Test the function lst = [5, 10, 3, 8, 1, 7, 2, 9, 4, 6] bubble_sort_descending(lst) print(lst) # Output: [10, 9, 8, 7, 6, 5...
Python
jtatman_500k
function sample_until_unique self sampleFromSeq sampleLim=integer 1000000.0 begin comment NOTE: If 'sampleLim' is set to 'infty' , the result may be an infinite loop if the Counter has a key for each 'sampleFromSeq' set trial = 1 while trial <= sampleLim begin set testKey = random choice sampleFromSeq if self at testKe...
def sample_until_unique( self , sampleFromSeq , sampleLim = int( 1e6 ) ): # NOTE: If 'sampleLim' is set to 'infty' , the result may be an infinite loop if the Counter has a key for each 'sampleFromSeq' trial = 1 while( trial <= sampleLim ): testKey = choice( sampleFromSeq ) ...
Python
nomic_cornstack_python_v1
function residue_subsystem begin set net = call residue_network set state = tuple 0 0 0 0 0 return call Subsystem net state end function
def residue_subsystem(): net = residue_network() state = (0, 0, 0, 0, 0) return Subsystem(net, state)
Python
nomic_cornstack_python_v1
comment -> DemezKeyValue: function AddItemSingle self key value=string begin set sub_dkv = call GetItem key if not sub_dkv begin set sub_dkv = call DemezKeyValue self key value file_path=file_path append value sub_dkv end else begin set value = value end return sub_dkv end function
def AddItemSingle(self, key: str, value=""): # -> DemezKeyValue: sub_dkv = self.GetItem(key) if not sub_dkv: sub_dkv = DemezKeyValue(self, key, value, file_path=self.file_path) self.value.append(sub_dkv) else: sub_dkv.value = value return sub_dkv
Python
nomic_cornstack_python_v1
function withMinor self integer begin Ellipsis end function
def withMinor(self, integer: int) -> 'DefaultDeviceTypeVersionNumberDto': ...
Python
nomic_cornstack_python_v1
function IGetEdges self begin set ret = call InvokeTypes 26 LCID 1 tuple 9 0 tuple if ret is not none begin set ret = call Dispatch ret string IGetEdges string {83A33D42-27C5-11CE-BFD4-00400513BB57} end return ret end function
def IGetEdges(self): ret = self._oleobj_.InvokeTypes(26, LCID, 1, (9, 0), (),) if ret is not None: ret = Dispatch(ret, u'IGetEdges', '{83A33D42-27C5-11CE-BFD4-00400513BB57}') return ret
Python
nomic_cornstack_python_v1
function query self query begin set response = post string %s/ws/search % call geturl data=dict string limit TARGET_NUMBER_OF_RESULTS ; string index index_number ; string query payload set parser = call XMLParser encoding=string utf-8 recover=true set response_element = call fromstring content parser=parser assert is i...
def query(self, query): response = requests.post("%s/ws/search" % self.url.geturl(), data={ "limit": TARGET_NUMBER_OF_RESULTS, "index": self.index_number, "query": query.payload, }) parser = XMLParser(encoding="utf-8", recover=True) response_element = ...
Python
nomic_cornstack_python_v1
function _get_images_path self begin if dataset == value begin return RSICD_PATH end else if dataset == value begin return UCM_PATH end else if dataset == value begin return SYDNEY_PATH end else begin error string Wrong dataset // SUPPORTED : rsicd, ucm or sydney end end function
def _get_images_path(self): if self.dataset == DATASETS.RSICD.value: return RSICD_PATH elif self.dataset == DATASETS.UCM.value: return UCM_PATH elif self.dataset == DATASETS.SYDNEY.value: return SYDNEY_PATH else: logging.error("Wrong datase...
Python
nomic_cornstack_python_v1
function __radd__ self that begin return call __opExpand2 that add end function
def __radd__(self,that): return self.__opExpand2(that,np.add)
Python
nomic_cornstack_python_v1
set s = string Life is too short, You need Python print find s string short print set s = string Eighty percent of $ucce$$ is Showing up. set s = replace s string $ string s print s print set s = string Life is too short, You need Python print split s print
s = 'Life is too short, You need Python' print(s.find('short')) print() s = 'Eighty percent of $ucce$$ is Showing up.' s = s.replace('$', 's') print(s) print() s = 'Life is too short, You need Python' print(s.split()) print()
Python
zaydzuhri_stack_edu_python
function predictResults self cases a begin set predictions = list for c in cases begin set outcome = call predictResultsRecurse c attributes append predictions outcome end return predictions end function
def predictResults(self, cases, a): predictions = [] for c in cases: outcome = self.predictResultsRecurse(c, attributes) predictions.append(outcome) return predictions
Python
nomic_cornstack_python_v1
from modules.CarControl import CarControl set car = call CarControl class CarAutoPilotByPredict extends object begin comment 控制小車(前,左,右)。 function steer self prediction begin comment 2 : 道路直線的圖片 comment 當預測到 "道路直線的圖片" if prediction == 0 begin comment 讓車子直行 call Forward 60 60 print string Forward end else comment 當預測到 "...
from modules.CarControl import CarControl car = CarControl() class CarAutoPilotByPredict(object): def steer(self, prediction): # 控制小車(前,左,右)。 ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import gzip function parse path begin set g = open path string rb for l in g begin yield eval l end end function function getDF path begin set i = 0 set df = dict for d in parse path begin set df at i = d end end function
import pandas as pd import gzip def parse(path): g = gzip.open(path, 'rb') for l in g: yield eval(l) def getDF(path): i = 0 df = {} for d in parse(path): df[i] = d
Python
zaydzuhri_stack_edu_python
function pc_noutput_items_var self begin return call randomiser_softbits_sptr_pc_noutput_items_var self end function
def pc_noutput_items_var(self): return _ccsds_swig.randomiser_softbits_sptr_pc_noutput_items_var(self)
Python
nomic_cornstack_python_v1
function calcQTable self state action returnFeatures=false network=none begin if network is none begin set network = target end set features = call process_state state action comment + self.qBias set qValue = decimal predict network array list features if returnFeatures begin return tuple qValue features end return qVa...
def calcQTable(self,state,action,returnFeatures=False,network=None): if network is None: network = self.target features = self.process_state(state,action) qValue = float(network.predict(np.array([features]))) #+ self.qBias if returnFeatures: return qValue...
Python
nomic_cornstack_python_v1
import serial from oauthlib.oauth2 import BackendApplicationClient from oauthlib.oauth2 import TokenExpiredError from requests_oauthlib import OAuth2Session import requests import datetime comment import all the neccessary libraries set PORT = string /dev/ttyUSB0 set BAUDRATE = string 115200 comment define the port and...
import serial from oauthlib.oauth2 import BackendApplicationClient from oauthlib.oauth2 import TokenExpiredError from requests_oauthlib import OAuth2Session import requests import datetime # import all the neccessary libraries PORT = "/dev/ttyUSB0" BAUDRATE = "115200" # define the port and the baudrate ser = seri...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup import re import http.client import json import codecs function crawl_proxy page begin string 获取代理列表 :return: proies set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46...
# -*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup import re import http.client import json import codecs def crawl_proxy(page): """ 获取代理列表 :return: proies """ headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrom...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web call use string ggplot set df = read csv string pure alcohol available for consumption.csv index_col=0 plot linewidth=2 y label string Litres (in millions) x label string Year title plt string Volume of...
import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web style.use('ggplot') df=pd.read_csv('pure alcohol available for consumption.csv',index_col = 0) df.plot(linewidth=2) plt.ylabel('Litres (in millions)') plt.xlabel('Year') plt.title('Volume of pure al...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 string The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? 1456 import primeutils...
# coding=utf-8 """ The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? 1456 """ import primeutils ...
Python
zaydzuhri_stack_edu_python
function GetIter self WANTED_REF=none WANTED_SUBTYPE=none begin if WANTED_REF == none begin for this_ref in ref_base begin if WANTED_SUBTYPE == none ? tested_subtype == WANTED_SUBTYPE begin for this_test in test_names begin yield my_map_shelf at seq_name + this_test end end end end else begin for this_test in test_name...
def GetIter(self, WANTED_REF = None, WANTED_SUBTYPE = None): if WANTED_REF == None: for this_ref in self.ref_base: if (WANTED_SUBTYPE == None) | (this_ref.tested_subtype == WANTED_SUBTYPE): for this_test in self.test_names: yield self.my_map_shelf[this_ref.seq_name+this_test] else: ...
Python
nomic_cornstack_python_v1
import string set n = integer input set ans = list while i >= 0 begin set tuple q mod = divide mod n 26 ^ i append ans q - 1 set n = mod set i = i - 1 end print ans set s = string for a in ans begin set s = s + ascii_lowercase at a end print s
import string n = int(input()) ans = [] while i >= 0: q, mod = divmod(n, 26 ** i) ans.append(q - 1) n = mod i -= 1 print(ans) s = "" for a in ans: s += string.ascii_lowercase[a] print(s)
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 import os class OsUse extends object begin function __init__ self input_path file_name begin set __input_path = input_path set __file_name = file_name set __dir_path = none set __file_path = none end function function search_other self begin comment self.__input_path.split(os.sep) 使用操作系统路径分隔符分割得到 c...
# coding:utf-8 import os class OsUse(object): def __init__(self, input_path, file_name): self.__input_path = input_path self.__file_name = file_name self.__dir_path = None self.__file_path = None def search_other(self): # self.__input_path.split(os.sep) 使用操作系统路径分隔符分割...
Python
zaydzuhri_stack_edu_python
comment g.append(s[int(k)-1]) for i in range 0 length s begin if s at i == a begin set f = i end end for i in range f length s integer k begin append g s at i end print *g
#g.append(s[int(k)-1]) for i in range(0,len(s)): if s[i]==a: f=i for i in range(f,len(s),int(k)): g.append(s[i]) print(*g)
Python
zaydzuhri_stack_edu_python
class Node begin set RED = true set BLACK = false function __init__ self key val color begin set left = none set right = none set key = key set value = val set color = color end function end class class RedBlackBST begin function __init__ self begin set root = none end function function put self key val begin set root ...
class Node: RED = True BLACK = False def __init__(self, key, val, color): self.left = None self.right = None self.key = key self.value = val self.color = color class RedBlackBST: def __init__(self): self.root = None de...
Python
zaydzuhri_stack_edu_python
function TestDict begin set thisdict = dict string brand string Ford ; string model string Mustang ; string year 1964 print thisdict comment accessing elements set x = thisdict at string model print x set x = get thisdict string model print x comment change values set thisdict at string year = 2018 print thisdict clear...
def TestDict(): thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 } print (thisdict) # accessing elements x = thisdict["model"] print(x) x = thisdict.get("model") print(x) #change values thisdict["year"] = 2018 print(thisdict) thisdict.clear() print(thisdict) TestDict()
Python
zaydzuhri_stack_edu_python
function readXML filePath begin set tree = parse ET filePath set root = get root tree set paras = list if string full-text-retrieval-response in tag begin for para in find all string .//xocs:rawtext ns_fulltext begin append paras text end end for para in find all string .//ce:sections//ce:para ns_doc begin append para...
def readXML(filePath): tree = ET.parse(filePath) root = tree.getroot() paras = [] if "full-text-retrieval-response" in root.tag: for para in root.findall(".//xocs:rawtext", ns_fulltext): paras.append(para.text) for para in root.findall(".//ce:sections//ce:para", ns_doc): paras.append(getNodeText...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment @Time : 2018/10/21 21:13 comment @Author : Administrator comment @Site : comment @File : Python练习实例28.py comment @Software: PyCharm string 题目: 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大? ------...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2018/10/21 21:13 # @Author : Administrator # @Site : # @File : Python练习实例28.py # @Software: PyCharm """ 题目: 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大? ------------------------------------...
Python
zaydzuhri_stack_edu_python
from torch.utils.data import Dataset import pickle class EncodingsDataset extends Dataset begin function __init__ self encodings transform=none begin string Args: encodings (string) - path to a .pickle file, output of encode_faces.py transform (callable, optional) - optional transform to be performed set samples = list...
from torch.utils.data import Dataset import pickle class EncodingsDataset(Dataset): def __init__(self, encodings, transform=None): ''' Args: encodings (string) - path to a .pickle file, output of encode_faces.py transform (callable, optional) - optional transform to be perfo...
Python
zaydzuhri_stack_edu_python
function make_particles input_file positive=false begin set particles = list for line in input_file begin comment each line is of the form p=<x,y,z>, v=x,y,z>, a=<x,y,z> set tuple point_str velocity_str accel_str = split strip line string string , set point = map int split point_str at slice 3 : - 1 : string , set ve...
def make_particles(input_file, positive=False): particles = [] for line in input_file: #each line is of the form p=<x,y,z>, v=x,y,z>, a=<x,y,z> point_str, velocity_str, accel_str = line.strip("\n").split(", ") point = map(int, point_str[3:-1].split(",")) velocity = map(int, vel...
Python
nomic_cornstack_python_v1
import numpy as np from itertools import chain from keras.applications.vgg16 import preprocess_input from keras.preprocessing import image from keras.models import load_model import os import tensorflow as tf set environ at string TF_CPP_MIN_LOG_LEVEL = string 3 from tensorflow.python.util import deprecation set _PRINT...
import numpy as np from itertools import chain from keras.applications.vgg16 import preprocess_input from keras.preprocessing import image from keras.models import load_model import os import tensorflow as tf os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from tensorflow.python.util import deprecation deprecation._PRINT_DEPR...
Python
zaydzuhri_stack_edu_python
function myMap func list begin set listA = list for x in list begin append listA call func x print listA end return listA end function function func x begin return x * 5 end function call myMap func list 1 2 3 4 5
def myMap(func,list): listA = [] for x in list: listA.append(func(x)) print(listA) return listA def func(x): return x*5 myMap(func,[1,2,3,4,5])
Python
zaydzuhri_stack_edu_python
function _onchange_exchange_product self begin set values = dict string quantity false ; string price_unit false ; string uom_id false set line = sale_line_id or purchase_line_id if exchange_product_id begin update values dict string quantity product_uom_qty ; string price_unit lst_price ; string uom_id id end else beg...
def _onchange_exchange_product(self): values = { 'quantity': False, 'price_unit': False, 'uom_id': False, } line = self.move_id.sale_line_id or self.move_id.purchase_line_id if self.exchange_product_id: values.update({ ...
Python
nomic_cornstack_python_v1
function take_exposure self seconds=1.0 * second filename=none dark=false blocking=false *args **kwargs begin assert is_connected msg error string Camera must be connected for take_exposure! assert filename is not none msg warning string Must pass filename for take_exposure if not is instance seconds Quantity begin set...
def take_exposure(self, seconds=1.0 * u.second, filename=None, dark=False, blocking=False, *args, **kwargs): assert self.is_connected, self.logger.error("Camera must be connected f...
Python
nomic_cornstack_python_v1
class Difference begin function __init__ self a begin set __elements = a set maximumDifference = 0 set elements = a end function function computeDifference self begin global maximumDifference set maximumDifference = 0 set i = 0 while i < length a begin for j in range i + 1 length a begin if maximumDifference < absolute...
class Difference: def __init__(self, a): self.__elements = a self.maximumDifference = 0 self.elements = a def computeDifference(self): global maximumDifference maximumDifference = 0 i = 0 while i < len(a): for j in range((i + 1), len(a)): ...
Python
zaydzuhri_stack_edu_python
function methylation_array_kcv dataset model_class model_params output_target k=10 verbose=0 callbacks=list begin set tuple test_accuracies val_accuracies = tuple list list for i in range k begin set tuple training_set test_set validation_set = call split_methylation_array_by_pheno dataset output_target set model = c...
def methylation_array_kcv(dataset, model_class, model_params, output_target, k=10, verbose=0, callbacks=[]): test_accuracies, val_accuracies = [], [] for i in range(k): training_set, test_set, validation_set = split_methylation_array_by_pheno(dataset, output_target) model = model_class(**model_p...
Python
nomic_cornstack_python_v1
import sys from itertools import combinations_with_replacement as cb set input = readline if __name__ == string __main__ begin set tuple N M = map int split strip input set nums = sorted set map int split strip input for e in sorted set call cb nums M begin print join string map str e end end
import sys from itertools import combinations_with_replacement as cb input = sys.stdin.readline if __name__ == '__main__': N, M = map(int, input().strip().split()) nums = sorted(set(map(int, input().strip().split()))) for e in sorted(set(cb(nums, M))): print(' '.join(map(str, e)))
Python
zaydzuhri_stack_edu_python
comment Hourly wage calculation print string Hourly wages and monthly income print string hours | 9/hr | 12/hr |15/hr for i in range 1 41 begin comment Hours times 4 weeks print i string | 36 * i string | 48 * i string | 60 * i end
#Hourly wage calculation print('Hourly wages and monthly income') print('hours\t| 9/hr\t| 12/hr\t|15/hr') for i in range(1, 41): #Hours times 4 weeks print(i, '\t|', 36*i, '\t|', 48*i, '\t|', 60*i)
Python
zaydzuhri_stack_edu_python